import { setStore, getStore } from 'utils/store';
import website from '@/config/website';

const tagWel = website.fistPage;
const navs = {
  state: {
    tagList: getStore({ name: 'tagList' }) || [],
    tag: getStore({ name: 'tag' }) || {},
    tagWel: tagWel,
  },
  mutations: {
    ADD_TAG: (state, action) => {
      if (typeof action.name == 'function') action.name = action.name(action.query);
      state.tag = action;
      setStore({ name: 'tag', content: state.tag });
      const tagItem = state.tagList.find(ele => ele.fullPath == action.fullPath);
      if (tagItem) {
        // 同键标签允许以新参数再次进入，原位刷新避免参数固化在首次值
        tagItem.query = action.query;
        tagItem.params = action.params;
        tagItem.meta = action.meta;
        setStore({ name: 'tagList', content: state.tagList });
        return;
      }
      state.tagList.push(action);
      setStore({ name: 'tagList', content: state.tagList });
    },
    SET_TAG: (state, action) => {
      const idx = state.tagList.findIndex(item => item.fullPath === action.fullPath);
      if (idx === -1) return;
      const updated = { ...state.tagList[idx], ...action };
      state.tagList.splice(idx, 1, updated);
      if (state.tag?.fullPath === action.fullPath) {
        state.tag = updated;
        setStore({ name: 'tag', content: state.tag });
      }
      setStore({ name: 'tagList', content: state.tagList });
    },
    DEL_TAG: (state, action) => {
      state.tagList = state.tagList.filter(item => {
        return item.fullPath !== action.fullPath;
      });
      setStore({ name: 'tagList', content: state.tagList });
    },
    DEL_ALL_TAG: (state, tagList = []) => {
      state.tagList = tagList;
      setStore({ name: 'tagList', content: state.tagList });
    },
    DEL_TAG_OTHER: state => {
      state.tagList = state.tagList.filter(item => {
        return [state.tag.fullPath, website.fistPage.path].includes(item.fullPath);
      });
      setStore({ name: 'tagList', content: state.tagList });
    },
  },
};
export default navs;
