// ***********************************************
// 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
    cy.setCookie('customerName', json.customerName)
    cy.setCookie('dataBranchFactoryId', String(json.dataBranchFactoryId))
    cy.setCookie('customerId', String(json.customerId))
    cy.setCookie('userId', String(json.id))
    cy.setCookie('userName', json.name)
    cy.setCookie('TOKEN', 'cbb7481f995d46788f42d9aa0dc7847a')
    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('[data-testid="collector-list-container"]').should('be.visible')
  cy.get('[data-testid="collector-common-table"]').should('be.visible')
})