package com.cslg.ppa.service.GetWebArticle;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cslg.ppa.common.utils.DateUtil;
import com.cslg.ppa.dto.GetArticleInfoDTO;
import com.cslg.ppa.entity.ArticleInfo;
import com.cslg.ppa.service.ArticleInfoService;
import com.cslg.ppa.service.commom.DifyService;
import com.cslg.ppa.service.commom.XmlParseService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.openqa.selenium.WebDriver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


@Slf4j
@Service
@RequiredArgsConstructor
public class GetCNIPAArticleService {
    private final ArticleInfoService articleInfoService;
    private final XmlParseService xmlParseService;
    @Autowired
    private DifyService difyService;

    /**
     * 国家知识产权局
     */
    @Scheduled(cron = "0 0 1 * * ?")
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Throwable.class)
    public void getCNIPA(){
        System.out.println(new Date() + "CNIPA-Begin");
        Map<String , String> urlMap = new HashMap<>();
        // 首页 - 专题 - 专利审查高速路（PPH）专栏 - 通知  669
//        urlMap.put("https://www.cnipa.gov.cn/col/col340/index.html", "669");
        // 政务 - 政策文件 - 公告   485
        urlMap.put("https://www.cnipa.gov.cn/col/col74/index.html", "17035");
        // 政务 - 政策文件 - 通知   485
        urlMap.put("https://www.cnipa.gov.cn/col/col75/index.html", "17035");
        // 新闻 - 地方动态 - 动态信息
//        urlMap.put("https://www.cnipa.gov.cn/col/col57/index.html", "485");

        for (Map.Entry<String, String> entry : urlMap.entrySet()) {
            String url = entry.getKey();
            CloseableHttpClient httpClient = HttpClients.createDefault();
            try {
                HttpGet request = new HttpGet(url);
                HttpResponse response = httpClient.execute(request);
                String responseBody = EntityUtils.toString(response.getEntity());
                httpClient.close();
                if (responseBody != null) {
                    String key = entry.getValue();
                    this.readJson(key, responseBody,1);
                }
            } catch (Exception e) {
                System.out.println("Get Web Article Error:" + e);
            }
        }
        System.out.println(new Date() + "CNIPA-End");
    }

    public void readJson(String key, String responseBody,Integer type) {
        try {
            List<GetArticleInfoDTO> articleInfoDTOS = new ArrayList<>();
            //使用JSoup解析HTML
            Document doc = Jsoup.parse(responseBody);
            Element div = doc.getElementById(key);
            Element scriptElement = div.select("script").first();
            String contentText = scriptElement.html();
            List<String> reStrs = xmlParseService.xmlParse(contentText, "record");
            for (String reStr : reStrs) {
                Document document = Jsoup.parse(reStr);
                Element linkElement = document.getElementsByTag("a").first();
                //获取时间
                String dateStr = document.getElementsByTag("span").text().trim();
                String yesterdayDateStr = DateUtil.getYesterdayDateStr();
                if (!StringUtils.equals(dateStr, yesterdayDateStr)) {
                    continue;
                }
                Date date = new Date();
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                try {
                    date = dateFormat.parse(dateStr);
                } catch (Exception e) {
                    continue;
                }

                String link = linkElement.attr("href");
                String title = linkElement.text();

                // 检查文章是否已存在
                long count = articleInfoService.count(new LambdaQueryWrapper<ArticleInfo>()
                        .eq(ArticleInfo::getTitle, title));
                if (count > 0) {
                    continue; // 文章已存在，跳过
                }

                String digest = null;
                try {
                    digest = this.getDigest(link);
                } catch (Exception e) {
                    digest = "";
                }
                if (StringUtils.isEmpty(digest)) {
                    continue;
                }
                String condensedAbstract = null;
                try {
                    condensedAbstract = difyService.getCondensedAbstract(digest);
                } catch (Exception ignored) {

                }
                if (StringUtils.isEmpty(condensedAbstract)) {
                    continue;
                }
                GetArticleInfoDTO articleInfoDTO = new GetArticleInfoDTO();
                articleInfoDTO.setCategoryId(type);
                articleInfoDTO.setSourceId(1);
                articleInfoDTO.setArticleUrl(link);
                articleInfoDTO.setTitle(title);
                articleInfoDTO.setPublicTime(date);
                articleInfoDTO.setDigest(condensedAbstract);
                articleInfoDTOS.add(articleInfoDTO);
            }
            articleInfoService.batchAddArticleInfo(articleInfoDTOS);
        } catch (Exception e) {
            System.out.println("Read Json Error" + e);
        }
    }

    //精简摘要
    public String getDigest(String url) throws IOException {
        String digest = "";
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet request = new HttpGet(url);
        HttpResponse response = httpClient.execute(request);
        String responseBody = EntityUtils.toString(response.getEntity());
        httpClient.close();
        if (responseBody != null) {
            digest = this.readJson(responseBody);
        }
        return digest;
    }

    public String readJson(String responseBody) {
        StringBuilder builder = new StringBuilder();
        try {
            //使用JSoup解析HTML
            Document doc = Jsoup.parse(responseBody);
//            String title = doc.title();
//            Elements paragraphs = doc.select("p");
//            for (Element paragraph : paragraphs) {
//                String text = paragraph.text();
//            }
            // 获取description元数据
            Element metaElement = doc.selectFirst("meta[name=description]");
            if (metaElement != null) {
                String content = metaElement.attr("content");
                builder = new StringBuilder(content);
            } else {
                builder = new StringBuilder();
            }
        } catch (Exception e) {
            builder = new StringBuilder();
        }
        return builder.toString();
    }

    //精简摘要
    public void getDigest1(String url) throws IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet request = new HttpGet(url);
        HttpResponse response = httpClient.execute(request);
        String responseBody = EntityUtils.toString(response.getEntity());
        httpClient.close();
        if (responseBody != null) {
            this.readJson1(responseBody,url);
        }
    }

    public void readJson1(String responseBody, String articleUrl) {
        StringBuilder builder = new StringBuilder();
        try {
            //使用JSoup解析HTML
            Document doc = Jsoup.parse(responseBody);
            String title = doc.title();
            // 通过 CSS 选择器定位元素
            Element dateSpan = doc.selectFirst("div.article-info.clearfix > span:containsOwn(发布时间：)");

            Date date = new Date();
            if (dateSpan != null) {
                String fullText = dateSpan.text();
                String publishDate = fullText.replace("发布时间：", "").trim();
                System.out.println("发布时间：" + publishDate);
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                try {
                    date = dateFormat.parse(publishDate);
                } catch (Exception e) {
                }// 输出：2025-08-21
            } else {
                System.out.println("未找到发布时间");
            }
            // 获取description元数据
            Element metaElement = doc.selectFirst("meta[name=description]");
            if (metaElement != null) {
                String content = metaElement.attr("content");
                builder = new StringBuilder(content);
            } else {
                builder = new StringBuilder();
            }
            System.out.println(builder.toString());
            String condensedAbstract = difyService.getCondensedAbstract(builder.toString());
            ArticleInfo articleInfo = new ArticleInfo();
            articleInfo.setTitle(title);
            articleInfo.setDigest(condensedAbstract);
            articleInfo.setCategoryId(1);
            articleInfo.setSourceId(1);
            articleInfo.setPublicTime(date);
            articleInfo.setArticleUrl(articleUrl);
            articleInfo.insert();
        } catch (Exception e) {
        }
    }
}

