import { defineStore } from "pinia";
import { ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import { message, notification } from "ant-design-vue";

import { useUserStore } from "./user";
import { login, logout as logoutApi } from "@/api/system";
import { setToken, getToken, removeToken, setAccount, removeAccount } from "@/utils/auth";
import type { LoginInfo } from "@/api/system/model";

export const useAuthStore = defineStore("auth", () => {
  const route = useRoute();
  const router = useRouter();
  const userStore = useUserStore();

  const loginLoading = ref(false);
  const token = ref(getToken() || null);

  async function authLogin(params: LoginInfo, rememberMe: boolean) {
    try {
      loginLoading.value = true;
      const res = await login(params);
      if (res.code === 200) {
        setToken(res.token as string);
        await userStore.fetchUserInfo();
        notification.success({
          message: "登录成功",
          description: `欢迎回来，${params.username}`,
          duration: 3,
        });

        if (rememberMe) {
          userStore.setUserInfo({
            ...params,
            rememberMe
          });
        } else {
          userStore.clearUserInfo();
        }
        const redirect = route.query.redirect || "/";
        router.replace(redirect as string);
        return res;
      } else {
        // 抛出错误，让调用方处理
        throw new Error(res.msg || "登录失败");
      }
    } catch (error) {
      throw error;
    } finally {
      loginLoading.value = false;
    }
  }

  async function logout() {
    // 在实际应用中，这里可以调用后端的退出登录接口
    await logoutApi();
    removeToken();
    userStore.clearUserInfo();
    await router.push("/login");
    message.success("已成功退出");
  }

  return {
    token,
    loginLoading,
    authLogin,
    logout,
  };
});
