package com.ruoyi.bid.util;

import com.microsoft.playwright.*;

import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 招投标系统 - 低仿真核心链路模型
 * 模拟功能：抓取 -> 清洗 -> 智能筛选 -> 模拟报警
 */
public class BidSystemMVP {
    // 配置常量
    // 基础 URL 模板 (注意 %s 占位符)
    private static final String BASE_URL = "http://www.ccgp.gov.cn/cggg/zygg/index%s.htm";

    // 正则表达式：用于从 URL 中提取日期 (匹配 t20251208 这种格式)
    private static final Pattern DATE_PATTERN = Pattern.compile("t(\\d{8})_");
    //关键词
    private static final List<String> KEYWORDS = Arrays.asList("公告", "中标", "采购");
    private static final int MAX_PAGES = 50;
    private static final long DELAY_BETWEEN_PAGES = 2000; // 毫秒

    public static void main(String[] args) {
        BidSystemMVP scraper = new BidSystemMVP();

        // 获取目标日期（默认前一天，也可以指定）
        String targetDateStr;
        if (args.length > 0) {
            targetDateStr = args[0]; // 从命令行参数获取日期
        } else {
            //LocalDate targetDate = LocalDate.now().minusDays(1);
            LocalDate targetDate = LocalDate.now();
            targetDateStr = targetDate.format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        }

        System.out.println("========== 开始抓取 " + targetDateStr + " 的数据 ==========");

        try {
            List<Map<String, String>> results = scraper.scrapeDataForDate(targetDateStr);
            scraper.saveResultsToFile(results, targetDateStr);
            System.out.println("抓取完成，共收集 " + results.size() + " 条数据");
        } catch (Exception e) {
            System.err.println("数据抓取失败: " + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 抓取指定日期的数据
     */
    public List<Map<String, String>> scrapeDataForDate(String targetDateStr) {
        List<Map<String, String>> allResults = new ArrayList<>();

        try (Playwright playwright = Playwright.create()) {
            // 启动浏览器
            /*Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions()
                    .setChannel("chrome") // 如果报错改成 "msedge"
                    .setHeadless(false)   // 指定浏览器通道
                    .setSlowMo(500));    // 慢动作模式，每步操作延迟 500 毫秒（调试用）*/
            Browser browser = playwright.chromium().launch(
                    new BrowserType.LaunchOptions()
                            .setHeadless(true)  //设置为无头模式（不显示浏览器窗口）
            );


            int pageNum = 0;
            boolean hasTargetDate = true;

            while (pageNum < MAX_PAGES && hasTargetDate) {
                List<Map<String, String>> pageResults = scrapePage(browser, targetDateStr, pageNum, allResults.size());
                allResults.addAll(pageResults);

                // 判断是否继续翻页
                if (pageResults.isEmpty() && pageNum > 0) {
                    System.out.println("本页无目标日期数据，停止抓取");
                    hasTargetDate = false;
                } else {
                    System.out.println("第 " + (pageNum + 1) + " 页分析完毕，准备翻下一页...");
                    pageNum++;
                }

                // 防止请求过快，防止反爬
                Thread.sleep(DELAY_BETWEEN_PAGES);
            }

            browser.close();

        } catch (Exception e) {
            System.err.println("爬取过程中出错: " + e.getMessage());
            e.printStackTrace();
        }

        return allResults;
    }

    /**
     * 爬取单页数据
     */
    private List<Map<String, String>> scrapePage(Browser browser, String targetDateStr, int pageNum, int currentCount) {
        List<Map<String, String>> results = new ArrayList<>();
        Page page = browser.newPage();

        try {
            // 构造URL
            String urlSuffix = (pageNum == 0) ? "" : "_" + pageNum;
            String currentUrl = String.format(BASE_URL, urlSuffix);

            System.out.println("[第 " + (pageNum + 1) + " 页] 正在访问: " + currentUrl);

            page.navigate(currentUrl);
            page.waitForLoadState();
            page.waitForTimeout(2000);

            // 提取链接
            Locator links = page.locator("a");
            int count = links.count();

            for (int i = 0; i < count; i++) {
                try {
                    Locator item = links.nth(i);
                    if (!item.isVisible()) continue;

                    String href = item.getAttribute("href");
                    String title = item.innerText().trim();

                    if (href == null || title.length() < 5) continue;

                    Matcher matcher = DATE_PATTERN.matcher(href);
                    if (matcher.find()) {
                        String urlDate = matcher.group(1);
                        if (urlDate.equals(targetDateStr)) {
                            if (shouldSave(title)) {
                                Map<String, String> result = new HashMap<>();
                                result.put("title", title);
                                result.put("date", urlDate);
                                result.put("link", fixLink(href));
                                results.add(result);
                            }
                        }
                    }
                } catch (Exception e) {
                    // 忽略单个元素处理异常
                }
            }

        } catch (Exception e) {
            System.err.println("页面访问失败: " + e.getMessage());
        } finally {
            page.close();
        }

        return results;
    }

    /**
     * 判断标题是否应该保存
     */
    private boolean shouldSave(String title) {
        return KEYWORDS.stream().anyMatch(title::contains);
    }

    /**
     * 修复相对链接
     */
    private String fixLink(String link) {
        if (!link.startsWith("http")) {
            return "http://www.ccgp.gov.cn/cggg/zygg/" + link.replace("./", "");
        }
        return link;
    }

    /**
     * 保存结果到文件
     */
    public void saveResultsToFile(List<Map<String, String>> results, String dateStr) {
        String filename = "gov_procurement_" + dateStr + ".txt";

        try (PrintWriter writer = new PrintWriter(new FileWriter(filename, true))) {
            writer.println("政府采购数据 - " + dateStr);
           // writer.println("=".repeat(50));
            writer.println(new String(new char[50]).replace("\0", "="));

            for (Map<String, String> item : results) {
                writer.println("[★收录] " + item.get("title"));
                writer.println("       日期: " + item.get("date") + " | 链接: " + item.get("link"));
                writer.println();
            }

            System.out.println("数据已保存至 " + filename);

        } catch (IOException e) {
            System.err.println("保存文件失败: " + e.getMessage());
        }
    }
}