/**
 * 截图脚本 - 使用 Playwright
 */

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

dotenv.config({path: ['.env.local', '.env'], quiet: true});

const BASE_DIR = process.env.BASE_DIR;
const PIC_DIR = path.join(BASE_DIR, 'pic');

const TARGET_URL = 'http://bjjs.zjw.beijing.gov.cn/eportal/ui?pageId=307749';

// 获取当前日期
function getToday() {
    return new Date().toISOString().split('T')[0];
}

async function screenshot(url, outputPath) {
    console.log(`正在截图: ${url}`);
    console.log(`输出路径: ${outputPath}`);

    const browser = await chromium.launch({
        headless: true,
        args: ['--no-sandbox', '--disable-setuid-sandbox']
    });

    try {
        const context = await browser.newContext({
            viewport: { width: 1920, height: 1080 }
        });

        const page = await context.newPage();

        // 设置超时
        page.setDefaultTimeout(60000);
        page.setDefaultNavigationTimeout(60000);

        // 访问页面
        await page.goto(url, {
            waitUntil: 'networkidle',
            timeout: 60000
        });

        // 等待页面加载完成
        await page.waitForLoadState('domcontentloaded');

        // 额外等待3秒确保动态内容加载
        await page.waitForTimeout(3000);

        // 确保输出目录存在
        const outputDir = path.dirname(outputPath);
        if (!fs.existsSync(outputDir)) {
            fs.mkdirSync(outputDir, { recursive: true });
        }

        // 截图
        await page.screenshot({
            path: outputPath,
            fullPage: true
        });

        console.log(`  ✓ 截图已保存: ${outputPath}`);

    } catch (error) {
        console.error(`  ✗ 截图失败: ${error.message}`);
        process.exit(1);
    } finally {
        await browser.close();
    }
}

// 主程序
screenshot(TARGET_URL, path.join(PIC_DIR, `${getToday()}.png`));
