import { defineStore } from "pinia";
import { AuthState, CommonMenuItem } from "@/stores/interface";
// import { getAuthButtonListApi, getAuthMenuListApi } from "@/api/modules/login";
import {
  getFlatMenuList,
  getShowMenuList,
  getAllBreadcrumbList,
  getQuickEnterFuncTree,
  getQuickEnterFuncTreeRouter
} from "@/utils";
import { menuRouter } from "@/routers/modules/menuRouter";
import { baseRouter } from "@/routers/modules/baseRouter";
import { salePriceRouter } from "@/routers/modules/salePriceRouter";
import { mattressQtuoteRouter } from "@/routers/modules/mattressQtuoteRouter";
import { bednetQtuoteRouter } from "@/routers/modules/bednetQtuoteRouter";
import { softbedQuoteRouter } from "@/routers/modules/softbedQuoteRouter";
import { semifinprodQuoteRouter } from "@/routers/modules/selmifinprodRouter";
import { erpApiRouter } from "@/routers/modules/erpApiRouter";
import { useUserStore } from "@/stores/modules/user";
import { concat } from "lodash-es";
import { isArray } from "@/utils/is";
import { useLayoutLocalStore } from "@/stores/modules/layoutLocal";

export const useAuthStore = defineStore({
  id: "geeker-auth",
  state: (): AuthState => ({
    // 按钮权限列表
    authButtonList: [],
    // 菜单权限列表
    authMenuList: [],
    // 当前页面的 router name，用来做按钮权限筛选
    routeName: "",
    // 系统选项
    optionList: [],
    commonMenu: []
  }),
  getters: {
    // // 按钮权限列表
    authButtonListGet: state => state.authButtonList,
    authOptionListGet: state => state.optionList,
    // 菜单权限列表 ==> 这里的菜单没有经过任何处理
    authMenuListGet: state => state.authMenuList,
    // 菜单权限列表 ==> 左侧菜单栏渲染，需要剔除 isHide == true
    showMenuListGet: state => getShowMenuList(state.authMenuList),
    // 菜单权限列表 ==> 扁平化之后的一维数组菜单，主要用来添加动态路由
    flatMenuListGet: state => getFlatMenuList(state.authMenuList),
    // 递归处理后的所有面包屑导航列表
    breadcrumbListGet: state => getAllBreadcrumbList(state.authMenuList),
    // 首页常用功能树
    quickEnterFuncTreeGet: state => getQuickEnterFuncTree(state.authMenuList),
    // 首页常用功能树路由
    quickEnterFuncTreeRouter: state => getQuickEnterFuncTreeRouter(state.authMenuList)
  },
  actions: {
    /**
     * @description 按钮权限列表
     */
    async getAuthButtonList() {
      const userStore = useUserStore();
      // const { data } = await getAuthButtonListApi();
      // this.authButtonList = data;
      this.authButtonList = userStore.userInfo.rsltFunids ?? [];
    },
    /**
     * @description 按钮权限列表
     */
    async getAuthOptionList() {
      const userStore = useUserStore();
      // const { data } = await getAuthButtonListApi();
      // this.authButtonList = data;
      this.optionList = userStore.userInfo?.optionList ?? [];
    },
    /**
     * @description 获取菜单列表
     */
    async getAuthMenuList() {
      // const { data } = await getAuthMenuListApi();
      // console.log("getAuthMenuList data :>> ", data);
      // this.authMenuList = data;
      this.authMenuList = concat(
        menuRouter,
        baseRouter,
        salePriceRouter,
        mattressQtuoteRouter,
        bednetQtuoteRouter,
        softbedQuoteRouter,
        semifinprodQuoteRouter,
        erpApiRouter
      );
      console.log("getAuthMenuList authMenuList :>> ", this.authMenuList);
    },
    // Set RouteName
    async setRouteName(name: string) {
      this.routeName = name;
    },
    // // Set GlobalState
    // setGlobalState(...args: ObjToKeyValArray<any>) {
    //   // setGlobalState(...args: ObjToKeyValArray<GlobalState>) {
    //   args && this.$patch({ [args[0]]: args[1] });
    // }
    setCommonMenu(data: string | any) {
      if (isArray(data)) {
        this.commonMenu = data;
      } else {
        let index = this.commonMenu.findIndex((item: any) => item.funid == data);
        if (index == -1) {
          this.commonMenu.push({ funid: data });
        } else {
          this.commonMenu.splice(index, 1);
        }
      }
    },
    getQuickEnterFunc(layout: any) {
      let initParam: any = {};
      for (const key in layout) {
        if (isArray(layout[key])) {
          let arr = layout[key];
          for (let i = 0; i < arr.length; i++) {
            console.log("arr[i] :>> ", arr[i]);
            if (arr[i].id == "QuickEnter") {
              initParam = arr[i]?.initParam ?? {};
              break;
            }
          }
        }
      }
      return initParam;
    },
    async getHomeLayout() {
      const layoutLocalStore = useLayoutLocalStore();
      let layout = await layoutLocalStore.getDwLayout("web_home_layout");
      console.log("111 layout :>> ", layout);
      let localLayout = {};
      if (layout?.hasOwnProperty("itemvalue") && layout.itemvalue) {
        layout.itemvalue = layout.itemvalue.replace(/'/g, '"');
        localLayout = JSON.parse(layout.itemvalue);
      }
      console.log("localLayout :>> ", localLayout);

      let params = this.getQuickEnterFunc(localLayout);
      console.log("getHomeLayout params :>> ", params);

      this.setCommonMenu(params.fnlist);

      // console.log("cloneDeep(defaultLayout) :>> ", cloneDeep(defaultLayout));

      //   if (JSON.stringify(localLayout) != "{}") {
      //     localLayout = Object.assign(cloneDeep(defaultLayout), localLayout);
      //   } else {
      //     localLayout = cloneDeep(defaultLayout);
      //   }
      //   console.log("after localLayout :>> ", localLayout);
      //   dwLayout.value = LayoutSettingRef.value?.setDefaultFunc(localLayout);
      //   console.log("onMounted 111 dwLayout.value :>> ", dwLayout.value);
      //   for (const key in dwLayout.value) {
      //     if (isArray(dwLayout.value[key])) {
      //       let arr = dwLayout.value[key];
      //       for (let i = 0; i < arr.length; i++) {
      //         console.log("arr[i] :>> ", arr[i]);
      //         if (arr[i].hasOwnProperty("initParam")) {
      //           initParam[arr[i].id] = arr[i].initParam;
      //         }
      //       }
      //     }
      //   }
    }
  }
});
