import cache from "@/utils/cache";
import { diff } from "@/utils/util";
import website from "@/const/website";
import { ITagType } from "@/const/interface_type";
import { ref } from "vue";

const isFirstPage = website.isFirstPage;
const tagWel = website.fistPage;
const tagObj = ref<ITagType>({
  label: "", // 标题名称
  value: "", // 标题的路径
  params: "", // 标题的路径参数
  query: "" // 标题的参数
  // group: [] // 分组
});

// 处理首个标签
function setFistTag(list: ITagType[]) {
  if (list.length === 1) {
    list[0].close = false;
  } else {
    list.forEach((ele) => {
      if (ele.value === tagWel.value && isFirstPage === false) {
        ele.close = false;
      } else {
        ele.close = true;
      }
    });
  }
}
export default {
  state: () => ({
    tagList: cache.session.getJSON("tagList") || [],
    tag: cache.session.getJSON("tag") || tagObj,
    tagWel: tagWel
  }),
  mutations: {
    ADD_TAG: (state: any, action: ITagType) => {
      state.tag = action;
      cache.session.setJSON("tag", state.tag);
      if (state.tagList.some((ele: any) => diff(ele, action))) return;
      state.tagList.push(action);
      setFistTag(state.tagList);
      cache.session.setJSON("tagList", state.tagList);
    },
    DEL_TAG: (state: any, action: ITagType) => {
      state.tagList = state.tagList.filter((item: ITagType) => {
        return !diff(item, action);
      });
      setFistTag(state.tagList);
      cache.session.set("tagList", state.tagList);
    },
    DEL_ALL_TAG: (state: any) => {
      state.tagList = [state.tagWel];
      cache.session.set("tagList", state.tagList);
    },
    DEL_TAG_OTHER: (state: any) => {
      state.tagList = state.tagList.filter((item: ITagType) => {
        if (item.value === state.tag.value) {
          return true;
        } else if (!website.isFirstPage && item.value === website.fistPage.value) {
          return true;
        }
      });
      setFistTag(state.tagList);
      cache.session.set("tagList", state.tagList);
    }
  },
  actions: {}
};
