/**
 * API客户端服务
 * 提供统一的HTTP请求接口，自动处理认证token
 */
class ApiClient {
  private baseURL: string

  constructor() {
    // 判断hostname是否为IP地址
    const isIPAddress = this.isIPAddress(window.location.hostname)
    
    if (isIPAddress) {
      // 如果是IP地址，添加3001端口
      this.baseURL = `${window.location.protocol}//${window.location.hostname}:3001`
    } else {
      // 如果是域名，直接使用域名（通常域名会通过反向代理处理端口）
      this.baseURL = `${window.location.protocol}//${window.location.hostname}`
    }
    
    console.log('API BaseURL:', this.baseURL)
  }

  /**
   * 判断字符串是否为IP地址
   */
  private isIPAddress(hostname: string): boolean {
    // IPv4地址正则表达式
    const ipv4Regex = /^(\d{1,3}\.){3}\d{1,3}$/
    
    // IPv6地址正则表达式（简化版）
    const ipv6Regex = /^([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$/
    
    return ipv4Regex.test(hostname) || ipv6Regex.test(hostname)
  }

  /**
   * 获取认证token
   */
  private getAuthToken(): string | null {
    return localStorage.getItem('auth_token')
  }

  /**
   * 创建请求headers
   */
  private createHeaders(customHeaders: Record<string, string> = {}): Record<string, string> {
    const headers: Record<string, string> = {
      'Content-Type': 'application/json',
      ...customHeaders
    }

    const token = this.getAuthToken()
    if (token) {
      headers['Authorization'] = `Bearer ${token}`
    }

    return headers
  }

  /**
   * 处理响应
   */
  private async handleResponse<T>(response: Response): Promise<T> {
    if (!response.ok) {
      // 如果是认证失败，清除本地token
      if (response.status === 401) {
        localStorage.removeItem('auth_token')
        localStorage.removeItem('auth_user')
        // 可以触发全局的登录状态重置事件
        window.dispatchEvent(new CustomEvent('auth:token-expired'))
      }

      const errorData = await response.json().catch(() => ({}))
      throw new Error(errorData.message || `HTTP ${response.status}: ${response.statusText}`)
    }

    return response.json()
  }

  /**
   * GET请求
   */
  async get<T>(endpoint: string, customHeaders?: Record<string, string>): Promise<T> {
    try {
      const response = await fetch(`${this.baseURL}${endpoint}`, {
        method: 'GET',
        headers: this.createHeaders(customHeaders),
      })

      return this.handleResponse<T>(response)
    } catch (error: any) {
      // 捕获网络错误（如 Failed to fetch）
      if (error?.name === 'TypeError' && error?.message?.includes('fetch')) {
        throw new Error(`网络连接失败: 无法连接到服务器 ${this.baseURL}。请检查服务器是否正常运行。`)
      }
      throw error
    }
  }

  /**
   * POST请求
   */
  async post<T>(
    endpoint: string, 
    data?: any, 
    customHeaders?: Record<string, string>
  ): Promise<T> {
    try {
      const headers = this.createHeaders(customHeaders)
      
      let body: string | FormData | undefined
      
      // 如果data是FormData，不设置Content-Type让浏览器自动设置
      if (data instanceof FormData) {
        body = data
        delete headers['Content-Type']
      } else if (data !== undefined) {
        body = JSON.stringify(data)
      }

      const response = await fetch(`${this.baseURL}${endpoint}`, {
        method: 'POST',
        headers,
        body,
      })

      return this.handleResponse<T>(response)
    } catch (error: any) {
      // 捕获网络错误（如 Failed to fetch）
      if (error?.name === 'TypeError' && error?.message?.includes('fetch')) {
        throw new Error(`网络连接失败: 无法连接到服务器 ${this.baseURL}。请检查服务器是否正常运行。`)
      }
      throw error
    }
  }

  /**
   * PUT请求
   */
  async put<T>(
    endpoint: string, 
    data?: any, 
    customHeaders?: Record<string, string>
  ): Promise<T> {
    const response = await fetch(`${this.baseURL}${endpoint}`, {
      method: 'PUT',
      headers: this.createHeaders(customHeaders),
      body: data ? JSON.stringify(data) : undefined,
    })

    return this.handleResponse<T>(response)
  }

  /**
   * DELETE请求
   */
  async delete<T>(endpoint: string, customHeaders?: Record<string, string>): Promise<T> {
    try {
      const response = await fetch(`${this.baseURL}${endpoint}`, {
        method: 'DELETE',
        headers: this.createHeaders(customHeaders),
      })

      return this.handleResponse<T>(response)
    } catch (error: any) {
      // 捕获网络错误（如 Failed to fetch）
      if (error?.name === 'TypeError' && error?.message?.includes('fetch')) {
        throw new Error(`网络连接失败: 无法连接到服务器 ${this.baseURL}。请检查服务器是否正常运行。`)
      }
      throw error
    }
  }

  /**
   * 上传文件的POST请求
   */
  async postFormData<T>(
    endpoint: string, 
    formData: FormData, 
    customHeaders?: Record<string, string>
  ): Promise<T> {
    return this.post<T>(endpoint, formData, customHeaders)
  }

  /**
   * 下载文件
   */
  async downloadFile(endpoint: string, filename?: string): Promise<void> {
    const response = await fetch(`${this.baseURL}${endpoint}`, {
      method: 'GET',
      headers: this.createHeaders(),
    })

    if (!response.ok) {
      throw new Error(`下载失败: ${response.status} ${response.statusText}`)
    }

    const blob = await response.blob()
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = filename || 'download'
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
  }

  /**
   * 获取base URL
   */
  getBaseURL(): string {
    return this.baseURL
  }

  /**
   * 设置base URL
   */
  setBaseURL(url: string): void {
    this.baseURL = url
  }
}

// 创建单例实例
export const apiClient = new ApiClient()
export default apiClient 