const home = { path: '/home', name: 'Home', title: '首页' };

const state = {
  tagnavs: [home], // 打开的所有菜单{path:'/home',name:'Home',title:'首页',query:{},params:{}}
  cache_page: [] // 设置需要缓存的页面
};

const getters = {
  tagnavs: state => state.tagnavs,
  cache_page: state => state.cache_page
};

const mutations = {
  SET_TAGNAVS(state, data) {
    let push = true;
    for (let i = 0, len = state.tagnavs.length; i < len; i++) {
      if (state.tagnavs[i].id == data.id) {
        push = false;
      }
    }

    if (push) {
      state.tagnavs.push(data);
      localStorage.setItem('tagnavs', JSON.stringify(state.tagnavs));
    }
  },
  REMOVE_TAGNAVS(state, index) {
    state.tagnavs.splice(index, 1);
    localStorage.setItem('tagnavs', JSON.stringify(state.tagnavs));
  },
  CLEAR_TAGNAVS(state) {
    state.tagnavs = [home];
    localStorage.setItem('tagnavs', JSON.stringify(state.tagnavs));
  },

  SET_CACH_PAGE(state, data) {
    state.cache_page = data;
  }
};

const actions = {
  /**
    * //设置缓存页面
    * @param state
    * @param commit
    */
  getCachPage({ state, commit }) {
    const tagnavs = state.tagnavs;
    let cache_page = [];
    if (tagnavs.length) {
      tagnavs.forEach(item => {
        if (!['Home', 'Iframe'].includes(item.name)) {
          cache_page.push(item.name);
        }
      });
    }
    commit('SET_CACH_PAGE', cache_page);
  }
};

export default{
  state,
  getters,
  mutations,
  actions
};
