import { defineStore } from 'pinia';
import { type BriUserInfo, logoutAxios } from '@/api/login';
import router from '@/router/router';
import { StorageSerializers, useStorage } from '@vueuse/core';
import { tauriSessionStorage } from '@/utils/tauri/tauri-session';
import { isObject } from '@/utils/verify';
import { tauri_store_page_user_info } from '@/utils/constant';
import { windowLabel } from '@/utils/tauri/windows-util';
import { closeWindowByLabel } from '@/utils/tauri/windows-action';
import { useMeetingStore } from './meeting';
export type UserStore = ReturnType<typeof useUserStore>;
/**
 * 注册全局状态相关的store
 */
export const useUserStore = defineStore('user', () => {
  const meetingStore = useMeetingStore();
  /** 用户信息 */
  const userInfo = useStorage<BriUserInfo | null>('my_store_page_user_info', null, window.sessionStorage, {
    serializer: StorageSerializers.object,
  });
  if (!userInfo.value) {
    tauriSessionStorage.get(tauri_store_page_user_info).then((value) => {
      const obj = isObject(value) ? value : null;
      if (obj && 'id' in obj && 'schoolId' in obj) {
        userInfo.value = obj as unknown as BriUserInfo;
      }
    });
  }

  return {
    /** 用户信息 */
    userInfo,

    /** 设置用户信息 */
    async setUserInfo(_userInfo: BriUserInfo) {
      try {
        await tauriSessionStorage.set(tauri_store_page_user_info, _userInfo);
        await nextTick();
        await nextTick();
        userInfo.value = _userInfo;
      } catch (error: any) {
        userInfo.value = null;
        console.error('设置用户信息失败:', error);
      }
    },

    /**
     * 退出登录并跳转到登录页面
     */
    async logout() {
      logoutAxios();

      try {
        await tauriSessionStorage.remove(tauri_store_page_user_info);
        userInfo.value = null;
        await nextTick();
        meetingStore.clear();
        await closeWindowByLabel(windowLabel.floatList);
        router.replace('/login');
      } catch (error: any) {
        console.error('清除用户信息失败:', error);
      }
    },
  };
});
