import { ref, onMounted, onUnmounted } from 'vue'

export function useNetworkStatus() {
  const isOnline = ref(navigator.onLine)
  const isSlowConnection = ref(false)

  const updateOnlineStatus = () => {
    isOnline.value = navigator.onLine
    console.log('网络状态变化:', isOnline.value ? '在线' : '离线')
  }

  const checkConnectionSpeed = async () => {
    if (!isOnline.value) return

    try {
      const startTime = Date.now()
      await fetch('/favicon.ico', {
        method: 'HEAD',
        cache: 'no-cache'
      })
      const endTime = Date.now()
      const duration = endTime - startTime

      // 如果请求时间超过3秒，认为是慢连接
      isSlowConnection.value = duration > 3000
      console.log('连接速度检测:', duration + 'ms', isSlowConnection.value ? '慢连接' : '正常')
    } catch (error) {
      console.warn('连接速度检测失败:', error)
      isSlowConnection.value = true
    }
  }

  onMounted(() => {
    window.addEventListener('online', updateOnlineStatus)
    window.addEventListener('offline', updateOnlineStatus)
    
    // 初始检测连接速度
    checkConnectionSpeed()
    
    // 每30秒检测一次连接速度
    const speedCheckInterval = setInterval(checkConnectionSpeed, 30000)
    
    onUnmounted(() => {
      window.removeEventListener('online', updateOnlineStatus)
      window.removeEventListener('offline', updateOnlineStatus)
      clearInterval(speedCheckInterval)
    })
  })

  return {
    isOnline,
    isSlowConnection,
    checkConnectionSpeed
  }
}
