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,
  httpCompanies
} from "/@/api/user";

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

import { nextTick } from "vue"


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 => ({
    defaultCompanyNo: '',
    licenseSet: [],
    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 } = 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, company_relaton } = 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 = (company_relaton || []).map(
            ({ companyCode, companyName, is_main }) => ({ companyCode, companyName, company_license: '' ,is_main })
          )


          if (!this.companyList || this.companyList.length === 0) { return; }
        }


        // if (!this.licenseSet || this.licenseSet.length === 0){
          // const { code, data: companies } = await httpCompanies({ size: 10000 })

          // const list = companies.list.map(item => ({
          //   companyNo: item.companyNo,
          //   company_license: item.company_license,
          //   company_name: item.company_name,
          //   invoice_title: item.invoice_title
          // }))

          // console.log(list)

          const companies = [
            {
              "companyNo": "GS2407291600490369",
              "company_license": "9144030056854457XB",
              "company_name": "深圳鸿逸科技发展有限公司",
              "invoice_title": "深圳鸿逸科技发展有限公司"
            },
            {
              "companyNo": "GS2404151642335170",
              "company_license": "911100006337468570",
              "company_name": "北京元隆雅图文化传播股份有限公司",
              "invoice_title": "北京元隆雅图文化传播股份有限公司"
            },
            {
              "companyNo": "GS2404151647395616",
              "company_license": "911100006337468571",
              "company_name": "结算单E企购",
              "invoice_title": "结算单E企购"
            },
            {
              "companyNo": "GS2402020907088731",
              "company_license": "91110118MACDK2TY8J",
              "company_name": "北京泰文创供应链管理有限公司",
              "invoice_title": "北京泰文创供应链管理有限公司"
            },
            {
              "companyNo": "GS2401181650538135",
              "company_license": "91110113MA008E6E18",
              "company_name": "北京知事文化产业发展有限公司",
              "invoice_title": "北京知事文化产业发展有限公司"
            },
            {
              "companyNo": "GS2302231122266720",
              "company_license": "91420106MA4F28BX0T",
              "company_name": "湖北泽仁文化发展有限公司",
              "invoice_title": "湖北泽仁文化发展有限公司"
            },
            {
              "companyNo": "GS2302231117413175",
              "company_license": "91420111MA4K345W3D",
              "company_name": "湖北德润仁合文化产业发展有限公司",
              "invoice_title": "湖北德润仁合文化产业发展有限公司"
            },
            {
              "companyNo": "GS2302231123305392",
              "company_license": "91230184MA1CNL5D05",
              "company_name": "五常市藏金壹柒肆伍农业科技有限公司",
              "invoice_title": "五常市藏金壹柒肆伍农业科技有限公司"
            },
            {
              "companyNo": "GS2302231114471122",
              "company_license": "91110113MA01PAPQ33",
              "company_name": "创世昌源 (北京)国际旅行社有限公司",
              "invoice_title": "创世昌源 (北京)国际旅行社有限公司"
            },
            {
              "companyNo": "GS2302231124114965",
              "company_license": "91110113MA7LH3Y14H",
              "company_name": "北京普润心堂商贸有限公司",
              "invoice_title": "北京普润心堂商贸有限公司"
            },
            {
              "companyNo": "GS2302231125079621",
              "company_license": "91110113MA008J790J",
              "company_name": "北京百辰荣达国际科贸有限公司",
              "invoice_title": "北京百辰荣达国际科贸有限公司"
            },
            {
              "companyNo": "GS2304031312553746",
              "company_license": "91110118MACEA1R94G",
              "company_name": "北京锦兴弘昌科技有限公司",
              "invoice_title": "北京锦兴弘昌科技有限公司"
            },
            {
              "companyNo": "GS2302231323386950",
              "company_license": "91120222MA06KMPU67",
              "company_name": "北京泓源广诚国际商贸有限公司",
              "invoice_title": "北京泓源广诚国际商贸有限公司"
            },
            {
              "companyNo": "GS2302231311448895",
              "company_license": "91120116MA073LUY6M",
              "company_name": "开乾国际商贸（天津）有限公司",
              "invoice_title": "开乾国际商贸（天津）有限公司"
            },
            {
              "companyNo": "GS2203161855277894",
              "company_license": "91110113MA004JNJ28",
              "company_name": "北京万宇恒通国际科贸有限公司",
              "invoice_title": "北京万宇恒通国际科贸有限公司"
            }
          ]

          this.licenseSet = companies

          if (code === 0) {
            this.companyList.forEach(item => {
              const current = companies.find(({ companyNo }) => companyNo == item.companyCode)
              item.company_license = current?.company_license
            })


            console.log(this.companyList)
          }
        // }

      
        const companyCode = getRelaComNo();
        const index = this.companyList.findIndex((item) => item.companyCode === companyCode);

        // /* 获取本地缓存的公司编码，和账号有的公司列表对比(默认选中该公司) */
        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] : "";


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


        nextTick(() => {
          this.setCurrentCompany(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('入库管理', 'inManager', 'invoiceInOut/inManager'),
            createMenu('出库管理', 'outManager', 'invoiceInOut/outManager'),
            createMenu('盘点', 'inventoryCheck', 'invoiceInOut/inventoryCheck'),
            createMenu('计提出库明细处理', 'provisionOut', 'invoiceInOut/provisionOut'),
            createMenu('调整单', 'adjustOrder', 'invoiceInOut/adjustOrder'),
            createMenu('收发存汇总', 'summary', 'invoiceInOut/summary'),
            createMenu('C端无发票订单出库', 'clinetC', 'invoiceInOut/clientC')
          ],
          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);
}
