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,
  ddDetail,
  refreshToken,
  httpMyCompany,
  httpUserInfo,
  httpSystemList
} from "/@/api/user";

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


function createMenu(menu_name: string, menu_route: string, menu_url: string, hasDetail = true){
  return {
    "menu_name": menu_name,
    "menu_img": "ep:add-location",
    "menu_route": "invoiceInOut",
    "is_display": "1",
    "status": "1",
    "child": [
      {
        "menu_name": menu_name,
        "menu_img": "el-icon-s-order",
        "menu_route": menu_route,
        "menu_url": menu_url + '/index',
        "status": "1",
        "is_private": "0",
        "is_display": "1",
        "action": ["001"]
      },
      ...(hasDetail ? [
          {
            "menu_name": menu_name + '详情',
            "menu_img": "el-icon-s-order",
            "menu_route": menu_route + 'Detail',
            "menu_url": menu_url + '/detail',
            "status": "1",
            "is_private": "0",
            "is_display": "0",
            "action": ["001"]
          }
      ] : [])
    ]
  }
}

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;
    },
    setCurrentCompany(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 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, is_main }) => ({ companyCode: companyCode, companyName: companyName, is_main }))
        //   if (!this.companyList || this.companyList.length === 0) { return; }
        // }

        // /* 获取本地缓存的公司编码，和账号有的公司列表对比(默认选中该公司) */
        // console.log(this.companyList)
        // const _index = this.companyList.findIndex(({ is_main }) => String(is_main) === "1");
        // const currentCompany = !this.isSuperUser ? this.companyList[_index === -1 ? 0 : _index] : "";
        // 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();

        const res = {
          code: 0,
          data: [
            createMenu('商品管理', 'productManager', 'invoiceInOut/productManager'),
            createMenu('出入库管理', 'inOutManager', 'invoiceInOut/inOutManager')
          ],
          message: '获取成功'
        }

        console.log(res)
        return res
      } 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);
}
