// 统一API客户端 - 处理所有HTTP请求的封装层
// 包含拦截器、日志记录和后处理能力

import { getDefaultRequestConfig, getNotificationConfig } from '@/config/cad'
import { ElNotification, ElLoading } from 'element-plus'
import websocketService from './websocketService'
import Logger from '@/utils/logger'

// 日志记录系统
class ApiLogger {
  static log(method, url, requestData, response, duration) {
    // 获取当前用户信息
    const currentUser = this.getCurrentUser()

    const logEntry = {
      timestamp: new Date().toISOString(),
      method: method.toUpperCase(),
      url,
      requestData,
      status: response.ok ? 'success' : 'error',
      statusCode: response.status,
      duration: `${duration}ms`,
      responseSize: response.headers?.get('content-length') || 'unknown',
      user: currentUser?.username || 'anonymous' // 添加用户信息
    }

    // 为将来扩展预留：可以发送到日志服务
    this.sendToLogService(logEntry)
  }

  // 获取当前登录用户信息
  static getCurrentUser() {
    try {
      const userKey = 'user' // 与auth.js中的tokenConfig.userKey保持一致
      const savedUser = localStorage.getItem(userKey)
      return savedUser ? JSON.parse(savedUser) : null
    } catch {
      return null
    }
  }

  static sendToLogService() {
    // 后处理钩子：将来可扩展为发送到远程日志服务
    // 当前只保留接口，不实现具体逻辑
  }
}

// 后处理管理器
class PostProcessManager {
  static handlers = []

  static addHandler(handler) {
    this.handlers.push(handler)
  }

  static async process(response, requestContext) {
    // 执行所有后处理钩子
    for (const handler of this.handlers) {
      try {
        await handler(response, requestContext)
      } catch (error) {
        Logger.callbackError('PostProcessHandler', error)
        // 不影响主流程，但记录错误
      }
    }
  }
}

// 统一API客户端
class ApiClient {
  constructor() {
    this.defaultConfig = getDefaultRequestConfig()
    this.setupNotificationHandler()
    this.loadingInstance = null
  }

  // 设置通知处理器
  setupNotificationHandler() {
    // 通知处理器
    PostProcessManager.addHandler(async (response, context) => {
      // 默认显示通知，可通过配置关闭
      if (context.showNotification !== false && context.operationContext) {
        const { software, operation } = context.operationContext
        const notificationConfig = getNotificationConfig()

        if (response.ok) {
          ElNotification({
            title: notificationConfig.SUCCESS_TITLE,
            message: `${software} ${operation}成功`,
            type: 'success',
            position: notificationConfig.POSITION,
            duration: notificationConfig.SUCCESS_DURATION
          })
        } else {
          ElNotification({
            title: notificationConfig.ERROR_TITLE,
            message: `${software} ${operation}失败`,
            type: 'error',
            position: notificationConfig.POSITION,
            duration: notificationConfig.ERROR_DURATION
          })
        }
      }
    })

    // WebSocket日志记录处理器
    PostProcessManager.addHandler(async (response, context) => {
      if (context.operationContext) {
        const { software, operation } = context.operationContext
        const status = response.ok ? 'success' : 'failed'
        const details = response.ok ?
          `${software} ${operation}执行成功` :
          `${software} ${operation}执行失败: ${response.statusText || '未知错误'}`

        // 发送到WebSocket后台记录
        websocketService.logOperation(
          `${software} - ${operation}`,
          details,
          {
            action_type: 'execute',
            target_object: context.url,
            status: status,
            duration: context.duration || 0,
            operation_category: 'CAD操作'
          }
        )

        // CAD连接成功时同步更新信息面板软件状态
        if (response.ok && operation === '连接测试') {
          websocketService.getSoftwareList()
        }
      }
    })
  }

  // 核心请求方法
  async request(url, options = {}) {
    const startTime = Date.now()

    // 合并默认配置
    const config = {
      ...this.defaultConfig,
      ...options,
      headers: {
        ...this.defaultConfig.headers,
        ...options.headers
      }
    }

    const requestContext = {
      url,
      method: options.method || 'GET',
      startTime,
      requestData: options.body,
      operationContext: options.operationContext,
      showNotification: options.showNotification
    }

    try {
      // 请求拦截器
      this.interceptRequest(requestContext)

      // 发送请求
      const response = await fetch(url, config)
      const duration = Date.now() - startTime

      // 响应拦截器
      await this.interceptResponse(response, requestContext, duration)

      // 先解析响应数据
      const data = await this.parseResponse(response)

      // 优先检查数据中的success字段
      if (data && data.success === false) {
        throw new Error(data.error || '操作失败')
      }

      // 如果数据中没有success字段，才检查HTTP状态码
      if (data && typeof data.success === 'undefined' && !response.ok) {
        throw new Error(`HTTP ${response.status}: ${response.statusText}`)
      }

      // 成功后处理
      await this.handleSuccess(response, requestContext, data, duration)

      return { success: true, data }

    } catch (error) {
      const duration = Date.now() - startTime

      // 错误处理
      await this.handleError(error, requestContext, duration)

      return { success: false, error: error.message }
    }
  }

  // 请求拦截器
  interceptRequest(context) {
    // 显示loading动画
    this.showLoading(context)
  }

  // 显示loading动画
  showLoading(context) {
    if (context.showLoading !== false) {
      this.loadingInstance = ElLoading.service({
        lock: true,
        text: context.operationContext ?
          `正在执行${context.operationContext.operation}...` :
          '请求处理中...',
        background: 'rgba(0, 0, 0, 0.7)',
        customClass: 'custom-loading'
      })
    }
  }

  // 隐藏loading动画
  hideLoading() {
    if (this.loadingInstance) {
      this.loadingInstance.close()
      this.loadingInstance = null
    }
  }

  // 响应拦截器
  async interceptResponse() {
    // 隐藏loading动画
    this.hideLoading()
  }

  // 解析响应数据
  async parseResponse(response) {
    const contentType = response.headers.get('content-type')

    if (contentType && contentType.includes('application/json')) {
      return await response.json()
    }

    return await response.text()
  }


  // 成功处理
  async handleSuccess(response, context, data, duration) {
    // 记录日志
    ApiLogger.log(context.method, context.url, context.requestData, response, duration)

    // 执行后处理钩子
    await PostProcessManager.process(response, { ...context, data, duration })
  }

  // 错误处理
  async handleError(error, context, duration) {
    const errorResponse = {
      ok: false,
      status: 0,
      statusText: error.message,
      headers: new Map()
    }

    // 确保隐藏loading动画
    this.hideLoading()

    // 记录错误日志
    ApiLogger.log(context.method, context.url, context.requestData, errorResponse, duration)

    // 执行后处理钩子（显示失败通知）
    await PostProcessManager.process(errorResponse, { ...context, duration })
  }

  // 便捷方法
  async get(url, config = {}) {
    return this.request(url, { ...config, method: 'GET' })
  }

  async post(url, data, config = {}) {
    return this.request(url, {
      ...config,
      method: 'POST',
      body: JSON.stringify(data)
    })
  }

  async put(url, data, config = {}) {
    return this.request(url, {
      ...config,
      method: 'PUT',
      body: JSON.stringify(data)
    })
  }

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

// 导出单例实例
export const apiClient = new ApiClient()

// 导出后处理管理器，供其他模块注册钩子
export { PostProcessManager }

// 默认导出
export default apiClient