import { NetworkLog } from '@/types/monitor'
import { ApiResponse, PaginatedResponse, PaginationParams } from '@/types'

export interface NetworkLogFilters {
  searchKeyword?: string
  method?: string
  status?: string
  startDate?: string
  endDate?: string
  minResponseTime?: number
  maxResponseTime?: number
}

export interface NetworkLogListParams extends PaginationParams {
  filters?: NetworkLogFilters
}

export class NetworkLogService {
  private static baseUrl = '/api/monitor/network-logs'

  /**
   * 获取网络日志列表
   */
  static async getNetworkLogs(params: NetworkLogListParams = {}): Promise<PaginatedResponse<NetworkLog>> {
    try {
      const queryParams = new URLSearchParams()

      // 添加分页参数
      if (params.page) queryParams.append('page', params.page.toString())
      if (params.pageSize) queryParams.append('pageSize', params.pageSize.toString())

      // 添加筛选参数
      if (params.filters) {
        if (params.filters.searchKeyword) queryParams.append('searchKeyword', params.filters.searchKeyword)
        if (params.filters.method && params.filters.method !== 'all') queryParams.append('method', params.filters.method)
        if (params.filters.status && params.filters.status !== 'all') queryParams.append('status', params.filters.status)
        if (params.filters.startDate) queryParams.append('startDate', params.filters.startDate)
        if (params.filters.endDate) queryParams.append('endDate', params.filters.endDate)
        if (params.filters.minResponseTime) queryParams.append('minResponseTime', params.filters.minResponseTime.toString())
        if (params.filters.maxResponseTime) queryParams.append('maxResponseTime', params.filters.maxResponseTime.toString())
      }

      const response = await fetch(`${this.baseUrl}?${queryParams}`)

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

      const data = await response.json()
      return data
    } catch (error) {
      console.error('Failed to fetch network logs:', error)
      // 降级处理：返回mock数据
      return this.getMockData(params)
    }
  }

  /**
   * 获取网络日志详情
   */
  static async getNetworkLogDetail(id: string): Promise<ApiResponse<NetworkLog>> {
    try {
      const response = await fetch(`${this.baseUrl}/${id}`)

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

      const data = await response.json()
      return data
    } catch (error) {
      console.error('Failed to fetch network log detail:', error)
      throw error
    }
  }

  /**
   * 导出网络日志
   */
  static async exportNetworkLogs(filters?: NetworkLogFilters): Promise<Blob> {
    try {
      const queryParams = new URLSearchParams()

      if (filters) {
        if (filters.searchKeyword) queryParams.append('searchKeyword', filters.searchKeyword)
        if (filters.method && filters.method !== 'all') queryParams.append('method', filters.method)
        if (filters.status && filters.status !== 'all') queryParams.append('status', filters.status)
        if (filters.startDate) queryParams.append('startDate', filters.startDate)
        if (filters.endDate) queryParams.append('endDate', filters.endDate)
        if (filters.minResponseTime) queryParams.append('minResponseTime', filters.minResponseTime.toString())
        if (filters.maxResponseTime) queryParams.append('maxResponseTime', filters.maxResponseTime.toString())
      }

      const response = await fetch(`${this.baseUrl}/export?${queryParams}`)

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

      return response.blob()
    } catch (error) {
      console.error('Failed to export network logs:', error)
      throw error
    }
  }

  /**
   * 获取网络日志统计信息
   */
  static async getNetworkLogStats(filters?: NetworkLogFilters): Promise<ApiResponse<{
    total: number
    success: number
    clientError: number
    serverError: number
    averageResponseTime: number
    totalResponseSize: number
    methodStats: Array<{ method: string, count: number }>
    statusStats: Array<{ status: number, count: number }>
    topSlowRequests: Array<{ url: string, responseTime: number, count: number }>
  }>> {
    try {
      const queryParams = new URLSearchParams()

      if (filters) {
        if (filters.method && filters.method !== 'all') queryParams.append('method', filters.method)
        if (filters.status && filters.status !== 'all') queryParams.append('status', filters.status)
        if (filters.startDate) queryParams.append('startDate', filters.startDate)
        if (filters.endDate) queryParams.append('endDate', filters.endDate)
      }

      const response = await fetch(`${this.baseUrl}/stats?${queryParams}`)

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

      const data = await response.json()
      return data
    } catch (error) {
      console.error('Failed to fetch network log stats:', error)
      // 降级处理：返回mock统计数据
      return this.getMockStats()
    }
  }

  
  /**
   * Mock数据 - 用于降级处理
   */
  private static getMockData(params: NetworkLogListParams): PaginatedResponse<NetworkLog> {
    const mockLogs: NetworkLog[] = [
      {
        id: 'net-1',
        timestamp: '2024-10-21T09:35:00',
        method: 'POST',
        url: '/api/users',
        requestParams: 'username=zhangsan&name=张三',
        responseStatus: 200,
        responseTime: 150,
        responseSize: 256,
        clientIp: '192.168.1.100',
        userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/118.0.0.0',
        userId: 'user-1',
        username: 'admin',
      },
      {
        id: 'net-2',
        timestamp: '2024-10-21T10:20:00',
        method: 'GET',
        url: '/api/machinery/list',
        requestParams: 'page=1&size=10',
        responseStatus: 200,
        responseTime: 89,
        responseSize: 4096,
        clientIp: '192.168.1.101',
        userAgent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) Safari/17.0',
        userId: 'user-2',
        username: 'zhangsan',
      },
      {
        id: 'net-3',
        timestamp: '2024-10-21T11:25:00',
        method: 'DELETE',
        url: '/api/roles/456',
        responseStatus: 400,
        responseTime: 120,
        responseSize: 128,
        clientIp: '192.168.1.102',
        userAgent: 'Mozilla/5.0 (X11; Linux x86_64) Chrome/118.0.0.0',
        userId: 'user-3',
        username: 'lisi',
      },
      {
        id: 'net-4',
        timestamp: '2024-10-21T14:50:00',
        method: 'PUT',
        url: '/api/system/settings',
        requestParams: 'sessionTimeout=30',
        responseStatus: 200,
        responseTime: 95,
        responseSize: 512,
        clientIp: '192.168.1.100',
        userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/118.0.0.0',
        userId: 'user-1',
        username: 'admin',
      },
      {
        id: 'net-5',
        timestamp: '2024-10-21T15:35:00',
        method: 'POST',
        url: '/api/tasks',
        responseStatus: 201,
        responseTime: 180,
        responseSize: 1024,
        clientIp: '192.168.1.101',
        userAgent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) Safari/17.0',
        userId: 'user-2',
        username: 'zhangsan',
      },
      {
        id: 'net-6',
        timestamp: '2024-10-21T16:15:00',
        method: 'GET',
        url: '/api/users/export',
        requestParams: 'format=excel',
        responseStatus: 200,
        responseTime: 1250,
        responseSize: 102400,
        clientIp: '192.168.1.100',
        userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/118.0.0.0',
        userId: 'user-1',
        username: 'admin',
      },
    ]

    // 应用筛选器
    let filteredLogs = mockLogs.filter(log => {
      if (params.filters?.searchKeyword) {
        const keyword = params.filters.searchKeyword.toLowerCase()
        if (!log.url.toLowerCase().includes(keyword) &&
            !(log.username && log.username.toLowerCase().includes(keyword))) {
          return false
        }
      }

      if (params.filters?.method && params.filters.method !== 'all') {
        if (log.method !== params.filters.method) return false
      }

      if (params.filters?.status && params.filters.status !== 'all') {
        const status = log.responseStatus
        switch (params.filters.status) {
          case '2xx':
            if (status < 200 || status >= 300) return false
            break
          case '4xx':
            if (status < 400 || status >= 500) return false
            break
          case '5xx':
            if (status < 500) return false
            break
        }
      }

      if (params.filters?.minResponseTime && log.responseTime < params.filters.minResponseTime) {
        return false
      }

      if (params.filters?.maxResponseTime && log.responseTime > params.filters.maxResponseTime) {
        return false
      }

      return true
    })

    // 应用分页
    const page = params.page || 1
    const pageSize = params.pageSize || 10
    const startIndex = (page - 1) * pageSize
    const endIndex = startIndex + pageSize
    const paginatedLogs = filteredLogs.slice(startIndex, endIndex)

    return {
      code: 200,
      message: 'success',
      success: true,
      data: paginatedLogs,
      pagination: {
        page,
        pageSize,
        total: filteredLogs.length,
        totalPages: Math.ceil(filteredLogs.length / pageSize)
      }
    }
  }

  private static getMockStats(): ApiResponse<{
    total: number
    success: number
    clientError: number
    serverError: number
    averageResponseTime: number
    totalResponseSize: number
    methodStats: Array<{ method: string, count: number }>
    statusStats: Array<{ status: number, count: number }>
    topSlowRequests: Array<{ url: string, responseTime: number, count: number }>
  }> {
    return {
      code: 200,
      message: 'success',
      success: true,
      data: {
        total: 6,
        success: 4,
        clientError: 1,
        serverError: 1,
        averageResponseTime: 314,
        totalResponseSize: 108416,
        methodStats: [
          { method: 'GET', count: 2 },
          { method: 'POST', count: 2 },
          { method: 'PUT', count: 1 },
          { method: 'DELETE', count: 1 }
        ],
        statusStats: [
          { status: 200, count: 3 },
          { status: 201, count: 1 },
          { status: 400, count: 1 },
          { status: 500, count: 1 }
        ],
        topSlowRequests: [
          { url: '/api/users/export', responseTime: 1250, count: 1 },
          { url: '/api/tasks', responseTime: 180, count: 1 }
        ]
      }
    }
  }
}