import { defineStore } from "pinia";
import { store } from "/@/store";
import { userType, resType } from "./types";
import { router } from "/@/router";
import { routerArrays } from "/@/layout/types";
import { storageSession } from "@pureadmin/utils";
import { getLogin, getAsyncRoutes, ddDetail, refreshToken } from "/@/api/user";
import {
  getToken,
  setToken,
  removeToken,
  getAction,
  setAction,
  removeAction
} from "/@/utils/auth";

import { useMultiTagsStoreHook } from "/@/store/modules/multiTags";

export const useUserStore = defineStore({
  id: "pure-user",
  state: (): userType => ({
    token: getToken(),
    name: "admin",
    // 前端生成的验证码（按实际需求替换）
    verifyCode: "",
    // 登录显示组件判断 0：登录 1：手机登录 2：二维码登录 3：注册 4：忘记密码，默认0：登录
    currentPage: 0,
    menuActions: getAction()
  }),
  actions: {
    SET_TOKEN(token) {
      this.token = token;
    },
    SET_NAME(name) {
      this.name = name;
    },
    SET_VERIFYCODE(verifyCode) {
      this.verifyCode = verifyCode;
    },
    SET_CURRENTPAGE(value) {
      this.currentPage = value;
    },
    SET_ACTIONS(value) {
      this.actions = value;
    },
    // 登入
    async loginByUsername(form) {
      return new Promise((resolve, reject) => {
        getLogin(form)
          .then((res: resType) => {
            const { code, data } = res;
            if (code === 0) {
              const { token } = data;
              setToken(token);
              resolve(res);
            } else {
              resolve(res);
            }
          })
          .catch(error => {
            reject(error);
          });
      });
    },
    //钉钉code 获取用户账号详情
    dingUserInfor(code) {
      return new Promise((resolve, reject) => {
        ddDetail(code)
          .then((res: resType) => {
            const { code, data } = res;
            if (code === 0) {
              const { token } = data;
              setToken(token);
              resolve(res);
            } else {
              resolve("error");
            }
          })
          .catch(error => {
            reject(error);
          });
      });
    },
    // 获取当前账号菜单数据
    async postMenuList(form) {
      return new Promise((resolve, reject) => {
        getAsyncRoutes(form)
          .then((res: resType) => {
            const { code, data } = res;
            if (code === 0) {
              const actionList: Array<any> = [];
              data.forEach(e => {
                e.child?.forEach(s => {
                  const item = {
                    menu_route: s.menu_route,
                    action: s.action
                  };
                  actionList.push(item);
                });
              });
              // console.log("77777777777");
              // console.log(actionList);
              setAction(JSON.stringify(actionList));
              resolve(res);
            } else {
              resolve(res);
            }
          })
          .catch(error => {
            reject(error);
          });
      });
    },
    // 登出 清空缓存
    logOut() {
      this.token = "";
      this.name = "";
      removeToken();
      removeAction();
      storageSession.clear();
      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();
      console.log("666666666666666666666666");
      if (arr && arr.length > 0) {
        const powerHook = JSON.parse(arr);
        const arr1 = powerHook.find(i => i.menu_route == code)?.action || [];
        console.log(arr1);
        return arr1;
      } else {
        return [];
      }
    }
  }
});

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