import { defineStore } from 'pinia';
import { store } from '@/store';
import { useAsyncRoute } from '@/store/modules/asyncRoute';
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';
import router from '@/router';
import type { RouteRecordRaw } from 'vue-router';
import { useProjectSetting } from '@/store/modules/projectSetting';

export type UserInfoType = {
  // TODO: add your own data
  realname: string;
  email: string;
  token: string;
  menuTree: any[];
  userStyleSetting: object;
  userId: number;
};

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

export const useUserStore = defineStore({
  id: 'app-user',
  state: (): IUserState => ({
    token: storage.get(StorageEnum.ZS_ACCESS_TOKEN, ''),
    username: '',
    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;
    },

    // setPermissions(permissions) {
    //   this.permissions = permissions;
    // },

    async setUserInfo(info: UserInfoType) {
      this.info = info;
      const useProjectSettingStore = useProjectSetting();
      useProjectSettingStore.setProjectSetting(info.userStyleSetting);
    },

    // 登录
    async login(params: { username: string; password: string }) {
      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.getInfo();
        const asyncRouteStore = useAsyncRoute();
        const routes = await asyncRouteStore.generateRoutes();
        // 动态添加可访问路由表;
        routes.forEach((item: unknown) => {
          router.addRoute(item as unknown as RouteRecordRaw);
        });
      }
      return res;
    },

    // 获取用户信息
    async getInfo() {
      const { data } = await getUserInfo();

      // 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 !");
      // }
      return data;
    },

    // 登出
    async logout() {
      // this.setPermissions([]);
      this.setUserInfo({
        realname: '',
        email: '',
        token: '',
        menuTree: [],
        userStyleSetting: {},
        userId: null as any,
      });
      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);
}
