import { store } from "/@/store";
import { router } from "/@/router";
import { defineStore } from "pinia";
import { userType, resType } from "./types";
import { routerArrays } from "/@/layout/types";
import { storageSession } from "@pureadmin/utils";
import { useMultiTagsStoreHook } from "/@/store/modules/multiTags";

import { getRelaComNo, setRelaComName, removeRelaComNo } from "/@/utils/auth";
import { ElMessage } from "element-plus";

import { loadEnv } from "@build/index";

const { VITE_IS_PROD } = loadEnv();

import {
  getLogin,
  getAsyncRoutes,
  ddDetail,
  refreshToken,
  httpCompany,
  httpMyCompany,
  httpUserInfo,
  httpSystemList
  // setSystemVer
} from "/@/api/user";

import {
  getToken,
  setToken,
  setRelaComNo,
  removeToken,
  getAction,
  setAction,
  removeAction
} from "/@/utils/auth";

import { removeMenus } from "/@/store/modules/permission";
import { trigger } from "/@/plugins/errorHooks/trigger";

export const useUserStore = defineStore({
  id: "pure-user",
  state: (): userType => ({
    token: getToken(),
    level: "0",
    name: "admin",
    // 前端生成的验证码（按实际需求替换）
    verifyCode: "",
    system_version: [],
    // 登录显示组件判断 0：登录 1：手机登录 2：二维码登录 3：注册 4：忘记密码，默认0：登录
    currentPage: 0,
    menuActions: getAction(),
    companyList: [],
    currentCompany: null,
    isSuperUser: false,
    swithingCompany: false,
    disabledCompany: false,
    systemInfo: {},
    info: {}
  }),
  actions: {
    SET_TOKEN(token) {
      this.token = token;
    },
    SET_NAME(name) {
      this.name = name;
    },
    SET_VERSION(version) {
      this.system_version = version;
    },
    SET_LEVEL(level) {
      this.level = level;
    },

    SET_VERIFYCODE(verifyCode) {
      this.verifyCode = verifyCode;
    },
    SET_CURRENTPAGE(value) {
      this.currentPage = value;
    },
    SET_ACTIONS(value) {
      this.actions = value;
    },
    SET_CURRENT_COMPANY(currentCompany) {
      this.currentCompany = currentCompany;
    },
    // 登入
    async loginByUsername(form) {
      return new Promise((resolve, reject) => {
        getLogin(form)
          .then((res: resType) => {
            const { code, data } = res;
            if (code === 0) {
              const { token, companyNo, company_name } = data;
              // setRelaComNo(companyNo);
              // setRelaComName(company_name);
              setToken(token);
              resolve(res);
            } else {
              resolve(res);
            }
          })
          .catch(error => {
            reject(error);
          });
      });
    },

    // async setUserVersion(VERSION) {
    //   return new Promise((resolve, reject) => {
    //     setSystemVer({
    //       account_id: this.info.id,
    //       plat_code: "cx",
    //       system_version: VERSION
    //     })
    //       .then((res: resType) => {
    //         const { code, data } = res;
    //         if (code === 0) {
    //           resolve(res);
    //         } else {
    //           resolve(res);
    //         }
    //       })
    //       .catch(error => {
    //         reject(error);
    //       });
    //   });
    // },
    async loginByToken(token) {
      setToken(token);
      await this.postMenuList();
    },
    //钉钉code 获取用户账号详情
    dingUserInfor(code) {
      return new Promise((resolve, reject) => {
        ddDetail(code)
          .then((res: resType) => {
            const { code, data } = res;
            if (code === 0) {
              const { token, companyNo } = data;
              setToken(token);
              setRelaComNo(companyNo);
              resolve(res);
            } else {
              resolve("error");
            }
          })
          .catch(error => {
            reject(error);
          });
      });
    },
    async updateUserVersion() {
      const { code, data, message } = await httpUserInfo({
        noRela: true
      });

      this.info = data;
      if (Number(code) === 0) {
        const { system_version } = data;
        this.system_version = system_version && system_version.st ? system_version.st.split(",") : [];
      }
    },
    async requesetUserInfo() {
      const { code, data, message } = await httpUserInfo({ noRela: true });

      this.info = data;
      if (Number(code) === 0) {
        const { role_level, level, system_version } = data;
        /** 没有设置过level 超管切换供应商和业务公司  */
        if (this.level === "0" || !this.level) { this.level = level; }
        /* 系统版本保存 */
        this.system_version = system_version && system_version.st ? system_version.st.split(",") : [];
        /* 是否为超管 */
        this.isSuperUser = level === "1";
        /* 非超管用户获取公司 */
        if (!this.isSuperUser && this.companyList.length === 0) {
          const result = await httpMyCompany({ size: 10000, type: '1' });
          this.companyList = result.data.list.map(({ companyCode, companyName }) => ({ companyCode: companyCode, companyName: companyName }))
          if (!this.companyList || this.companyList.length === 0) { return; }
        }

        /* 获取本地缓存的公司编码，和账号有的公司列表对比(默认选中该公司) */
        const code = getRelaComNo();
        const index = this.companyList.findIndex(({ companyNo, companyCode }) => companyNo === code || companyCode === code);
        let _index = index >= 0 ? index : -1;
        // 没有找到则寻找该账户下绑定公司的主公司
        if (_index === -1) { _index = this.companyList.findIndex(({ is_main }) => String(is_main) === "1"); }
        const currentCompany = !this.isSuperUser ? this.companyList[_index === -1 ? 0 : _index] : "";

        console.log(currentCompany)

        if (currentCompany && currentCompany.companyCode) {currentCompany.companyNo = currentCompany.companyCode; }

        this.currentCompany = currentCompany;
        setRelaComName(currentCompany.companyName);
        setRelaComNo(currentCompany.companyNo);
      } else {
        throw new Error(JSON.stringify({ code, message }));
      }
    },

    /* Get update history */
    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];
          }
        }
      } else {
        throw new Error();
      }
    },
    // 获取当前账号菜单数据
    async postMenuList(form) {
      try {
        await this.requesetUserInfo();
        await this.requsetSystemInfo();

        return new Promise((resolve, reject) => {
          getAsyncRoutes(form)
            .then((res: resType) => {
              const { code, data, message } = res;
              const { id } = this.info;
              let systemList = [];


              /* 只有这四个ID可以看到系统设置和业务公司账号权限 */ 
              if (String(VITE_IS_PROD) === "true") { systemList = ["109", "44", "37", "36"];}
              if (String(VITE_IS_PROD) === "false") {systemList = ["109", "44", "37", "36"]; }
              if (!systemList.includes(id)) {
                res.data = res.data.filter(({ menu_name }) =>  menu_name !== "系统设置" && menu_name !== "业务公司账号权限" );
              }

              if (message === "账户已禁用") {
                removeMenus();
                reject(10000);
                trigger("roleException");
                return;
              }

              const actionList: Array<any> = [];
              switch (Number(code)) {
                case 0:
                  /* 处理集合类型的菜单 -》 结算的运单管理 */ 
                  data.forEach(e => {
                    e.child?.forEach(s => {
                      const item = { menu_route: (s.menu_route.split('_collection'))[0], action: s.action };
                      actionList.push(item);
                    });
                  });
                  setAction(JSON.stringify(actionList));
                  resolve(res);
                  break;
                case 10000:
                  removeMenus();
                  reject(10000);
                  trigger("roleException");
                  return;
                default:
                  resolve(res);
                  break;
              }
              this.disabledCompany = false;
            })
            .catch(error => {
              reject(error);
            });
        });
      } catch (err) {
        if (err && err.message) {
          const { code, message } = JSON.parse(err.message);
          if (!(Number(code) >= 100 && Number(code) <= 104)) {
            ElMessage.error(message);
          }
        }
        window.location.hash = "login";
      }
    },
    // 登出 清空缓存
    logOut() {
      this.token = "";
      this.name = "";
      this.level = "";
      removeToken();
      removeAction();
      storageSession.clear();
      this.currentComapny = "";
      this.companyList = [];
      removeRelaComNo();
      useMultiTagsStoreHook().handleTags("equal", routerArrays);
      router.push("/login");
    },
    // 刷新token
    async refreshToken(data) {
      return refreshToken(data).then(data => {
        if (data) {
          setToken(data);
          return data;
        }
      });
    },
    getMenuActions(code) {
      const arr = getAction();
      if (arr && arr.length > 0) {
        const powerHook = JSON.parse(arr);
        const arr1 = powerHook.find(i => i.menu_route == code)?.action || [];
        return arr1;
      } else {
        return [];
      }
    }
  }
});

export async function initalUser() {
  return useUserStore().requesetUserInfo();
}

export function useUserStoreHook() {
  return useUserStore(store);
}
