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: null,
    account: '',
    name: '',
    role: null,
    orgId: null,
    categoryId: null,
    applyTaskId: null,
    openId: null,
    sessionId: '',
    token: '',
  }),

  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;
