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 { getUserInfo, login } 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;
  };
  tenantId: number;
  showLogin: boolean;
}

export const useUserStore = defineStore({
  id: 'app-user',
  state: (): IUserState => ({
    token: Storage.get(ACCESS_TOKEN, ''),
    tenantId: Storage.get(TENANT_TOKEN, ''),
    // username: '',
    welcome: '',
    avatar: '',
    permissions: [],
    info: Storage.get(CURRENT_USER, {}),
    showLogin: false,
  }),
  getters: {
    getToken(): string {
      return this.token;
    },
    getTenantId(): number {
      return this.tenantId;
    },
    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: {
    setTenantId(tenantId: number) {
      this.tenantId = tenantId;
    },
    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) {
      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;
          const tenantId = result.tenantId;
          storage.set(ACCESS_TOKEN, token, ex);
          storage.set(TENANT_TOKEN, tenantId, ex);
          storage.set(CURRENT_USER, result, ex);
          storage.set(IS_LOCKSCREEN, false);
          storage.setCookie('satoken', token);
          storage.setCookie('tenantId', tenantId);
          this.setToken(token);
          this.setTenantId(tenantId);
          this.setUserInfo(result);
        }
        return Promise.resolve(response);
      } catch (e) {
        return Promise.reject(e);
      }
    },

    // 获取用户信息
    GetInfo() {
      return new Promise((resolve, reject) => {
        getUserInfo({ 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');
      storage.remove('lxUsername');
      return Promise.resolve('');
    },

    /**
     * 用户是否有某个权限
     * @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);
}
