import { defineStore } from 'pinia';
import { removeRouteListener } from '@/utils/route-listener';
import { userLogout } from '@/api/user';
import { UserState } from './types';

const useUserStore = defineStore('user', {
  state: (): UserState => ({
    id: 0,
    account: '',
    loginName: '',
    name: '',
    empno: '',
    source: '',
    role: '',
    roleName: '',
    enable: true,
    relatedAccount: '',
    schoolId: 0,
    lastLoginIp: '',
    lastLoginTime: '',
    description: '',
    accessToken: '',
    accessTokenRefreshTime: '',
    schoolName: '',
  }),

  getters: {
    userInfo(state: UserState): UserState {
      return { ...state };
    },
    isSuperAdmin(state: UserState): boolean {
      return state.role === 'SYS_ADMIN';
    },
    isSchoolAdmin(state: UserState): boolean {
      return state.role === 'SCHOOL_ADMIN';
    },
  },

  actions: {
    setInfo(partial: Partial<UserState>) {
      this.$patch(partial);
    },
    resetInfo() {
      this.$reset();
    },
    // Logout
    async logout(authValid = true) {
      if (authValid) {
        await userLogout().catch(() => {});
      }
      this.resetInfo();
      removeRouteListener();

      window.location.reload();
    },
  },
  persist: {
    storage: sessionStorage,
  },
});

export default useUserStore;
