// ***********************************************
// This example commands.js shows you how to
// create various custom commands and overwrite
// existing commands.
//
// For more comprehensive examples of custom
// commands please read more here:
// https://on.cypress.io/custom-commands
// ***********************************************

// 模拟登录状态
Cypress.Commands.add('mockLogin', () => {

  cy.window().then((win) => {
    const mockMenuList = [
      { name: '首页', url: '/dashboard' },
      { name: '除尘器总览', url: '/dust-overview' },
      { name: '除尘器监控', url: '/monitor' },
      { name: '布袋周期', url: '/collectorList' },
      { name: '告警总览', url: '/alerts' },
      { name: '设备管理', url: '/device-management' },
      { name: '我的闭环', url: '/my-loop' }
    ]
    win.localStorage.setItem('menuList', JSON.stringify(mockMenuList))

    // 预设一个json
    const json =  {
        "id": 26,
        "customerId": 26,
        "officeId": 1,
        "name": "纵横钢铁",
        "account": "zongheng_admin",
        "customerName": "纵横钢铁",
        "ultralowBoard": null,
        "officeNameList": null,
        "roleNameList": [
            "admin",
            "全厂基础角色",
            "dctom"
        ],
        "dataBranchFactoryId": "",
        "enable": true
    }

    // 设置cookie (对中文内容进行URL编码)
    cy.setCookie('customerName', encodeURIComponent(json.customerName))
    cy.setCookie('dataBranchFactoryId', String(json.dataBranchFactoryId))
    cy.setCookie('customerId', String(json.customerId))
    cy.setCookie('userId', String(json.id))
    cy.setCookie('userName', encodeURIComponent(json.name))
    cy.setCookie('TOKEN', '24cb57d7b2024dcb9bd8b54554418905')
    win.sessionStorage.setItem('userId', json.id)
  })
})

// 登录命令
Cypress.Commands.add('loginWithUI', (username = 'admin', password = 'password123') => {
  cy.visit('/#/login')
  cy.get('[data-testid="login-username-input"]').clear().type(username)
  cy.get('[data-testid="login-password-input"]').clear().type(password)
  
  // 处理验证码（如果需要）
  cy.get('body').then(($body) => {
    if ($body.find('[data-testid="login-captcha-input"]').length > 0) {
      cy.get('[data-testid="login-captcha-input"]').type('test')
    }
  })
  
  cy.get('[data-testid="login-submit-button"]').click()
  
  // 等待登录成功跳转
  cy.url().should('not.include', '/#/login')
})

// 导航到特定页面
Cypress.Commands.add('navigateToPage', (pageName) => {
  cy.get(`[data-testid="menu-item-${pageName}"]`).click()
  cy.waitForPageLoad()
})

// 检查表格数据加载
Cypress.Commands.add('checkTableDataLoaded', (tableSelector = '[data-testid="common-table"]') => {
  cy.get(tableSelector).should('be.visible')
  cy.get(`${tableSelector} [data-testid="el-table"]`).should('be.visible')
})

// 搜索功能
Cypress.Commands.add('searchInTable', (searchText, inputSelector = '[data-testid="dust-device-name-input"]') => {
  cy.get(inputSelector).clear().type(searchText)
  cy.get('[data-testid="dust-search-button"]').click()
  cy.wait(1000) // 等待搜索结果
})

// 检查响应式设计
Cypress.Commands.add('checkResponsive', () => {
  // 检查不同屏幕尺寸
  const viewports = [
    { width: 1920, height: 1080 }, // 桌面
    { width: 1280, height: 720 },  // 笔记本
    { width: 768, height: 1024 },  // 平板
  ]
  
  viewports.forEach(viewport => {
    cy.viewport(viewport.width, viewport.height)
    cy.wait(500)
    cy.get('body').should('be.visible')
  })
})

// 验证健康状态指示器
Cypress.Commands.add('verifyHealthIndicators', () => {
  cy.get('[data-testid="dashboard-health-score"]').should('be.visible')
  cy.get('[data-testid="dashboard-bag-progress"]').should('be.visible')
  cy.get('[data-testid="dashboard-pulse-valve-progress"]').should('be.visible')
  cy.get('[data-testid="dashboard-poppet-valve-progress"]').should('be.visible')
})

// ========== CollectorList 专用命令 ==========

// 导航到布袋周期页面
Cypress.Commands.add('navigateToCollectorList', () => {
  cy.visit('/#/collectorList')
  cy.get('[data-testid="collector-list-container"]').should('be.visible')
})

// 搜索布袋周期数据
Cypress.Commands.add('searchCollectorData', (compart = '', dusterName = '', dateRange = null) => {
  if (compart) {
    cy.get('[data-testid="collector-compart-input"]').clear().type(compart)
  }
  
  if (dusterName) {
    cy.get('[data-testid="collector-duster-name-input"]').clear().type(dusterName)
  }
  
  if (dateRange) {
    cy.get('[data-testid="collector-date-picker"]').click()
    cy.get('.el-picker-panel').should('be.visible')
    
    // 选择日期范围
    if (dateRange.startDate) {
      cy.get('.el-date-table td.available').first().click()
    }
    if (dateRange.endDate) {
      cy.get('.el-date-table td.available').eq(5).click()
    }
  }
  
  cy.get('[data-testid="collector-search-button"]').click()
  cy.wait(1000) // 等待搜索结果
})

// 重置搜索条件
Cypress.Commands.add('resetCollectorSearch', () => {
  cy.get('[data-testid="collector-reset-button"]').click()
  
  // 验证输入框已清空
  cy.get('[data-testid="collector-compart-input"]').should('have.value', '')
  cy.get('[data-testid="collector-duster-name-input"]').should('have.value', '')
})

// 打开更换周期分析对话框
Cypress.Commands.add('openAnalysisDialog', (method = 'button') => {
  if (method === 'button') {
    cy.get('[data-testid="collector-analysis-button"]').click()
  } else if (method === 'dblclick') {
    cy.get('[data-testid="collector-duster-name-link"]').first().dblclick()
  }
  
  cy.get('.dustListDialog').should('be.visible')
  cy.get('.el-dialog__title').should('contain', '更换周期分析')
})

// 关闭分析对话框
Cypress.Commands.add('closeAnalysisDialog', () => {
  cy.get('.dustListDialog .el-dialog__headerbtn').click()
  cy.get('.dustListDialog').should('not.exist')
})

// 验证表格数据完整性
Cypress.Commands.add('verifyCollectorTableData', (expectedData) => {
  cy.get('[data-testid="collector-common-table"]').within(() => {
    if (expectedData.rowCount) {
      cy.get('.el-table__body tr').should('have.length', expectedData.rowCount)
    }
    
    if (expectedData.firstRow) {
      cy.get('.el-table__body tr').first().within(() => {
        Object.keys(expectedData.firstRow).forEach((key, index) => {
          cy.get('td').eq(index + 1).should('contain', expectedData.firstRow[key])
        })
      })
    }
  })
})

// 验证表格列标题
Cypress.Commands.add('verifyCollectorTableHeaders', () => {
  const expectedHeaders = [
    '序号',
    '除尘器名称',
    '仓室',
    '布袋位置（排/列）',
    '布袋更换提醒时间',
    '更换时间',
    '更换人',
    '更换周期(与上次更换比)'
  ]
  
  cy.get('[data-testid="collector-common-table"]').within(() => {
    expectedHeaders.forEach(header => {
      cy.get('.el-table__header').should('contain', header)
    })
  })
})

// 模拟API响应
Cypress.Commands.add('mockCollectorAPI', (apiType, responseData) => {
  const apiMap = {
    'list': '**/bag/cycle/getReplaceListPage',
    'dusterList': '**/bag/cycle/getDusterList',
    'analysis': '**/bag/cycle/getReplaceAnalysis'
  }
  
  cy.intercept('GET', apiMap[apiType], {
    statusCode: 200,
    body: {
      code: 200,
      data: responseData,
      message: 'success'
    }
  }).as(`mock${apiType}API`)
})

// 等待页面加载完成 - 通用版本
Cypress.Commands.add('waitForPageLoad', () => {
  // 等待页面基本加载完成
  cy.get('body').should('be.visible')
  
  // 等待可能的加载动画完成
  cy.wait(1000)
  
  // 检查是否有常见的加载指示器，如果有则等待其消失
  cy.get('body').then(($body) => {
    if ($body.find('.loading, .spinner, .el-loading-mask').length > 0) {
      cy.get('.loading, .spinner, .el-loading-mask').should('not.exist')
    }
  })
})

// ========== Monitor 专用命令 ==========

// 导航到除尘器监控页面
Cypress.Commands.add('navigateToMonitor', () => {
  cy.visit('/#/monitor')
  cy.get('[data-testid="dust-monitoring-container"]').should('be.visible')
})

// 选择除尘器
Cypress.Commands.add('selectDuster', (dusterName) => {
  cy.get('[data-testid="dust-monitoring-duster-select"]').click()
  cy.get('.el-select-dropdown').should('be.visible')
  
  if (dusterName) {
    cy.get('.el-select-dropdown__item').contains(dusterName).click()
  } else {
    cy.get('.el-select-dropdown__item').first().click()
  }
})

// 设置监控时间范围
Cypress.Commands.add('setMonitorTimeRange', (startDate, endDate) => {
  cy.get('[data-testid="dust-monitoring-date-picker"]').click()
  cy.get('.el-picker-panel').should('be.visible')
  
  if (startDate) {
    cy.get('.el-date-table td.available').first().click()
  }
  if (endDate) {
    cy.get('.el-date-table td.available').eq(5).click()
  }
  
  cy.get('.el-picker-panel__footer .el-button--primary').click()
})

// ========== Alerts 专用命令 ==========

// 导航到告警总览页面
Cypress.Commands.add('navigateToAlerts', () => {
  cy.visit('/#/alerts')
  cy.get('.page-container').should('be.visible')
})

// 搜索告警
Cypress.Commands.add('searchAlerts', (eventName, location, dusterName, deviceType) => {
  if (eventName) {
    cy.get('input[placeholder="请输入事件名称"]').clear().type(eventName)
  }
  
  if (location) {
    cy.get('input[placeholder="请输入发生位置"]').clear().type(location)
  }
  
  if (dusterName) {
    cy.get('input[placeholder="请输入除尘器名称"]').clear().type(dusterName)
  }
  
  if (deviceType) {
    cy.get('.el-select').click()
    cy.get('.el-select-dropdown__item').contains(deviceType).click()
  }
  
  cy.get('.search-btn-balck-theme').click()
  cy.wait(1000)
})

// 选择告警类型
Cypress.Commands.add('selectAlertType', (type) => {
  const typeMap = {
    'suspend': '挂起期间告警',
    'non-suspend': '非挂起期间告警',
    'all': '全部告警'
  }
  
  cy.get('.el-radio').contains(typeMap[type]).click()
})

// ========== Device Management 专用命令 ==========

// 导航到设备管理页面
Cypress.Commands.add('navigateToDeviceManagement', () => {
  cy.visit('/#/management/device-management')
  cy.get('[data-testid="equipment-management-container"]').should('be.visible')
})

// 搜索设备
Cypress.Commands.add('searchDevices', (productionLine, dusterName, deviceName, deviceType) => {
  if (productionLine) {
    cy.get('[data-testid="equipment-production-line-select"]').click()
    cy.get('.el-select-dropdown__item').contains(productionLine).click()
  }
  
  if (dusterName) {
    cy.get('[data-testid="equipment-duster-name-input"]').clear().type(dusterName)
  }
  
  if (deviceName) {
    cy.get('[data-testid="equipment-device-name-input"]').clear().type(deviceName)
  }
  
  if (deviceType) {
    cy.get('[data-testid="equipment-device-type-select"]').click()
    cy.get('.el-select-dropdown__item').contains(deviceType).click()
  }
  
  cy.get('[data-testid="equipment-search-button"]').click()
  cy.wait(1000)
})

// 重置设备搜索条件
Cypress.Commands.add('resetDeviceSearch', () => {
  cy.get('[data-testid="equipment-reset-button"]').click()
  
  // 验证输入框已清空
  cy.get('[data-testid="equipment-duster-name-input"]').should('have.value', '')
  cy.get('[data-testid="equipment-device-name-input"]').should('have.value', '')
})

// ========== My Loop 专用命令 ==========

// 导航到我的待办页面
Cypress.Commands.add('navigateToMyAgency', () => {
  cy.visit('/#/my-loop/myAgency')
  cy.get('[data-testid="my-agency-container"]').should('be.visible')
})

// 导航到我的已办页面
Cypress.Commands.add('navigateToMyDone', () => {
  cy.visit('/#/my-loop/myDone')
  cy.get('.my-done').should('be.visible')
})

// 搜索待办事项
Cypress.Commands.add('searchMyAgency', (eventName, keyword, productionLine, deviceType) => {
  if (eventName) {
    cy.get('[data-testid="my-agency-event-name-input"]').clear().type(eventName)
  }
  
  if (keyword) {
    cy.get('[data-testid="my-agency-keyword-input"]').clear().type(keyword)
  }
  
  if (productionLine) {
    cy.get('[data-testid="my-agency-production-line-select"]').click()
    cy.get('.el-select-dropdown__item').contains(productionLine).click()
  }
  
  if (deviceType) {
    cy.get('[data-testid="my-agency-device-type-select"]').click()
    cy.get('.el-select-dropdown__item').contains(deviceType).click()
  }
  
  cy.get('[data-testid="my-agency-search-button"]').click()
  cy.wait(1000)
})

// 重置待办搜索条件
Cypress.Commands.add('resetMyAgencySearch', () => {
  cy.get('[data-testid="my-agency-reset-button"]').click()
  
  // 验证输入框已清空
  cy.get('[data-testid="my-agency-event-name-input"]').should('have.value', '')
  cy.get('[data-testid="my-agency-keyword-input"]').should('have.value', '')
})

// 搜索已办事项
Cypress.Commands.add('searchMyDone', (eventName, keyword, productionLine) => {
  if (eventName) {
    cy.get('input[placeholder="请输入事件名称"]').clear().type(eventName)
  }
  
  if (keyword) {
    cy.get('input[placeholder="请输入"]').clear().type(keyword)
  }
  
  if (productionLine) {
    cy.get('.el-select').click()
    cy.get('.el-select-dropdown__item').contains(productionLine).click()
  }
  
  cy.get('.search-btn-balck-theme').click()
  cy.wait(1000)
})

// 重置已办搜索条件
Cypress.Commands.add('resetMyDoneSearch', () => {
  cy.get('.reset-btn-balck-theme').click()
  
  // 验证输入框已清空
  cy.get('input[placeholder="请输入事件名称"]').should('have.value', '')
  cy.get('input[placeholder="请输入"]').should('have.value', '')
})

// ========== API 异常收集系统 ==========

// 全局API错误收集器
let apiErrors = []

// 启动API异常收集
Cypress.Commands.add('startAPIErrorCollection', () => {
  apiErrors = []
  
  // 拦截所有API请求
  cy.intercept('**', (req) => {
    const startTime = Date.now()
    
    req.continue((res) => {
      const duration = Date.now() - startTime
      
      // 提取API路径和分类
      const urlObj = new URL(req.url)
      const apiPath = urlObj.pathname
      const apiCategory = getAPICategory(apiPath)
      const endpoint = getEndpointName(apiPath)
      
      // 收集详细的API异常信息
      const apiInfo = {
        method: req.method,
        url: req.url,
        apiPath: apiPath,
        endpoint: endpoint,
        apiCategory: apiCategory,
        statusCode: res.statusCode,
        statusMessage: res.statusMessage,
        duration: duration,
        timestamp: new Date().toISOString(),
        isError: res.statusCode >= 400,
        isSlow: duration > 5000,
        requestBody: req.body,
        responseBody: res.body,
        // 错误详细信息
        errorType: res.statusCode >= 400 ? getErrorType(res.statusCode) : null,
        severity: res.statusCode >= 400 ? getErrorSeverity(res.statusCode) : null,
        errorMessage: res.statusCode >= 400 ? getErrorMessage(res.statusCode, res.statusMessage, res.body) : null
      }
      
      // 如果是错误或慢请求，记录到收集器
      if (apiInfo.isError || apiInfo.isSlow) {
        apiErrors.push(apiInfo)
        console.log('API异常收集:', apiInfo)
      }
    })
  })
})

// 获取API分类
function getAPICategory(apiPath) {
  if (apiPath.includes('/login') || apiPath.includes('/auth')) return '认证接口'
  if (apiPath.includes('/user') || apiPath.includes('/profile')) return '用户接口'
  if (apiPath.includes('/alert') || apiPath.includes('/alarm')) return '告警接口'
  if (apiPath.includes('/device') || apiPath.includes('/equipment')) return '设备接口'
  if (apiPath.includes('/data') || apiPath.includes('/query')) return '数据接口'
  if (apiPath.includes('/report') || apiPath.includes('/export')) return '报表接口'
  if (apiPath.includes('/upload') || apiPath.includes('/file')) return '文件接口'
  if (apiPath.includes('/config') || apiPath.includes('/setting')) return '配置接口'
  return '其他接口'
}

// 获取端点名称
function getEndpointName(apiPath) {
  const segments = apiPath.split('/').filter(segment => segment)
  if (segments.length === 0) return '根路径'
  if (segments.length === 1) return segments[0]
  return segments.slice(-2).join('/')
}

// 获取错误类型
function getErrorType(statusCode) {
  if (statusCode >= 400 && statusCode < 500) return '客户端错误'
  if (statusCode >= 500) return '服务器错误'
  return '未知错误'
}

// 获取错误严重性
function getErrorSeverity(statusCode) {
  if (statusCode === 401 || statusCode === 403) return '高'
  if (statusCode >= 500) return '高'
  if (statusCode === 404) return '中'
  if (statusCode >= 400 && statusCode < 500) return '中'
  return '低'
}

// 获取错误消息
function getErrorMessage(statusCode, statusMessage, responseBody) {
  let message = `${statusCode} ${statusMessage}`
  
  // 尝试从响应体中提取更详细的错误信息
  if (responseBody) {
    try {
      if (typeof responseBody === 'string') {
        const parsed = JSON.parse(responseBody)
        if (parsed.message) message += ` - ${parsed.message}`
        if (parsed.error) message += ` - ${parsed.error}`
      } else if (typeof responseBody === 'object') {
        if (responseBody.message) message += ` - ${responseBody.message}`
        if (responseBody.error) message += ` - ${responseBody.error}`
      }
    } catch (e) {
      // 解析失败，使用原始消息
    }
  }
  
  return message
}

// 获取API异常统计
Cypress.Commands.add('getAPIErrors', () => {
  const errors = apiErrors.filter(e => e.isError)
  const slowRequests = apiErrors.filter(e => e.isSlow)
  
  const stats = {
    totalErrors: errors.length,
    totalSlowRequests: slowRequests.length,
    errorRate: 0,
    averageResponseTime: 0,
    errors: errors,
    slowRequests: slowRequests,
    allAPIs: apiErrors,
    // 详细错误分析
    errorAnalysis: {
      byType: getErrorsByType(errors),
      bySeverity: getErrorsBySeverity(errors),
      byCategory: getErrorsByCategory(errors),
      byEndpoint: getErrorsByEndpoint(errors),
      byStatusCode: getErrorsByStatusCode(errors)
    },
    // 详细错误信息
    detailedErrors: errors.map(error => ({
      endpoint: error.endpoint,
      apiPath: error.apiPath,
      method: error.method,
      statusCode: error.statusCode,
      errorType: error.errorType,
      severity: error.severity,
      errorMessage: error.errorMessage,
      duration: error.duration,
      apiCategory: error.apiCategory,
      timestamp: error.timestamp,
      url: error.url
    })),
    // 性能分析
    slowestRequest: getSlowestRequest(apiErrors),
    detailedSlowRequests: slowRequests.map(req => ({
      endpoint: req.endpoint,
      apiPath: req.apiPath,
      method: req.method,
      duration: req.duration,
      apiCategory: req.apiCategory,
      timestamp: req.timestamp,
      url: req.url
    }))
  }
  
  // 计算错误率
  if (apiErrors.length > 0) {
    stats.errorRate = Math.round((stats.totalErrors / apiErrors.length) * 100)
    stats.averageResponseTime = Math.round(apiErrors.reduce((sum, api) => sum + api.duration, 0) / apiErrors.length)
  }
  
  return cy.wrap(stats)
})

// 按错误类型分组
function getErrorsByType(errors) {
  return errors.reduce((acc, error) => {
    acc[error.errorType] = (acc[error.errorType] || 0) + 1
    return acc
  }, {})
}

// 按严重性分组
function getErrorsBySeverity(errors) {
  return errors.reduce((acc, error) => {
    acc[error.severity] = (acc[error.severity] || 0) + 1
    return acc
  }, {})
}

// 按API分类分组
function getErrorsByCategory(errors) {
  return errors.reduce((acc, error) => {
    acc[error.apiCategory] = (acc[error.apiCategory] || 0) + 1
    return acc
  }, {})
}

// 按端点分组
function getErrorsByEndpoint(errors) {
  return errors.reduce((acc, error) => {
    acc[error.endpoint] = (acc[error.endpoint] || 0) + 1
    return acc
  }, {})
}

// 按状态码分组
function getErrorsByStatusCode(errors) {
  return errors.reduce((acc, error) => {
    acc[error.statusCode] = (acc[error.statusCode] || 0) + 1
    return acc
  }, {})
}

// 获取最慢的请求
function getSlowestRequest(apis) {
  if (apis.length === 0) return null
  return apis.reduce((slowest, current) => 
    current.duration > slowest.duration ? current : slowest
  )
}

// 检查API健康状态
Cypress.Commands.add('checkAPIHealth', (options = {}) => {
  const {
    maxErrors = 5,
    maxSlowRequests = 3,
    maxErrorRate = 10
  } = options
  
  return cy.getAPIErrors().then((stats) => {
    // 检查错误数量
    if (stats.totalErrors > maxErrors) {
      throw new Error(`API错误数量超过限制: ${stats.totalErrors} > ${maxErrors}`)
    }
    
    // 检查慢请求数量
    if (stats.totalSlowRequests > maxSlowRequests) {
      throw new Error(`慢请求数量超过限制: ${stats.totalSlowRequests} > ${maxSlowRequests}`)
    }
    
    // 检查错误率
    if (stats.errorRate > maxErrorRate) {
      throw new Error(`API错误率过高: ${stats.errorRate}% > ${maxErrorRate}%`)
    }
    
    return cy.wrap(stats)
  })
})

// 等待API请求完成
Cypress.Commands.add('waitForAPIs', (timeout = 5000) => {
  cy.wait(timeout)
  return cy.wrap(null)
})

// 生成API异常报告
Cypress.Commands.add('generateAPIReport', () => {
  return cy.getAPIErrors().then((stats) => {
    const report = {
      timestamp: new Date().toISOString(),
      summary: {
        totalAPIs: stats.allAPIs.length,
        totalErrors: stats.totalErrors,
        totalSlowRequests: stats.totalSlowRequests,
        errorRate: stats.errorRate + '%',
        averageResponseTime: stats.averageResponseTime + 'ms'
      },
      errorAnalysis: stats.errorAnalysis,
      detailedErrors: stats.detailedErrors,
      slowRequests: stats.detailedSlowRequests,
      slowestRequest: stats.slowestRequest,
      allAPIs: stats.allAPIs
    }
    
    // 输出到控制台
    console.log('API异常报告:', report)
    
    return cy.wrap(report)
  })
})

// 将API错误信息整合到测试报告中
Cypress.Commands.add('integrateAPIErrorsToTestReport', () => {
  return cy.getAPIErrors().then((stats) => {
    if (stats.totalErrors > 0 || stats.totalSlowRequests > 0) {
      // 构建详细的错误报告内容
      let reportContent = `\n=== API接口异常报告 ===\n`
      reportContent += `测试执行时间: ${new Date().toLocaleString()}\n`
      reportContent += `总API请求数: ${stats.allAPIs.length}\n`
      reportContent += `错误请求数: ${stats.totalErrors}\n`
      reportContent += `慢请求数: ${stats.totalSlowRequests}\n`
      reportContent += `错误率: ${stats.errorRate}%\n`
      reportContent += `平均响应时间: ${stats.averageResponseTime}ms\n\n`
      
      // 添加详细错误信息
      if (stats.totalErrors > 0) {
        reportContent += `=== 接口错误详情 ===\n`
        stats.detailedErrors.forEach((error, index) => {
          reportContent += `错误 ${index + 1}:\n`
          reportContent += `  接口: ${error.method} ${error.apiPath}\n`
          reportContent += `  状态码: ${error.statusCode}\n`
          reportContent += `  错误信息: ${error.errorMessage}\n`
          reportContent += `  接口分类: ${error.apiCategory}\n`
          reportContent += `  严重性: ${error.severity}\n`
          reportContent += `  响应时间: ${error.duration}ms\n`
          reportContent += `  发生时间: ${new Date(error.timestamp).toLocaleString()}\n\n`
        })
        
        // 添加错误统计分析
        reportContent += `=== 错误统计分析 ===\n`
        reportContent += `按接口分类:\n`
        Object.entries(stats.errorAnalysis.byCategory).forEach(([category, count]) => {
          reportContent += `  ${category}: ${count}个\n`
        })
        
        reportContent += `按严重性:\n`
        Object.entries(stats.errorAnalysis.bySeverity).forEach(([severity, count]) => {
          reportContent += `  ${severity}: ${count}个\n`
        })
        
        reportContent += `按状态码:\n`
        Object.entries(stats.errorAnalysis.byStatusCode).forEach(([code, count]) => {
          reportContent += `  ${code}: ${count}个\n`
        })
        reportContent += `\n`
      }
      
      // 添加慢请求信息
      if (stats.totalSlowRequests > 0) {
        reportContent += `=== 慢请求详情 ===\n`
        stats.detailedSlowRequests.forEach((req, index) => {
          reportContent += `慢请求 ${index + 1}:\n`
          reportContent += `  接口: ${req.method} ${req.apiPath}\n`
          reportContent += `  响应时间: ${req.duration}ms\n`
          reportContent += `  接口分类: ${req.apiCategory}\n`
          reportContent += `  发生时间: ${new Date(req.timestamp).toLocaleString()}\n\n`
        })
      }
      
      // 将完整报告直接作为断言失败信息显示在测试报告中
      cy.then(() => {
        // 使用断言失败将错误信息显示在测试报告中
        const assertion = expect(stats.totalErrors, reportContent)
        assertion.to.equal(0)
      }).then(() => {
        // 如果没有抛出错误，说明没有API错误
      }, (error) => {
        // 捕获断言失败，记录但不阻止测试继续
        cy.log('⚠️ API接口异常已记录到测试报告')
        // 重新抛出错误以确保在报告中显示
        throw error
      }).then(() => {}, () => {
        // 最终捕获，确保测试不会因为API错误而失败
        cy.log('API异常检测完成')
      })
    } else {
      // 没有错误时记录成功状态
      cy.log(`✅ API接口检测通过`, `共${stats.allAPIs.length}个请求，平均响应时间${stats.averageResponseTime}ms`)
    }
    
    return cy.wrap(stats)
  })
})

// 输出详细的API错误分析到测试报告
Cypress.Commands.add('logDetailedAPIErrors', (testName) => {
  return cy.getAPIErrors().then((stats) => {
    cy.log(`${testName} - API异常统计`, {
      总API请求数: stats.allAPIs.length,
      错误数量: stats.totalErrors,
      慢请求数量: stats.totalSlowRequests,
      错误率: stats.errorRate + '%',
      平均响应时间: stats.averageResponseTime + 'ms'
    })
    
    // 输出错误分析
    if (stats.totalErrors > 0) {
      cy.log('错误类型分析', stats.errorAnalysis.byType)
      cy.log('错误严重性分析', stats.errorAnalysis.bySeverity)
      cy.log('错误分类分析', stats.errorAnalysis.byCategory)
      cy.log('错误端点分析', stats.errorAnalysis.byEndpoint)
      cy.log('错误状态码分析', stats.errorAnalysis.byStatusCode)
      
      // 输出具体错误详情
      stats.detailedErrors.forEach((error, index) => {
        cy.log(`错误 ${index + 1}`, {
          接口: error.endpoint,
          路径: error.apiPath,
          方法: error.method,
          状态码: error.statusCode,
          错误类型: error.errorType,
          严重性: error.severity,
          错误消息: error.errorMessage,
          响应时间: error.duration + 'ms',
          API分类: error.apiCategory,
          时间: error.timestamp
        })
      })
    }
    
    // 输出性能分析
    if (stats.slowestRequest) {
      cy.log('最慢请求', {
        接口: stats.slowestRequest.endpoint,
        路径: stats.slowestRequest.apiPath,
        方法: stats.slowestRequest.method,
        响应时间: stats.slowestRequest.duration + 'ms',
        API分类: stats.slowestRequest.apiCategory,
        时间: stats.slowestRequest.timestamp
      })
    }
    
    // 输出慢请求详情
    if (stats.detailedSlowRequests.length > 0) {
      stats.detailedSlowRequests.forEach((req, index) => {
        cy.log(`慢请求 ${index + 1}`, {
          接口: req.endpoint,
          路径: req.apiPath,
          方法: req.method,
          响应时间: req.duration + 'ms',
          API分类: req.apiCategory,
          时间: req.timestamp
        })
      })
    }
    
    return cy.wrap(stats)
  })
})