import { ref } from 'vue';
import { defineStore } from 'pinia';
import { useSSEStore } from './sse';
import { store } from '@/store';
import { resetRouter } from '@/router';
import { userLogin, userLogout } from '@/io';
export const useUserStore = defineStore(
  'user',
  () => {
    const sseStore = useSSEStore();
    const token = ref<string>();
    const perms = ref<string[]>([]);
    const userInfo = ref<Partial<API.UserEntity>>({});

    /** 清空登录态(token、userInfo...) */
    const clearLoginStatus = () => {
      token.value = '';
      perms.value = [];
      userInfo.value = {};
      resetRouter();
      setTimeout(() => {
        localStorage.clear();
      });
    };
    /** 登录成功保存token */
    const setToken = (_token: string) => {
      token.value = _token;
    };
    /** 登录 */
    const login = async (params: any) => {
      const data = await userLogin(params);
      console.log('data', data);
      // @ts-ignore
      setToken(data.msg);
    };
    /** 登出 */
    const logout = async () => {
      sseStore.closeEventSource();
      await userLogout();
      clearLoginStatus();
    };

    return {
      token,
      perms,
      userInfo,
      login,
      logout,
      clearLoginStatus,
    };
  },
  {
    persist: {
      pick: ['token'],
    },
  },
);

// 在组件setup函数外使用
export function useUserStoreWithOut() {
  return useUserStore(store);
}
