import Vue from 'vue'
import Vuex from 'vuex'
import layout from './modules/layout'
Vue.use(Vuex)

export default new Vuex.Store({
    state: {
        //左侧导航菜单
        menus: [],
        /**
         * 用户信息 {id:'',name:''}
         */
        user: {},
        //记录上一次访问的页面
        fromPath: '',
        //面包屑{label:'',to:''}
        breadcrumbs: [],
        //项目信息{id:'',name:'',groupCode:''}
        projects: [],
        //选择的项目信息
        selectProject: {},
        // token
        ssoToken: ''
    },
    getters: {},
    mutations: {
        updateMenus(state, menus) {
            state.menus = menus;
        },
        updateUser(state, user) {
            state.user = user;
        },
        updateFromPath(state, fromPath) {
            state.fromPath = fromPath;
        },
        /**
         * 更新面包屑数据
         * @param {*} state 
         * @param {*} breadcrumb {label:'',to:'/a'}
         */
        updateBreadcrumbs(state, breadcrumb) {
            var newBreadcrumbs = [];

            find(state.menus);
            //如果从菜单里找到了，说明是从菜单上点击的导航
            if (newBreadcrumbs.length > 0) {
                newBreadcrumbs.reverse();
                state.breadcrumbs = newBreadcrumbs;
                return;
            }

            //找不到时，说明是自定义面包屑，比如在页面内的跳转
            newBreadcrumbs = state.breadcrumbs;
            newBreadcrumbs.push(breadcrumb);
            state.breadcrumbs = newBreadcrumbs;

            //从菜单里找和breadcrumb对应的
            function find(menus) {
                for (let i = 0; i < menus.length; i++) {
                    let currMenu = menus[i];
                    if (currMenu.url == breadcrumb.to) {
                        return currMenu;
                    }
                    if (currMenu.child && currMenu.child.length > 0) {
                        let findMenu = find(currMenu.child);
                        if (findMenu) {
                            newBreadcrumbs.push({
                                label: findMenu.name,
                                to: findMenu.url
                            });
                            return currMenu;
                        }
                    }
                }
                return null;
            };
        },
        updateProjects(state, projects) {
            state.projects = projects;
        },
        updateSelectProject(state, selectProject) {
            state.selectProject = selectProject;
        },
        //注销
        loginOut(state) {
            state.menus = [];
            state.user = {};
            state.fromPath = '';
            state.breadcrumbs = [];
            state.projects = [];
            state.selectProject = {};
        }
    },
    actions: {},
    modules: {
        layout
    }
})