import { defineStore } from "pinia";
import { store } from "/@/store";
import { cacheType } from "./types";
import { constantMenus } from "/@/router";
import { cloneDeep } from "lodash-unified";
import { RouteConfigs } from "/@/layout/types";
import { ascending, filterTree } from "/@/router/utils";

import {  getVersionDate,
  setVersionDate
} from "/@/utils/auth";


import {
  httpSystemList,
} from "/@/api/user";


export const usePermissionStore = defineStore({
  id: "pure-permission",
  state: () => ({
    systemInfo: {},
    // 静态路由生成的菜单
    constantMenus,
    // 整体路由生成的菜单（静态、动态）
    wholeMenus: [],
    // 深拷贝一个菜单树，与导航菜单不突出
    menusTree: [],
    buttonAuth: [],
    // 缓存页面keepAlive
    cachePageList: [],
    collections: {}
  }),
  actions: {
    setCollections(value) {
      this.collections = value;
    },
    // 获取异步路由菜单
    asyncActionRoutes(routes) {
      this.wholeMenus = filterTree(ascending(this.constantMenus.concat(routes)));
      
      console.log(this.wholeMenus)

      this.menusTree = cloneDeep(filterTree(ascending(this.constantMenus.concat(routes))));

      const getButtonAuth = (arrRoutes: Array<RouteConfigs>) => {
        if (!arrRoutes || !arrRoutes.length) return;
        arrRoutes.forEach((v: RouteConfigs) => {
          if (v.meta && v.meta.authority) {
            this.buttonAuth.push(...v.meta.authority);
          }
          if (v.children) {
            getButtonAuth(v.children);
          }
        });
      };

      getButtonAuth(this.wholeMenus);
    },
    async changeSetting(routes) {
      await this.asyncActionRoutes(routes);
    },
    cacheOperate({ mode, name }: cacheType) {
      switch (mode) {
        case "add":
          this.cachePageList.push(name);
          this.cachePageList = [...new Set(this.cachePageList)];
          break;
        case "delete":
          // eslint-disable-next-line no-case-declarations
          const delIndex = this.cachePageList.findIndex(v => v === name);
          delIndex !== -1 && this.cachePageList.splice(delIndex, 1);
          break;
      }
    },
    async requsetSystemInfo() {
      const { data, code } = await httpSystemList({ page: 1, size: 2 });
      
      if (Number(code) === 0) {
        const { list } = data;
        if (list.length === 1) {
          this.systemInfo = list[0];
        } else if (list.length === 2) {
          if (list[0].sys_type === "VER" && new Date(list[0].addtime).valueOf() > new Date().valueOf()) {
            this.systemInfo = list[1];
          } else {
            this.systemInfo = list[0];
          }
        }

        const versionDate = getVersionDate()
        // 当前最新版本
        const { addtime } = this.systemInfo
        // 1.没有记录过版本日期 2.最新版本日期和记录的版本不一致
        console.log(versionDate, addtime)
        if(!versionDate || addtime !== versionDate){
          setVersionDate(addtime)  // 记录版本
          window.location.reload() // 强制刷新
        }
      } else {
        throw new Error();
      }
    },
    // 清空缓存页面
    clearAllCachePage() {
      this.cachePageList = [];
    }
  }
});

export function usePermissionStoreHook() {
  return usePermissionStore(store);
}

export function removeMenus() {
  const userStore = usePermissionStore();
  userStore.wholeMenus = [
    {
      path: "/welcome",
      component: () => import("/@/views/welcome/index.vue"),
      meta: {
        title: "首页"
      }
    }
  ];
}
