// ***********************************************
// 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', '')
})