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: '',
    loginName: '',
    realName: '',
    sessionId: '',
    accessToken: '',
    schoolInfo: [],
    curSchoolInfo: {} as UserState['curSchoolInfo'],
    orgInfo: {} as UserState['orgInfo'],
    roleList: [],
    role: [],
    time: 0,
    appSource: '',
    pwdCount: 0,
    userLoginCheckResult: {
      userId: '',
      mobileNumber: '',
      pwdCount: 0,
    },
    roleSource: [],
    returnUrl: '',
    version: '',
    privilegeId: '',
    uiSetting: null,
    deviceId: '',
    platform: '',
  }),

  getters: {
    userInfo(state: UserState): UserState {
      return { ...state };
    },
  },

  actions: {
    setInfo(partial: Partial<UserState>) {
      this.$patch(partial);
    },
    resetInfo() {
      this.$reset();
    },
    // Logout
    async logout() {
      // TODO:如果token已经失效，不用调退出接口
      await userLogout().catch(() => {});
      this.resetInfo();
      removeRouteListener();
      window.location.reload();
    },
  },
  persist: {
    storage: sessionStorage,
  },
});

export default useUserStore;
