import { login, logout, getInfo } from "@/api/login";
import { getToken, setToken, removeToken } from "@/utils/auth";
import defAva from "@/static/images/profile.jpg";
import { defineStore } from "pinia";

export interface LoginForm {
  tenantId?: string;
  username: string;
  password: string;
  code?: string;
  uuid?: string;
  rememberMe?: boolean;
  clientId?: string;
  grantType?: string;
}

const useUserStore = defineStore("user", {
  state: () => ({
    token: getToken(),
    userId: "",
    name: "",
    avatar: "",
    roles: Array(),
    permissions: [],
  }),
  actions: {
    // 登录
    login(userInfo: LoginForm) {
      const loginData = {
        tenantId: userInfo.tenantId || '000000',
        username: userInfo.username.trim(),
        password: userInfo.password,
        code: userInfo.code,
        uuid: userInfo.uuid,
        rememberMe: userInfo.rememberMe
      };
      return new Promise((resolve, reject) => {
        login(loginData)
          .then((res: any) => {
            // 兼容多种token字段名称和位置
            // 支持格式：{ data: { access_token: "xxx" } } 或 { data: { token: "xxx" } } 或 { token: "xxx" }
            const token = res.data?.access_token || res.data?.token || res.token;
            if (token) {
              setToken(token);
              this.token = token;
              resolve(null);
            } else {
              reject('登录失败：未获取到token');
            }
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    // 获取用户信息
    getInfo() {
      return new Promise((resolve, reject) => {
        getInfo()
          .then((res: any) => {
            // 接口返回的是 { code, msg, data: { user, permissions, roles } }
            // 但request.ts已经返回了data，所以这里res就是data部分
            const userData = res.data || res; // 兼容两种情况
            const user = userData.user;
            
            if (!user) {
              reject('获取用户信息失败：用户数据为空');
              return;
            }
            
            const avatar =
              user.avatar == "" || user.avatar == null
                ? defAva
                : user.avatar;

            if (userData.roles && userData.roles.length > 0) {
              // 验证返回的roles是否是一个非空数组
              this.roles = userData.roles;
              this.permissions = userData.permissions;
            } else {
              this.roles = ["ROLE_DEFAULT"];
            }
            this.userId = user.userId;
            this.name = user.userName;
            this.avatar = avatar;
            resolve(res);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    // 退出系统
    logOut() {
      return new Promise<null>((resolve, reject) => {
        logout()
          .then(() => {
            this.token = "";
            this.userId = "";
            this.roles = [];
            this.permissions = [];
            this.name = "";
            this.avatar = "";
            removeToken();
            resolve(null);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
  },
  persist: true,
});

export default useUserStore;
