import { defineStore } from "pinia";
import { getUserInfo, login, phoneLogin, UserInfo } from "@/api/user.ts";
import { UserAuthInfo, PhoneAuthInfo } from "@/enums/verification.ts";
import useConversationStore from "./chatConversation";
interface UserState {
  userInfo: UserInfo;
  showLoginModel: boolean;
  loginType: LoginType;
  token: string | null;
}

// 登录类型的枚举
export const enum LoginType {
  ACCOUNT_LOGIN,
  SMS_LOGIN,
  REGISTER,
  WECHAT_LOGIN,
  RESET_PASSWORD,
}

export const userStore = defineStore("userStore", {
  state: (): UserState => ({
    token: localStorage.getItem("TOKEN") ?? "",
    userInfo: new UserInfo(),
    showLoginModel: false,
    loginType: LoginType.ACCOUNT_LOGIN,
  }),
  getters: {
    // 获取用户登陆状态
    checkUserLoggedIn: (state: UserState) => !!state.token,
    // 获取用户信息
    getUserInfo: (state: UserState) => state.userInfo,
  },
  actions: {
    // 优化登录模态框控制
    setLoginModalVisibility(isVisible: boolean) {
      this.showLoginModel = isVisible;
    },

    // 设置用户信息
    SET_USER_INFO(userinfo: UserInfo) {
      this.userInfo = userinfo;
    },

    // 设置用户令牌并保存到本地存储
    async SET_USER_TOKEN(token: string) {
      this.token = token;
      localStorage.setItem("TOKEN", `${token}`);
      this.showLogin();
    },

    // 切换登录模态框的显示状态
    showLogin() {
      this.showLoginModel = !this.showLoginModel;
    },

    // 统一的登录方法，使用类型守卫优化类型安全性
    async login(data: UserAuthInfo | PhoneAuthInfo) {
      try {
        let token: string;
        
        switch (this.loginType) {
          case LoginType.ACCOUNT_LOGIN:
            if (!this.isUserAuthInfo(data)) {
              throw new Error("无效的账号登录数据");
            }
            let response:any = await login(data);
            console.log(response);
            token = response.data.access_token;
            break;

          case LoginType.SMS_LOGIN:
            if (!this.isPhoneAuthInfo(data)) {
              throw new Error("无效的手机登录数据");
            }
            token = await phoneLogin(data);
            break;

          default:
            throw new Error("不支持的登录类型");
        }

        await this.SET_USER_TOKEN(token);
        // await this.fetchUserDetails();
      } catch (error) {
        // 统一错误处理
        console.error("登录失败:", error);
        throw error;
      }
    },

    // 类型守卫
    isUserAuthInfo(data: any): data is UserAuthInfo {
      return "username" in data && "password" in data;
    },

    isPhoneAuthInfo(data: any): data is PhoneAuthInfo {
      return "phone" in data && "code" in data;
    },

    // 优化用户详情获取
    async fetchUserDetails() {
      try {
        const userInfo = await getUserInfo();
        this.SET_USER_INFO(userInfo);
      } catch (error) {
        console.error("获取用户信息失败:", error);
        throw error;
      }
    },

    // 优化登出逻辑
    async logout() {
      try {
        const conversationStore = useConversationStore();

        this.userInfo = new UserInfo();
        this.token = null;
        conversationStore.clearConversationList();
        localStorage.removeItem("TOKEN");
        this.setLoginModalVisibility(false);
      } catch (error) {
        console.error("登出失败:", error);
        throw error;
      }
    },
  },
});
