import { defineStore } from 'pinia';
import { createStorage } from '@/utils/Storage';
import { store } from '@/store';
import { ACCESS_TOKEN, CURRENT_USER, IS_LOCKSCREEN, TENANT_TOKEN } from '@/store/mutation-types';
import { ResultEnum } from '@/enums/httpEnum';
import { getUserInfoApi, login, LoginParams, logoutApi, changePassword, UpdateMyPwdParams } from '@/api/system/user';
import { storage } from '@/utils/Storage';
import { useGlobSetting } from '@/hooks/setting';
import { PERM } from '@/types/permission/type';

const Storage = createStorage({ storage: localStorage });
const { tenantCode } = useGlobSetting();

export interface IUserState {
  token: string;
  // username: string;
  welcome: string;
  avatar: string;
  permissions: any[];
  info: {
    // userId: number;
    id: number;
    username: string;
    realname: string;
    avatar: string;
    desc: string;
    token: string;
    roleType: number;
    nickname: string;
    mobile: string;
    email: string;
    remark: string;
    tenantName: string;
    tenantCode: string;
    tenantId: number;
    isFirstLogin: number;
  };
  showLogin: boolean;
  showUpdatePwd: boolean;
  showSwitchAccount: boolean;
}

export const useUserStore = defineStore({
  id: 'app-user',
  state: (): IUserState => ({
    token: Storage.get(ACCESS_TOKEN, ''),
    welcome: '',
    avatar: '',
    permissions: [],
    info: {} as IUserState['info'],
    showLogin: false,
    showUpdatePwd: false,
    showSwitchAccount: false,
  }),
  getters: {
    getToken(): string {
      return this.token;
    },

    getAvatar(): string {
      return this.avatar;
    },
    getNickname(): string {
      return this.info.username;
    },
    getPermissions(): [any][] {
      return this.permissions;
    },
    getUserInfo(): any {
      return this.info;
    },
    /** 获取角色类型，可能为多个 */
    getRoleTypes(): number {
      return this.info.roleType;
    },
  },
  actions: {
    setToken(token: string) {
      this.token = token;
    },
    setAvatar(avatar: string) {
      this.avatar = avatar;
    },
    setPermissions(permissions) {
      this.permissions = permissions;
    },
    setUserInfo(info) {
      this.info = info;
    },
    // 登录
    async login(userInfo: LoginParams) {
      try {
        const response = await login(userInfo);
        const { data: result, code } = response;
        if (parseInt(code) === ResultEnum.SUCCESS) {
          const ex = 7 * 24 * 60 * 60 * 1000;
          const token = result.satoken;
          storage.set(ACCESS_TOKEN, token, ex);
          this.setToken(token);
          this.setUserInfo(result);
          return Promise.resolve(response);
        } else {
          return Promise.reject(response);
        }
      } catch (e) {
        return Promise.reject(e);
      }
    },

    // 获取用户信息
    GetInfo() {
      return new Promise((resolve, reject) => {
        getUserInfoApi({ tenantCode })
          .then((res) => {
            const result = res;
            if (result.permissions && result.permissions.length) {
              const permissionsList = result.permissions;
              this.setPermissions(permissionsList);
            }
            this.setUserInfo(result);
            this.setAvatar(result.avatar);
            resolve(res);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },

    // 登出
    async logout() {
      this.setPermissions([]);
      this.setUserInfo('');
      storage.remove(ACCESS_TOKEN);
      storage.remove(CURRENT_USER);
      storage.remove('username');
      return logoutApi();
    },

    // 修改密码
    async changePassword(params: UpdateMyPwdParams) {
      return changePassword(params);
    },

    /**
     * 用户是否有某个权限
     * @param permission
     * @returns
     */
    checkPermission(permission: PERM) {
      return this.permissions.find((x) => x.code === permission);
    },
  },
});

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