import AuthAPI, { LoginData } from "@/api/auth";
import {} from "@/api/user";
import router, { resetRouter } from "@/router";
import { store } from "@/store";
import UserAPI from "@/api/user";

import { TOKEN_KEY, CODE_KEY } from "@/enums/CacheEnum";

export const useUserStore = defineStore(
  "user",
  () => {
    const user = ref<any>();
    /**
     * 登录
     *
     * @param {LoginData}
     * @returns
     */
    function login(loginData: LoginData) {
      return new Promise<void>((resolve, reject) => {
        AuthAPI.login(loginData)
          .then((data) => {
            const { token } = data;
            localStorage.setItem(TOKEN_KEY, <string>token); // Bearer eyJhbGciOiJIUzI1NiJ9.xxx.xxx
            user.value = data;
            resolve();
          })
          .catch((error) => {
            reject(error);
          });
      });
    }

    function getUserInfo() {
      return new Promise<any>((resolve, reject) => {
        UserAPI.getUserInfo()
          .then((data) => {
            if (!data) {
              reject("Verification failed, please Login again.");
              return;
            }
            if (!data.roleList || data.roleList.length <= 0) {
              reject("getUserInfo: roles must be a non-null array!");
              return;
            }
            Object.assign(user.value, { ...data });
            resolve(data);
          })
          .catch((error) => {
            resetToken();
            reject(error);
          });
      });
    }

    // user logout
    function logout() {
      return new Promise<void>((resolve, reject) => {
        AuthAPI.logout()
          .then(() => {
            localStorage.setItem(TOKEN_KEY, "");
            localStorage.setItem(CODE_KEY, "");
            location.reload(); // 清空路由
            resolve();
          })
          .catch((error) => {
            reject(error);
          });
      });
    }

    // remove token
    function resetToken() {
      console.log("resetToken");
      return new Promise<void>((resolve) => {
        localStorage.setItem(TOKEN_KEY, "");
        localStorage.setItem(CODE_KEY, "");
        resetRouter();
        resolve();
      });
    }

    return {
      user,
      login,
      getUserInfo,
      logout,
      resetToken,
    };
  },
  {
    // 配置持久化
    persist: true,
  }
);

/**
 * 用于在组件外部（如在Pinia Store 中）使用 Pinia 提供的 store 实例。
 * 官方文档解释了如何在组件外部使用 Pinia Store：
 * https://pinia.vuejs.org/core-concepts/outside-component-usage.html#using-a-store-outside-of-a-component
 */
export function useUserStoreHook() {
  return useUserStore(store);
}
