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

export const useUserStore = defineStore({
  id: "pure-user",
  state: (): userType => ({
    // 用户名
    username:
      storageSession().getItem<DataInfo<number>>(sessionKey)?.username ?? "",
    // 页面级别权限
    roles: storageSession().getItem<DataInfo<number>>(sessionKey)?.roles ?? [],
    profile:
      storageSession().getItem<DataInfo<number>>(sessionKey)?.profile ?? [],
    isStaff: localStorage.getItem('CASE_ISSTAFF',)?? 'false'
  }),
  actions: {
    /** 存储用户名 */
    SET_USERNAME(username: string) {
      this.username = username;
    },
    /** 存储角色 */
    SET_ROLES(roles: Array<string>) {
      this.roles = roles;
    },
    SET_PROFILE(profile) {
      this.profile = profile;
      console.log('存储成功', profile);

    },
    SET_ISSTAFF(value) {
      localStorage.setItem('CASE_ISSTAFF', String(value));
      this.isStaff = String(value)
    },
    /** 登入 */
    async loginByUsername(data) {
      return new Promise<UserResult>(async (resolve, reject) => {
        getLogin(data)
          .then(async res => {
            if (res) {
              await setToken(res.data);
              resolve(data);
            }
          })
          .catch(error => {
            reject(error);
          });
      });
    },
    /** 前端登出（不调用接口） */
    logOut() {
      this.username = "";
      this.roles = [];
      removeToken();
      useMultiTagsStoreHook().handleTags("equal", [...routerArrays]);
      resetRouter();
      let CACHE_CHANNEL = useLoginStore().getChannel;
      if (CACHE_CHANNEL) {
        router.push(`/login?channel=${CACHE_CHANNEL}`);
      } else {
        router.push(`/login`);
      }
    },
    /** 刷新`token` */
    async handRefreshToken(data) {
      return new Promise<RefreshTokenResult>((resolve, reject) => {
        refreshTokenApi(data)
          .then(data => {
            if (data) {
              setToken(data.data);
              resolve(data);
            }
          })
          .catch(error => {
            reject(error);
          });
      });
    }
  }
});

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