/* eslint-disable */
// 自动截图脚本：登录后逐页访问、等待加载、截图保存到 prd/汇丰银行/screenshots/
// 用法：node pc/scripts/capture-screenshots.js
// 前置：pc/ 下 npm run serve 已在 http://localhost:8080 运行

const { chromium } = require('playwright')
const path = require('path')
const fs = require('fs')

const BASE = 'http://localhost:8080'
const OUT_DIR = path.resolve(__dirname, '../../prd/汇丰银行/screenshots')

// 页面清单：{ name: 输出文件名（不带扩展名）, path: 路由, step?: 多步骤页的某一步, wait?: 额外等待 ms, action?: 截图前执行的函数 }
const PAGES = [
  // §2 借记卡权益
  { name: '2-1-equity-products-list', path: '/customization/hsbc/equity-products' },
  { name: '2-2-equity-add-step1', path: '/customization/hsbc/equity-products/add' },
  { name: '2-2-equity-add-step2', path: '/customization/hsbc/equity-products/add', step: 2 },
  { name: '2-2-equity-add-step3', path: '/customization/hsbc/equity-products/add', step: 3 },
  { name: '2-3-equity-edit', path: '/customization/hsbc/equity-products/edit/Q100006' },
  { name: '2-4-equity-view', path: '/customization/hsbc/equity-products/view/Q100001' },
  // §3 信用卡权益
  { name: '3-credit-card-equity-list', path: '/customization/hsbc/credit-card-equity' },
  // §6 权益审核
  { name: '6-audit-list', path: '/customization/hsbc/audit' },
  { name: '6-audit-detail', path: '/customization/hsbc/audit/AR202605150001' },
  // §三 人群管理
  { name: 'crowd-task-list', path: '/customization/hsbc/crowd-tasks' },
  { name: 'crowd-task-add-step1', path: '/customization/hsbc/crowd-tasks/add' },
  { name: 'crowd-task-add-step2', path: '/customization/hsbc/crowd-tasks/add', step: 2 },
  { name: 'crowd-name-list-add-step1', path: '/customization/hsbc/crowd-name-lists/add' },
  { name: 'crowd-name-list-add-step2', path: '/customization/hsbc/crowd-name-lists/add', step: 2 },
  { name: 'rule-group-list', path: '/customization/hsbc/rule-groups' },
  { name: 'rule-group-add-step1', path: '/customization/hsbc/rule-groups/add' },
  { name: 'rule-group-add-step2', path: '/customization/hsbc/rule-groups/add', step: 2 },
  // §四 发放计划
  { name: '4-grant-campaign-list', path: '/customization/hsbc/equity-grant-campaign' },
  { name: '4-grant-campaign-add', path: '/customization/hsbc/equity-grant-campaign/add' },
  // §五 页面管理
  { name: '5-page-home', path: '/customization/hsbc/pages/home' },
  { name: '5-page-zone', path: '/customization/hsbc/pages/zone' },
  { name: '5-page-assembly', path: '/customization/hsbc/pages/assembly' },
  // Channel/Campaign
  { name: 'channel-management', path: '/customization/hsbc/channel' },
  { name: 'campaign-management', path: '/customization/hsbc/campaign' },
  // §六 短信管理
  { name: '6-sms-template-list', path: '/customization/hsbc/sms-templates' },
  { name: '6-sms-send-record', path: '/customization/hsbc/sms-send-records' },
  // §七 报表中心
  { name: '7-points-detail', path: '/customization/hsbc/points-detail' },
  { name: '7-customer-equity-grant', path: '/customization/hsbc/equity-grant' },
  { name: '7-cash-discount-grant', path: '/customization/hsbc/cash-discount-grant' }
]

async function waitDevServer() {
  const fetchUrl = BASE + '/'
  for (let i = 0; i < 60; i++) {
    try {
      const res = await fetch(fetchUrl)
      if (res.ok || res.status === 200) return true
    } catch (_) { /* not ready */ }
    await new Promise(r => setTimeout(r, 1000))
  }
  throw new Error('dev server 未在 60s 内就绪，请确认 npm run serve 已启动')
}

async function gotoStep(page, stepIdx) {
  // 三步骤向导（添加/编辑/规则组/客群任务）通过点击「下一步」翻到目标 step
  // stepIdx 是 1-based 业务步骤；首屏已是 step 1，则点击 stepIdx-1 次「下一步」
  for (let i = 1; i < stepIdx; i++) {
    const nextBtn = page.locator('button:has-text("下一步")').first()
    if (await nextBtn.count() === 0) break
    await nextBtn.click().catch(() => {})
    await page.waitForTimeout(400)
  }
}

;(async () => {
  console.log('[1/4] 等待 dev server 就绪...')
  await waitDevServer()
  console.log('     dev server OK')

  console.log('[2/4] 启动 chromium...')
  const browser = await chromium.launch({ headless: true })
  // 视口宽高按 1/0.8 放大，让一屏容纳更多内容（等价于"缩放 80%"的视觉效果）
  const context = await browser.newContext({ viewport: { width: 1800, height: 1125 }, deviceScaleFactor: 2 })
  const page = await context.newPage()

  console.log('[3/4] 注入 token 跳过登录...')
  await page.goto(BASE + '/#/login', { waitUntil: 'domcontentloaded' })
  await page.evaluate(() => {
    localStorage.setItem('token', 'mock-token-' + Date.now())
    localStorage.setItem('username', 'admin')
  })

  console.log(`[4/4] 开始截图（共 ${PAGES.length} 张）...`)
  const results = []
  for (const item of PAGES) {
    const url = BASE + '/#' + item.path
    try {
      await page.goto(url, { waitUntil: 'networkidle', timeout: 15000 })
    } catch (_) {
      // networkidle 在 dev server 热更新场景下可能 timeout，降级用 domcontentloaded
      await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 15000 })
    }
    await page.waitForTimeout(800)
    if (item.step && item.step > 1) {
      await gotoStep(page, item.step)
      await page.waitForTimeout(400)
    }
    const file = path.join(OUT_DIR, item.name + '.png')
    await page.screenshot({ path: file, fullPage: true })
    const size = (fs.statSync(file).size / 1024).toFixed(0)
    console.log(`     ✓ ${item.name}.png  (${size}KB)`)
    results.push({ name: item.name, file })
  }

  await browser.close()
  console.log(`\n完成。共 ${results.length} 张，输出目录：${OUT_DIR}`)
})()
