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 { removeRelaComNo } from "/@/utils/auth";
import { ElMessage } from "element-plus";

import {
  getLogin,
  getAsyncRoutes,
  ddDetail,
  refreshToken,
  httpUserInfo
} 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: "",
    // 登录显示组件判断 0：登录 1：手机登录 2：二维码登录 3：注册 4：忘记密码，默认0：登录
    currentPage: 0,
    menuActions: getAction(),
    companyList: [],
    currentCompany: null,
    isSuperUser: false,
    swithingCompany: false,
    disabledCompany: false,
    systemInfo: {},
    info: {},
    business: []
  }),
  actions: {
    SET_TOKEN(token) {
      this.token = token;
    },
    SET_NAME(name) {
      this.name = name;
    },
    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.currentComapny = currentCompany;
    },
    // 登入
    async loginByUsername(form) {
      return new Promise((resolve, reject) => {
        getLogin(form)
          .then(async (res: resType) => {
            const { code, data } = res;
            if (Number(code) === 1) {
              const { token } = data;
              setToken(token);
              // await this.requesetUserInfo()
              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 requesetUserInfo() {
      const { code, data, message } = await httpUserInfo({ noRela: true });
      console.log(data);
      this.info = data;
      if (Number(code) === 1) {
        const { level } = data;
        this.level = level;
        this.isSuperUser = Number(this.level) === 1;
        /** 没有设置过level  */
        if (this.level === "0" || !this.level) {
          this.level = level;
        }

        if (this.level === "2") {
          this.business = data.company_relaton;
        }

        if (this.level === "3") {
          this.business = data.company_relaton;
        }

        return data;
      } else {
        throw new Error(JSON.stringify({ code, message }));
      }
    },

    // 获取当前账号菜单数据
    async postMenuList() {
      try {
        const userinfo = await this.requesetUserInfo();
        return new Promise((resolve, reject) => {
          getAsyncRoutes({
            role_id: userinfo.role_id
          })
            .then((res: resType) => {
              const { code, data, message } = res;
              if (message === "账户已禁用") {
                removeMenus();
                reject(10000);
                trigger("roleException");
                return;
              }

              const actionList: Array<any> = [];
              switch (Number(code)) {
                case 1:
                  data.forEach(e => {
                    e.child?.forEach(s => {
                      const item = {
                        menu_route: s.menu_route,
                        action: s.child.map(({ action_id }) =>
                          String(action_id)
                        )
                      };
                      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 => {
              console.log(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 = [];
      this.business = [];
      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);
}
