import { defineStore } from "pinia";
import { store } from "@/store";
import { StorageEnum } from "@/enums/storageEnum";
import { ResultEnum } from "@/enums/httpEnum";
import { storage, routerTurnByName } from "@/utils";
import { login, getUserInfo } from "@/api/system/user";
import { PageEnum } from "@/enums/pageEnum";
export type UserInfoType = {
  // TODO: add your own data
  name: string;
  email: string;
};

export interface IUserState {
  token: string;
  username: string;
  welcome: string;
  avatar: string;
  permissions: any[];
  info: UserInfoType;
}

export const useUserStore = defineStore({
  id: "app-user",
  state: (): IUserState => ({
    token: storage.get(StorageEnum.ZS_ACCESS_TOKEN, ""),
    username: "",
    welcome: "",
    avatar: "",
    permissions: [],
    info: storage.get(StorageEnum.ZS_CURRENT_USER, {}),
  }),
  getters: {
    getToken(): string {
      return this.token;
    },
    getAvatar(): string {
      return this.avatar;
    },
    getNickname(): string {
      return this.username;
    },
    getPermissions(): [any][] {
      return this.permissions;
    },
    getUserInfo(): UserInfoType {
      return this.info;
    },
  },
  actions: {
    setToken(token: string) {
      this.token = token;
    },
    setAvatar(avatar: string) {
      this.avatar = avatar;
    },
    setPermissions(permissions) {
      this.permissions = permissions;
    },
    setUserInfo(info: UserInfoType) {
      this.info = info;
    },
    // 登录
    async login(params: any) {
      const res = await login(params);
      const { data } = res;
      if (res.status === ResultEnum.STATUS) {
        const ex = 7 * 24 * 60 * 60;
        storage.set(StorageEnum.ZS_ACCESS_TOKEN, data, ex);
        this.setToken(data);
        // this.setUserInfo(result);
      }
      return res;
    },

    // 获取用户信息
    async getInfo() {
      const { data } = await getUserInfo();
      console.log(data, "用户信息");

      // if (result.permissions && result.permissions.length) {
      // const permissionsList = result.permissions;
      // this.setPermissions(permissionsList);
      this.setUserInfo(data);
      // } else {
      //   throw new Error("getInfo: permissionsList must be a non-null array !");
      // }
      this.setAvatar(data.avatar);
      return data;
    },

    // 登出
    async logout() {
      this.setPermissions([]);
      this.setUserInfo({ name: "", email: "" });
      storage.remove(StorageEnum.ZS_ACCESS_TOKEN);
      storage.remove(StorageEnum.ZS_CURRENT_USER);
      routerTurnByName(PageEnum.BASE_LOGIN_NAME);
    },
  },
});

// Need to be used outside the setup
export function useUser() {
  return useUserStore(store);
}
