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

export interface OperationLogFilters {
  searchKeyword?: string
  module?: string
  action?: string
  status?: string
  startDate?: string
  endDate?: string
}

export interface OperationLogListParams extends PaginationParams {
  filters?: OperationLogFilters
}

export class OperationLogService {
  private static baseUrl = '/api/monitor/operation-logs'

  /**
   * 获取操作日志列表
   */
  static async getOperationLogs(params: OperationLogListParams = {}): Promise<PaginatedResponse<OperationLog>> {
    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.module && params.filters.module !== 'all') queryParams.append('module', params.filters.module)
        if (params.filters.action && params.filters.action !== 'all') queryParams.append('action', params.filters.action)
        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)
      }

      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 operation logs:', error)
      // 降级处理：返回mock数据
      return this.getMockData(params)
    }
  }

  /**
   * 获取操作日志详情
   */
  static async getOperationLogDetail(id: string): Promise<ApiResponse<OperationLog>> {
    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 operation log detail:', error)
      throw error
    }
  }

  /**
   * 导出操作日志
   */
  static async exportOperationLogs(filters?: OperationLogFilters): Promise<Blob> {
    try {
      const queryParams = new URLSearchParams()

      if (filters) {
        if (filters.searchKeyword) queryParams.append('searchKeyword', filters.searchKeyword)
        if (filters.module && filters.module !== 'all') queryParams.append('module', filters.module)
        if (filters.action && filters.action !== 'all') queryParams.append('action', filters.action)
        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}/export?${queryParams}`)

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

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

  /**
   * 获取操作日志统计信息
   */
  static async getOperationLogStats(filters?: OperationLogFilters): Promise<ApiResponse<{
    total: number
    success: number
    failed: number
    averageDuration: number
    moduleStats: Array<{ module: string, count: number }>
    actionStats: Array<{ action: string, count: number }>
  }>> {
    try {
      const queryParams = new URLSearchParams()

      if (filters) {
        if (filters.module && filters.module !== 'all') queryParams.append('module', filters.module)
        if (filters.action && filters.action !== 'all') queryParams.append('action', filters.action)
        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 operation log stats:', error)
      // 降级处理：返回mock统计数据
      return this.getMockStats()
    }
  }

  /**
   * Mock数据 - 用于降级处理
   */
  private static getMockData(params: OperationLogListParams): PaginatedResponse<OperationLog> {
    const mockLogs: OperationLog[] = [
      {
        id: 'op-1',
        userId: 'user-1',
        username: 'admin',
        operationTime: '2024-10-21T09:35:00',
        module: 'user',
        action: 'create',
        description: '创建用户账号: zhangsan',
        ipAddress: '192.168.1.100',
        requestUrl: '/api/users',
        requestMethod: 'POST',
        requestParams: JSON.stringify({ username: 'zhangsan', name: '张三' }),
        duration: 150,
        status: 'success',
      },
      {
        id: 'op-2',
        userId: 'user-2',
        username: 'zhangsan',
        operationTime: '2024-10-21T10:20:00',
        module: 'machinery',
        action: 'update',
        description: '更新农机信息: 约翰迪尔拖拉机',
        ipAddress: '192.168.1.101',
        requestUrl: '/api/machinery/123',
        requestMethod: 'PUT',
        duration: 89,
        status: 'success',
      },
      {
        id: 'op-3',
        userId: 'user-3',
        username: 'lisi',
        operationTime: '2024-10-21T11:25:00',
        module: 'role',
        action: 'delete',
        description: '删除角色: 临时操作员',
        ipAddress: '192.168.1.102',
        requestUrl: '/api/roles/456',
        requestMethod: 'DELETE',
        duration: 120,
        status: 'failed',
        errorMessage: '该角色下仍有关联用户，无法删除',
      },
      {
        id: 'op-4',
        userId: 'user-1',
        username: 'admin',
        operationTime: '2024-10-21T14:50:00',
        module: 'system',
        action: 'update',
        description: '修改系统配置: 会话超时时间',
        ipAddress: '192.168.1.100',
        requestUrl: '/api/system/settings',
        requestMethod: 'PUT',
        duration: 95,
        status: 'success',
      },
      {
        id: 'op-5',
        userId: 'user-2',
        username: 'zhangsan',
        operationTime: '2024-10-21T15:35:00',
        module: 'task',
        action: 'create',
        description: '创建作业任务: 小麦播种作业',
        ipAddress: '192.168.1.101',
        requestUrl: '/api/tasks',
        requestMethod: 'POST',
        duration: 180,
        status: 'success',
      },
      {
        id: 'op-6',
        userId: 'user-1',
        username: 'admin',
        operationTime: '2024-10-21T16:15:00',
        module: 'user',
        action: 'export',
        description: '导出用户列表数据',
        ipAddress: '192.168.1.100',
        requestUrl: '/api/users/export',
        requestMethod: 'GET',
        duration: 1250,
        status: 'success',
      },
    ]

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

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

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

      if (params.filters?.status && params.filters.status !== 'all') {
        if (log.status !== params.filters.status) 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
    failed: number
    averageDuration: number
    moduleStats: Array<{ module: string, count: number }>
    actionStats: Array<{ action: string, count: number }>
  }> {
    return {
      code: 200,
      message: 'success',
      success: true,
      data: {
        total: 6,
        success: 5,
        failed: 1,
        averageDuration: 314,
        moduleStats: [
          { module: 'user', count: 2 },
          { module: 'machinery', count: 1 },
          { module: 'role', count: 1 },
          { module: 'system', count: 1 },
          { module: 'task', count: 1 }
        ],
        actionStats: [
          { action: 'create', count: 2 },
          { action: 'update', count: 2 },
          { action: 'delete', count: 1 },
          { action: 'export', count: 1 }
        ]
      }
    }
  }
}