import { loginApi, logoutApi } from "@/api/auth";
import { getUserInfoApi } from "@/api/user";
import { resetRouter } from "@/router";
import { store } from "@/store";

import { LoginData } from "@/api/auth/types";
import { UserInfo } from "@/api/user/types";

export const useUserStore = defineStore("user", () => {
  const user = ref<UserInfo>({
    roles: [],
    perms: [],
    sysData: [],
    canSetPermission: false,
    canSetIP: false,
    canCreateMessage1: false,
    canCreateMessage2: false,
    setRoles: false,
    canSetMessageOrg: false,
    canFileShare: false,
  });

  const isGetAuth = ref(false); //是否已经请求过auth接口活的role和menus了

  /**
   * 登录
   *
   * @param {LoginData}
   * @returns
   */
  function login(loginData: LoginData) {
    return new Promise<void>((resolve, reject) => {
      loginApi(loginData)
        .then((response) => {
          // const { tokenType, accessToken } = response.data;
          // localStorage.setItem("token", tokenType + " " + accessToken); // Bearer eyJhbGciOiJIUzI1NiJ9.xxx.xxx
          localStorage.setItem("token", response.data + "");
          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  }

  // 获取信息(用户昵称、头像、角色集合、权限集合)
  function getUserInfo() {
    return new Promise<any>((resolve, reject) => {
      getUserInfoApi()
        .then(({ data }) => {
          if (!data) {
            reject("Verification failed, please Login again.");
            return;
          }
          user.value.userId = data.id;
          user.value.username = data.username;

          user.value.avatar = data.avatar ?? "";
          isGetAuth.value = true;

          user.value.sysData = [];
          user.value.canSetPermission = false;
          user.value.canSetIP = false;
          user.value.setRoles = false;

          data.menus.map((menu: any) => {
            if (menu.isFrame === 1) {
              user.value!.sysData!.push(menu);
            } else {
              if (menu.id === 6) {
                user.value.canSetPermission = true;
              } else if (menu.id === 7) {
                user.value.canSetIP = true;
              } else if (menu.id === 8) {
                user.value.canCreateMessage1 = true;
              } else if (menu.id === 9) {
                user.value.setRoles = true;
              } else if (menu.id === 11) {
                user.value.canSetMessageOrg = true;
              } else if (menu.id === 12) {
                user.value.canFileShare = true;
              } else if (menu.id === 13) {
                user.value.canCreateMessage2 = true;
              }
            }
          });

          resolve(data);
        })
        .catch((error) => {
          reject(error);
        });
    });
  }

  // user logout
  function logout() {
    return new Promise<void>((resolve, reject) => {
      logoutApi()
        .then(() => {
          localStorage.setItem("token", "");
          resetRouter();
          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  }

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

  return {
    user,
    login,
    getUserInfo,
    logout,
    resetToken,
    isGetAuth,
  };
});

// 非setup
export function useUserStoreHook() {
  return useUserStore(store);
}
