import { defineStore } from "pinia";
import { store } from "@/store";
import { userType } from "./types";
import { routerArrays } from "@/layout/types";
import { resetRouter } from "@/router";
import router from "@/router";
import { storageSession } from "@pureadmin/utils";
import { getLogin, getUserMenu, refreshTokenApi } from "@/api/user";
import { UserResult, RefreshTokenResult } from "@/api/user";
import { useMultiTagsStoreHook } from "@/store/modules/multiTags";
import {
  type DataInfo,
  setToken,
  removeToken,
  sessionKey,
  setUserinfo
} from "@/utils/auth";
import { ShakeDownDecrypt } from "@/utils/CryptoJS";

// 菜单格式化函数
const formateRouter = (data, role = 1) => {
  return data.map(item => {
    return {
      path: item.path,
      name: item.name,
      component: null,
      meta: {
        title: item.meta.title,
        icon: item.meta.icon,
        roles: [role],
        auths: item.permission
      },
      children: item.children
        ? item.children.length != 0
          ? formateRouter(item.children, role)
          : null
        : null
    };
  });
};
export const useUserStore = defineStore({
  id: "pure-user",
  state: (): userType => ({
    // 用户名
    username:
      (storageSession().getItem<DataInfo<number>>(sessionKey) &&
        ShakeDownDecrypt(storageSession().getItem<DataInfo<number>>(sessionKey))
          .username) ??
      "",
    // 页面级别权限
    roles:
      (storageSession().getItem<DataInfo<number>>(sessionKey) &&
        ShakeDownDecrypt(storageSession().getItem<DataInfo<number>>(sessionKey))
          .roles) ??
      [],

    // 前端生成的验证码（按实际需求替换）
    verifyCode: "",
    // 判断登录页面显示哪个组件（0：登录（默认）、1：手机登录、2：二维码登录、3：注册、4：忘记密码）
    currentPage: 0
  }),
  actions: {
    /** 存储用户名 */
    SET_USERNAME(username: string) {
      this.username = username;
    },
    /** 存储角色 */
    SET_ROLES(roles: Array<string>) {
      this.roles = roles;
    },
    /** 存储角色 */
    SET_ROUTELIST(routeList: Array<object>) {
      this.routeList = routeList;
    },
    /** 存储前端生成的验证码 */
    SET_VERIFYCODE(verifyCode: string) {
      this.verifyCode = verifyCode;
    },
    /** 存储登录页面显示哪个组件 */
    SET_CURRENTPAGE(value: number) {
      this.currentPage = value;
    },

    /** 登入 */
    async loginByUsername(data) {
      return new Promise<UserResult>((resolve, reject) => {
        getLogin(data)
          .then((data: any) => {
            if (data.status === 1) {
              console.log("[ data ] >", data);
              const token = data.data;
              setToken({
                accessToken: token.access_token,
                refreshToken: token.refresh_token,
                expires: new Date(token.exp)
              });
              getUserMenu().then((res: any) => {
                if (res.status === 1) {
                  console.log(1);
                  setUserinfo({
                    SysAdminId: token.user_id,
                    username: token.username,
                    // 一个用户可能有多个角色
                    roles: 1,
                    routeList: formateRouter(res.data)
                  });
                  resolve(data);
                } else {
                  resolve(data);
                }
              });
            } else {
              resolve(data);
            }
          })
          .catch(error => {
            reject(error);
          });
      });
    },
    /** 前端登出（不调用接口） */
    logOut() {
      this.username = "";
      this.roles = [];
      removeToken();
      useMultiTagsStoreHook().handleTags("equal", [...routerArrays]);
      resetRouter();
      router.push("/login");
    },
    /** 刷新`token` */
    async handRefreshToken(data) {
      return new Promise<RefreshTokenResult>((resolve, reject) => {
        refreshTokenApi(data)
          .then(res => {
            if (res) {
              const data: any = res.data;
              // 重新分配token
              setToken({
                accessToken: data.access_token,
                refreshToken: data.refresh_token,
                expires: new Date(data.exp)
              });
              resolve(data);
            }
          })
          .catch(error => {
            reject(error);
          });
      });
    }
  }
});

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