/**
 * 诊断脚本 - 检查每个页面上的按钮和交互元素
 */
import { test, expect, type Page } from '@playwright/test'

const MOCK_TOKEN = 'mock-test-token'
test.beforeEach(async ({ page }) => {
  await page.addInitScript((token) => {
    localStorage.setItem('token', token)
  }, MOCK_TOKEN)
})

async function resetMock(page: Page, endpoint: string) {
  await page.evaluate(async (url) => {
    await fetch(url, { method: 'POST' })
  }, endpoint)
}

async function diagnosePage(page: Page, path: string, resetEndpoint: string, pageName: string) {
  await page.goto(path, { waitUntil: 'networkidle' })
  await resetMock(page, resetEndpoint)
  await page.reload({ waitUntil: 'networkidle' })
  await page.waitForSelector('.el-table', { timeout: 15000 })

  // 1. 未勾选时，统计所有按钮
  const allButtonsBefore = await page.locator('.mb-16 button, .mb-16 .el-button').allTextContents()
  console.log(`\n=== ${pageName} - 未勾选时的按钮 ===`)
  console.log(JSON.stringify(allButtonsBefore))

  // 2. 勾选第1行
  const checkboxes = page.locator('.el-table__body .el-checkbox')
  const checkboxCount = await checkboxes.count()
  console.log(`checkbox数量: ${checkboxCount}`)
  if (checkboxCount > 0) {
    await checkboxes.first().click()
    await page.waitForTimeout(500)
  }

  // 3. 勾选后，统计所有按钮
  const allButtonsAfter = await page.locator('.mb-16 button, .mb-16 .el-button').allTextContents()
  console.log(`\n=== ${pageName} - 勾选后的按钮 ===`)
  console.log(JSON.stringify(allButtonsAfter))

  // 4. 查找状态列有没有 el-switch
  const switches = await page.locator('.el-switch').count()
  console.log(`状态列的el-switch数量: ${switches}`)

  // 5. 查找状态列的内容
  const statusTags = await page.locator('.el-table .el-tag').allTextContents()
  console.log(`状态标签: ${JSON.stringify(statusTags)}`)

  // 6. 查找表格所有列标题
  const headers = await page.locator('.el-table__header th').allTextContents()
  console.log(`列标题: ${JSON.stringify(headers)}`)
}

test('诊断：设备管理页面', async ({ page }) => {
  await diagnosePage(page, '/mock/machine', '/mock-api/test/reset-machines', '设备管理')
})

test('诊断：员工管理页面', async ({ page }) => {
  await diagnosePage(page, '/mock/worker', '/mock-api/test/reset-workers', '员工管理')
})

test('诊断：采集地址页面', async ({ page }) => {
  await diagnosePage(page, '/mock/collect-address', '/mock-api/test/reset-addresses', '采集地址')
})
