import { login, logout, getInfo, getPublicKey } from "@/api/login";
import {
  getToken,
  getJToken,
  setToken,
  JsetToken,
  removeToken,
} from "@/utils/auth";
import { encrypt } from "@/utils/jsencrypt";
import defAva from "@/assets/images/profile.jpg";
import Cookies from "js-cookie";
const useUserStore = defineStore("user", {
  state: () => ({
    token: getToken(),
    jtoken: getJToken(),
    name: "",
    avatar: "",
    roles: [],
    permissions: [],
  }),
  actions: {
    async getPublicKey() {
      try {
        const res = await getPublicKey();
        return res;
      } catch (error) {
        throw error;
      }
    },
    // async login(userInfo) {
    //   try {
    //     console.log(111111);
    //     const res = await this.getPublicKey();
    //     console.log(res);
    //     const publicKey = res.publicKey;
    //     const username = userInfo.username.trim();
    //     const password = encrypt(userInfo.password, publicKey);
    //     const code = userInfo.code;
    //     const uuid = userInfo.uuid;
    //     const loginResponse = await login(username, password, code, uuid);
    //     this.token = loginResponse.data.access_token; // 直接更新状态
    //     setToken(loginResponse.data.access_token);
    //   } catch (error) {
    //     throw error;
    //   }
    // },
    // 登录
    async login(userInfo) {
      const res = await this.getPublicKey();
      console.log(res);
      const publicKey = res.publicKey;
      const username = userInfo.username.trim();
      const password = encrypt(userInfo.password, publicKey);
      const code = userInfo.code;
      const uuid = userInfo.uuid;
      return new Promise((resolve, reject) => {
        login(username, password, code, uuid)
          .then((res) => {
            setToken(res.token);
            Cookies.set("jFontIp", res.jFontIp);
            Cookies.set("jFontDomain", res.jFontDomain);
            JsetToken(res.jtoken);
            this.token = res.token;
            this.jtoken = res.jtoken;
            resolve();
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    // 获取用户信息
    getInfo() {
      return new Promise((resolve, reject) => {
        getInfo()
          .then((res) => {
            // console.log("rezs", res);
            const user = res.user;
            const avatar =
              user.avatar == "" || user.avatar == null
                ? defAva
                : import.meta.env.VITE_APP_BASE_API + user.avatar;

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

export default useUserStore;
