import { defineStore } from "pinia";
import { store } from "@/store";
import type { userType } from "../types";
import { routerArrays } from "@/layout/types";
import { router, resetRouter } from "@/router";
import { storageLocal } from "@pureadmin/utils";
import { getLogin, refreshTokenApi } from "@/api/login";
import type { LoginResult } from "@/api/login";
import { useMultiTagsStoreHook } from "@/store/modules/multiTags";
import {
  type UserInfo,
  type UserToken,
  setToken,
  removeToken,
  userInfoKey,
  userTokenKey
} from "@/utils/auth";

export const useUserStore = defineStore({
  id: "user",
  state: (): userType => ({
    // 用户名
    username: storageLocal().getItem<UserInfo>(userInfoKey)?.username ?? "",
    // 页面级别权限
    permissions:
      storageLocal().getItem<UserInfo>(userInfoKey)?.permissions ?? [],
    // 前端生成的验证码（按实际需求替换）
    verifyCode: "",
    // 判断登录页面显示哪个组件（0：登录（默认）、1：手机登录、2：二维码登录、3：注册、4：忘记密码,1,2预留暂不开发）
    currentPage: 0,
    /**用户头像 */
    avatar: storageLocal().getItem<UserInfo>(userInfoKey)?.avatar ?? "",
    /**用户数据库ID */
    id: storageLocal().getItem<UserInfo>(userInfoKey)?.id ?? "",
    /**用户Token */
    accessToken:
      storageLocal().getItem<UserToken>(userTokenKey)?.accessToken ?? "",
    /**用户刷新Token*/
    refreshToken:
      storageLocal().getItem<UserToken>(userTokenKey)?.refreshToken ?? "",
    /**过期时间 */
    expires: storageLocal().getItem<UserToken>(userTokenKey)?.expiresTime ?? 0,
    // 是否勾选了登录页的免登录
    isRemembered: false,
    // 登录页的免登录存储几天，默认2天
    loginDay: 2,
    /***
     * 用户手机号
     */
    phone: storageLocal().getItem<UserInfo>(userInfoKey)?.phone ?? "",
    /***
     * 用户邮箱
     */
    email: storageLocal().getItem<UserInfo>(userInfoKey)?.email ?? "",
    /***
     * 用户昵称
     */
    nickname: storageLocal().getItem<UserInfo>(userInfoKey)?.nickname ?? "",
    /***
     * 用户性别
     */
    gender: storageLocal().getItem<UserInfo>(userInfoKey)?.gender ?? 0,
    /***
     * 用户角色
     */
    roles: storageLocal().getItem<UserInfo>(userInfoKey)?.roles ?? [],
    /***
     * 部门ID
     */
    department_id:
      storageLocal().getItem<UserInfo>(userInfoKey)?.department_id ?? ""
  }),
  actions: {
    /** 存储用户名 */
    SET_USERNAME(username: string) {
      this.username = username;
    },
    /** 存储权限 */
    SET_PERMISSIONS(permissions: Array<string>) {
      this.permissions = permissions;
    },
    /** 存储前端生成的验证码 */
    SET_VERIFYCODE(verifyCode: string) {
      this.verifyCode = verifyCode;
    },
    /** 存储登录页面显示哪个组件 */
    SET_CURRENTPAGE(value: number) {
      this.currentPage = value;
    },
    /**存储用户头像 */
    SET_AVATAR(value: string) {
      this.avatar = value;
    },
    /**存储用户数据库ID */
    SET_ID(value: string) {
      this.id = value;
    },
    /**存储用户Token */
    SET_ACCESSTOKEN(value: string) {
      this.accessToken = value;
    },
    /**存储用户刷新Token */
    SET_REFRESHTOKEN(value: string) {
      this.refreshToken = value;
    },
    /**存储用户Token过期时间戳 */
    SET_EXPIRES(value: number) {
      this.expires = value;
    },
    /** 存储是否勾选了登录页的免登录 */
    SET_ISREMEMBERED(bool: boolean) {
      this.isRemembered = bool;
    },
    /** 设置登录页的免登录存储几天 */
    SET_LOGINDAY(value: number) {
      this.loginDay = Number(value);
    },
    /** 存储用户手机号 */
    SET_PHONE(value: string) {
      this.phone = value;
    },
    /** 存储用户邮箱 */
    SET_EMAIL(value: string) {
      this.email = value;
    },
    /** 存储用户昵称 */
    SET_NICKNAME(value: string) {
      this.nickname = value;
    },
    /** 存储用户性别 */
    SET_GENDER(value: number) {
      this.gender = value;
    },
    /** 存储用户角色 */
    SET_ROLES(value: Array<string>) {
      this.roles = value;
    },
    /** 存储用户部门ID */
    SET_DEPARTMENT_ID(value: string) {
      this.department_id = value;
    },
    /** 登入 */
    async loginByUsername(data: {
      username: string;
      password: string;
      loginDay?: number;
      uuid?: string;
      code?: string;
    }) {
      return new Promise<ResponseResult<LoginResult>>((resolve, reject) => {
        getLogin(data)
          .then(data => {
            if (data.code === 200) {
              setToken(data.data);
            }
            resolve(data);
          })
          .catch(error => {
            reject(error);
          });
      });
    },
    /** 前端登出（不调用接口） */
    logOut() {
      this.username = "";
      this.permissions = [];
      this.verifyCode = "";
      this.currentPage = 0;
      this.avatar = "";
      this.id = "";
      this.accessToken = "";
      this.refreshToken = "";
      this.expires = 0;
      this.isRemembered = false;
      this.loginDay = 2;
      this.phone = "";
      this.email = "";
      this.nickname = "";
      this.gender = 0;
      this.roles = [];
      this.department_id = "";
      removeToken();
      useMultiTagsStoreHook().handleTags("equal", [...routerArrays]);
      resetRouter();
      router.push("/login");
    },
    /** 刷新`token` */
    async handRefreshToken(data: { refreshToken: string }) {
      return new Promise<ResponseResult<LoginResult>>((resolve, reject) => {
        refreshTokenApi(data)
          .then(data => {
            if (data.code === 200) {
              setToken(data.data);
            }
            resolve(data);
          })
          .catch(error => {
            reject(error);
          });
      });
    }
  }
});

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