import { useScreenStore } from '@/stores/screen'

const BASE_URL = import.meta.env.VITE_API_BASE_URL || '/dev-api'

class Request {
  constructor() {
    this.baseURL = BASE_URL
    this.timeout = 10000
  }

  async request(url, options = {}) {
    const {
      method = 'GET',
      data = null,
      headers = {},
      timeout = this.timeout
    } = options

    const controller = new AbortController()
    const timeoutId = setTimeout(() => controller.abort(), timeout)

    try {
      const config = {
        method,
        headers: {
          'Content-Type': 'application/json',
          ...headers
        },
        signal: controller.signal
      }

      if (data && (method === 'POST' || method === 'PUT' || method === 'PATCH')) {
        config.body = JSON.stringify(data)
      }

      const response = await fetch(`${this.baseURL}${url}`, config)
      clearTimeout(timeoutId)

      if (!response.ok) {
        throw new Error(`HTTP ${response.status}: ${response.statusText}`)
      }

      const result = await response.json()

      // 检查业务状态码（非 200 视为错误）
      if (result.code !== 200 && result.code !== undefined) {
        throw new Error(result.msg || '请求失败')
      }

      return result
    } catch (error) {
      clearTimeout(timeoutId)
      
      if (error.name === 'AbortError') {
        throw new Error('请求超时')
      }
      
      console.error(`[Request Error] ${method} ${url}:`, error)
      throw error
    }
  }

  get(url, options = {}) {
    return this.request(url, { ...options, method: 'GET' })
  }

  post(url, data, options = {}) {
    return this.request(url, { ...options, method: 'POST', data })
  }

  put(url, data, options = {}) {
    return this.request(url, { ...options, method: 'PUT', data })
  }

  delete(url, options = {}) {
    return this.request(url, { ...options, method: 'DELETE' })
  }
}

export const http = new Request()
export default http