import { onMounted, onUnmounted } from 'vue'
import { useUserStore } from '@/store/modules/user'
import { removeToken } from '@/utils/auth'
import { logout as logoutApi } from '@/api/login';

export function useBeforeUnload() {
  const userStore = useUserStore()

  // 处理浏览器关闭前的逻辑
  const handleBeforeUnload = async (event: BeforeUnloadEvent) => {
    // 检查用户是否已登录
    if (userStore.token) {
      try {
        // 执行安全退出逻辑
        await performSafeLogout()
      } catch (error) {
        // 即使API调用失败，也要清理本地数据
        performLocalCleanup()
      }
    }
  }

  // 执行安全退出操作
  const performSafeLogout = async () => {
    try {
      await logoutApi();
    } catch (error) {
    } finally {
      // 无论API调用是否成功，都要清理本地数据
      performLocalCleanup()
    }
  }

  // 执行本地数据清理
  const performLocalCleanup = () => {
    try {
      // 2. 清理token
      removeToken()
    } catch (error) {
    }
  }

  // 注册事件监听器
  onMounted(() => {
    window.addEventListener('unload', handleBeforeUnload)
  })

  // 清理事件监听器
  onUnmounted(() => {
    window.removeEventListener('unload', handleBeforeUnload)
  })

  return {
    performSafeLogout,
    performLocalCleanup
  }
}
