package com.spider.quartz.util;

import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * XML爬虫工具类 - 提供各种数据转换和通用方法
 */
public class SpiderXmlUtil {

    private static final SimpleDateFormat DEFAULT_DATE_FORMAT = new SimpleDateFormat("dd/MM/yyyy");

    /**
     * 预处理XML文件，修复不合规的实体引用
     */
    public static File preprocessXmlFile(File xmlFile) {
        try {
            System.out.println("开始预处理XML文件...");

            // 读取原始文件内容
            String content = new String(Files.readAllBytes(xmlFile.toPath()), StandardCharsets.UTF_8);

            // 修复不合规的实体引用
            Pattern entityPattern = Pattern.compile("&([a-zA-Z_][a-zA-Z0-9_.-]*)(?![;])");
            Matcher matcher = entityPattern.matcher(content);
            StringBuffer sb = new StringBuffer();

            while (matcher.find()) {
                String entityName = matcher.group(1);
                // 修复已知的问题实体，其他的替换为空白
                if ("banner_delivery_id".equals(entityName)) {
                    matcher.appendReplacement(sb, "");
                    System.out.println("修复不合规实体引用: &" + entityName);
                } else {
                    // 其他未知实体也移除
                    matcher.appendReplacement(sb, "");
                }
            }
            matcher.appendTail(sb);

            String cleanedContent = sb.toString();

            // 如果内容有变化，保存到新文件
            if (!cleanedContent.equals(content)) {
                File cleanedFile = new File(xmlFile.getParent(), "cleaned_" + xmlFile.getName());
                Files.write(cleanedFile.toPath(), cleanedContent.getBytes(StandardCharsets.UTF_8));
                System.out.println("已创建修复后的XML文件: " + cleanedFile.getAbsolutePath());
                return cleanedFile;
            } else {
                System.out.println("XML文件无需修复");
                return xmlFile;
            }

        } catch (Exception e) {
            System.err.println("预处理XML文件失败: " + e.getMessage());
            // 如果预处理失败，返回原始文件
            return xmlFile;
        }
    }

    /**
     * 从文本中提取日期
     */
    public static Date extractDateFromText(String text, String regex, String dateFormat) {
        if (text == null || text.isEmpty()) {
            return null;
        }

        try {
            Pattern pattern = Pattern.compile(regex);
            Matcher matcher = pattern.matcher(text);

            if (matcher.find()) {
                String dateStr = matcher.group(1);
                System.out.println("提取到日期: " + dateStr);
                SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
                return sdf.parse(dateStr);
            }

            // 检查是否为未知日期
            if (text.contains("Date of entry into force: Unknown")) {
                System.out.println("发现未知生效日期的记录");
                return null;
            }

            // 尝试其他可能的日期格式
            System.out.println("未找到标准格式的日期，文本内容: " + text.substring(0, Math.min(100, text.length())));

        } catch (Exception e) {
            System.err.println("提取日期失败: " + e.getMessage());
        }
        return null;
    }

    /**
     * 获取XML元素的文本内容
     */
    public static String getElementText(Element element, String tagName) {
        try {
            NodeList nodeList = element.getElementsByTagName(tagName);
            if (nodeList.getLength() > 0) {
                String text = nodeList.item(0).getTextContent().trim();
                return text.isEmpty() ? null : text;
            }
        } catch (Exception e) {
            System.err.println("获取元素 " + tagName + " 文本内容失败: " + e.getMessage());
        }
        return null;
    }

    /**
     * 清理字段值
     */
    public static String cleanFieldValue(String fieldValue) {
        if (fieldValue == null ||
                fieldValue.trim().isEmpty() ||
                "未提供".equals(fieldValue.trim()) ||
                "Not provided".equals(fieldValue.trim()) ||
                "N/A".equals(fieldValue.trim())) {
            return null;
        }
        return fieldValue.trim();
    }

    /**
     * 拆分风险描述和不合格原因
     */
    public static Map<String, String> splitRiskAndCause(String dangerText) {
        Map<String, String> result = new HashMap<>();

        if (dangerText == null || dangerText.isEmpty()) {
            result.put("riskDescription", null);
            result.put("unqualifiedCause", null);
            return result;
        }

        // 简单的拆分逻辑：根据句子结构拆分
        String[] sentences = dangerText.split("\\. ");

        if (sentences.length > 1) {
            // 前部分作为风险描述
            StringBuilder riskDesc = new StringBuilder();
            for (int i = 0; i < sentences.length - 1; i++) {
                if (riskDesc.length() > 0) riskDesc.append(". ");
                riskDesc.append(sentences[i]);
            }
            result.put("riskDescription", riskDesc.toString() + ".");

            // 最后部分作为不合格原因
            result.put("unqualifiedCause", sentences[sentences.length - 1]);
        } else {
            // 如果只有一句话，都作为风险描述
            result.put("riskDescription", dangerText);
            result.put("unqualifiedCause", "产品不符合相关法规要求");
        }

        return result;
    }

    /**
     * 获取当前年份的开始日期
     */
    public static Date getCurrentYearStartDate() {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.MONTH, Calendar.JANUARY);
        cal.set(Calendar.DAY_OF_MONTH, 1);
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        return cal.getTime();
    }

    /**
     * 格式化日期为字符串
     */
    public static String formatDate(Date date, String pattern) {
        if (date == null) return null;
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(pattern);
            return sdf.format(date);
        } catch (Exception e) {
            System.err.println("日期格式化失败: " + e.getMessage());
            return null;
        }
    }

    /**
     * 解析日期字符串
     */
    public static Date parseDate(String dateStr, String pattern) {
        if (dateStr == null || dateStr.trim().isEmpty()) return null;
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(pattern);
            return sdf.parse(dateStr.trim());
        } catch (Exception e) {
            System.err.println("日期解析失败: " + e.getMessage());
            return null;
        }
    }

    /**
     * 截断字符串到指定长度
     */
    public static String truncateString(String str, int maxLength) {
        if (str == null) return null;
        if (str.length() <= maxLength) return str;
        return str.substring(0, maxLength - 3) + "...";
    }

    /**
     * 检查字符串是否为空或空白
     */
    public static boolean isBlank(String str) {
        return str == null || str.trim().isEmpty();
    }

    /**
     * 如果字符串为空则返回默认值
     */
    public static String defaultIfBlank(String str, String defaultValue) {
        return isBlank(str) ? defaultValue : str;
    }
}