<template>
    <nav class="v-nav-menu__h3">
        <div class="submenu v-nav-menu__scroll">
            <slot></slot>
            <ul class="nav-list">
                <tree-node
                        v-for="node in internalNodeList"
                        :node="node"
                        :data-maps="internalDataMap"
                        :active-menu-key="internalActiveMenuKey"
                        @change-active-menu="changeActiveMenu"
                        :isHref="node.isHref"
                        :key="node.id"
                        :isClickReload="isClickReload"
                        :favorite="favorite"
                        :favorite-list="favoriteList"
                        :favorite-click="favoriteClick"
                >
                </tree-node>
            </ul>
        </div>
    </nav>
</template>

<script>
    import TreeNode from './tree-node.vue'

    export default{
        name: 'v-nav-menu',
        components: {
            TreeNode
        },
        props: {
            nodeList: {
                require: true,
                type: Array
            },

            defaultExpandedKeys: {
                type: Array,
                default: function () {
                    return []
                }
            },

            isExpandAll: {
                type: Boolean
            },

            // 当前选中的菜单
            activeMenuKey: [String, Number],

            // true 将会触发 路由改变事件
            isClickReload:[Boolean],

            // 是否有收藏功能
            favorite:{
                type:Boolean,
                default:false
            },

            // 已收藏的列表（存储的是菜单id）
            favoriteList:{
                type:Array,
                default:function () {
                    return [];
                }
            },

            // 收藏、取消收藏回调
            favoriteClick:Function
        },
        data(){
            return {
                internalNodeList: [],

                // 数据映射
                dataMaps: {},

                internalDataMap: {},


                // 当前选中的key
                internalActiveMenuKey: this.activeMenuKey
            }
        },
        methods: {
            // 数据初始化
            nodeListInit(nodeList){

                Object.assign(this.internalNodeList, nodeList);

                this.setInternalNodeList(this.internalNodeList, true);

            },

            // 内部数据初始化（递归）
            setInternalNodeList(nodes, isLeaf){

                var self = this;

                var nodes2 = isLeaf ? nodes : nodes.childNode;

                nodes2.map((item, index) => {

                    item.hasChild = false;

                    item.isLeaf = isLeaf ? isLeaf : false;

                    if (!isLeaf) item.parentId = nodes.id;

                    if (Array.isArray(item.childNode) && item.childNode.length > 0) {
                        item.hasChild = true;

                        self.setInternalNodeList(item);
                    }

                    self.setDataMap(item);
                })
            },

            // 给 dataMap 赋值（子节点不复制）
            setDataMap(item){
                var entity = {};
                for (var attr in item) {
                    if (attr === "childNode") {
                        continue;
                    }
                    entity[attr] = item[attr];
                }

                this.dataMaps[item.id] = entity;
            },


            expands(){
                if (this.isExpandAll) {

                    this.expandAll();
                } else {
                    this.setExpandedNode();
                }

                this.internalDataMap = this.dataMaps;
            },

            // 设置要打开节点
            setExpandedNode(){
                var self = this;
                if (Array.isArray(self.defaultExpandedKeys) && self.defaultExpandedKeys.length > 0) {
                    self.defaultExpandedKeys.forEach(key => {
                        self.expandByKey(key);
                    })
                }
            },

            // 展开全部
            expandAll(){
                if (this.dataMaps) {

                    for (var item in this.dataMaps) {
                        this.dataMaps[item].isExpand = true;
                    }

                }
            },

            // 设置当前key对应的所有父级节点为打开状态
            expandByKey(key){
                var self = this;

                if (self.dataMaps[key]) {
                    self.dataMaps[key].isExpand = true;

                    if (!self.dataMaps[key].isLeaf) {
                        self.expandByKey(self.dataMaps[key].parentId)
                    }
                }
            },

            setInternalActiveMenuKey(){
                this.internalActiveMenuKey = this.activeMenuKey;
            },

            // 改变选中菜单
            changeActiveMenu(key){

                this.internalActiveMenuKey = key;

                let currentNode = this.dataMaps[key];

                this.$emit('change-active-menu', currentNode);
            },

            // 根据linkTo 获取key
            getKeysByLinkTo(linkTo){
                var keys = [];

                for (var attr in this.dataMaps) {

                    // 模糊匹配（顶级路由匹配即可）
                    if (this.dataMaps[attr].isLikeMatch){

                        let link1 = linkTo.split('/'),
                            link2 = this.dataMaps[attr]['linkTo'].split('/');

                        if (Array.isArray(link1) && link1.length > 0 && Array.isArray(link2) && link2.length > 0){

                            if (link1[1] === link2[1]){

                                keys.push(this.dataMaps[attr].id);
                            }
                        }
                    }else if (this.dataMaps[attr]['linkTo'] === linkTo){

                        keys.push(this.dataMaps[attr].id);
                    }
                }

                return keys;
            },

            // 如果是vue 路由，路由改变时选中以及展开（刷新时）根据路由决定
            routerChange(to){
                var keys = this.getKeysByLinkTo(to.path)

                if (Array.isArray(keys) && keys.length > 0) {

                    this.internalActiveMenuKey = keys[0];

                    if (Array.isArray(this.defaultExpandedKeys)) {

                        if (!this.defaultExpandedKeys.includes(keys[0])) {
                            this.defaultExpandedKeys.push(keys[0]);
                        }

                    } else {
                        this.defaultExpandedKeys.push(keys[0]);
                    }

                }else{
                    this.internalActiveMenuKey = "The route does not match the menu !"
                }

            },

            // 对外提供的方法
            getCurrentNodeByKey(key){

                return this.internalDataMap[key];
            }
        },

        created(){

            // 数据初始化
            this.nodeListInit(this.nodeList);

        },

        watch: {
            'nodeList': function (newVal) {
                this.nodeListInit(newVal);
            },

            'activeMenuKey': function (newVal) {
                this.internalActiveMenuKey = newVal;
            },

            '$route' (to, from) {

                this.routerChange(to);

                this.expands();
            }
        }
    }
</script>