import { defineStore } from "pinia";
import { loginApi, logoutApi } from "@/api/auth";
import { resetRouter } from "@/router";
import { store } from "@/store";
import { useStorage } from "@vueuse/core";
import { LoginData, LoginResult } from "@/api/auth/types";

export const useUserStore = defineStore("user", () => {
  // state
  const token = useStorage("accessToken", "");
  const userInfo = useStorage("userInfo", "");
  const schoolId = useStorage("schoolId", 0);
  const schoolNum = useStorage("schoolNum", "");
  const routeStatus = ref(false);
  const nickname = ref("");
  const phone = ref("");
  const role = ref(""); // 用户角色 → 判断路由权限
  const perms = ref<Array<string>>([]); // 用户权限编码集合 → 判断按钮权限

  // 登录调用
  function login(loginData: LoginData) {
    return new Promise<void>((resolve, reject) => {
      loginApi(loginData)
        .then(({ data }) => {
          userInfo.value = JSON.stringify(data);
          setUserData(data);
          resolve();
        })
        .catch((error) => {
          console.log(error);
          reject(error);
        });
    });
  }

  // 动态路由调用
  function getInfo() {
    return new Promise<string>((resolve, reject) => {
      const userInfoStr = localStorage.getItem("userInfo");
      if (null != userInfoStr) {
        const userInfo = JSON.parse(userInfoStr);
        const role = setUserData(userInfo);
        resolve(role);
      } else {
        reject("本地数据丢失，请重新登录！");
      }
    });
  }

  // 设置用户信息
  function setUserData(data: LoginResult) {
    token.value = data.token;
    nickname.value = data.name;
    phone.value = data.phone;
    schoolNum.value = data.num;
    //role.value = data.role;
    role.value = "ADMIN";
    perms.value = data.perms;
    return role.value;
  }

  // 注销
  function logout() {
    return new Promise<void>((resolve, reject) => {
      logoutApi()
        .then(() => {
          resetRouter();
          resetToken();
          location.reload(); // 清空路由
          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  }

  // 重置
  function resetToken() {
    token.value = "";
    userInfo.value = "";
    nickname.value = "";
    phone.value = "";
    role.value = "";
    perms.value = [];
  }

  // 切换学校
  function changeSchool(id: number, num: string) {
    schoolId.value = id;
    schoolNum.value = num;
  }

  // 路由加载后设置
  function setRouteStatus(status: boolean) {
    routeStatus.value = status;
  }

  return {
    token,
    routeStatus,
    schoolId,
    schoolNum,
    nickname,
    phone,
    role,
    perms,
    login,
    logout,
    getInfo,
    resetToken,
    setRouteStatus,
    changeSchool,
  };
});

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