<!-- 以mu-list-item为基础，输出树形列表 -->
<!-- 如数据列表中有代表“全部”的对象，该对象的id不能为0，否则会递归死循环 -->
<!--events-->
    <!--行点击item-clicked，参数(value)-->
<template>
    <mu-list toggle-nested>
        <lj-list-tree-node
                v-for="node in treeData"
                :node="node"
                :key-name="keyName"
                :value-name="valueName"
                :open="nestOpen"
                @item-clicked="itemClicked"/>
    </mu-list>
</template>
<script>
    import LjListTreeNode from "components/lj-list-tree-node";
    export default {
        name: "lj-list-tree",
        components: {LjListTreeNode},
        props: {
            // 数组对象的id名
            keyName: {
                type: String,
                default: "id"
            },
            // 以表示上级id的字段
            parentKeyName: {
                type: String,
                default: "parentid"
            },
            // 文字描述的字段
            valueName: {
                type: String,
                default: "name"
            },
            // nodes: {
            //     type: Array
            // },
            // 数据数组
            dataList: {
                type: Array,
                default: function () {
                    return [];
                }
            },
            // 是否展开折叠
            nestOpen: {
                type: Boolean,
                default: false
            },
            // grade: {
            //     type: Number,
            //     default: 0
            // }
        },
        // data() {
        //     return {
        //         divStyle: {
        //             paddingLeft: "1rem"
        //         }
        //     }
        // },
        computed: {
            treeData() {
                if (this.nodes !== undefined) {
                    return this.nodes;
                }
                let nodeDic = new Map();
                let oriList = this.dataList;
                for (let item of oriList) {
                    let thisParentid = item[this.parentKeyName];
                    if (!nodeDic.has(thisParentid)) {
                        nodeDic.set(thisParentid, []);
                    }
                    nodeDic.get(thisParentid).push(item);
                }
                for (let list of nodeDic.values()) {
                    for (let item of list) {
                        let id = item[this.keyName];
                        if (nodeDic.has(id)) {
                            item.children = nodeDic.get(id);
                        }
                    }
                }
                return nodeDic.get(0);
            }
        },
        methods: {
            itemClicked(item) {
                this.$emit("item-clicked", item);
            }
        }
    }
</script>