package com.cslg.ppa.service.GetWebArticle;

import com.cslg.ppa.service.ArticleInfoService;
import com.cslg.ppa.service.commom.XmlParseService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
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.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Slf4j
@Service
@RequiredArgsConstructor
public class GetLocalInformationService {
    private final GetCNIPAArticleService getCNIPAArticleService;

    @Scheduled(cron = "0 0 2 * * ?")
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Throwable.class)
    public void getLocalInformation(){
        System.out.println(new Date() + "Local-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", "485");
        // 政务 - 政策文件 - 通知   485
//        urlMap.put("https://www.cnipa.gov.cn/col/col75/index.html", "485");
        // 新闻 - 地方动态 - 动态信息
        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();
                    getCNIPAArticleService.readJson(key, responseBody, 2);
                }
            } catch (Exception e) {
                System.out.println("Get Web Article Error:" + e);
            }
        }
        System.out.println(new Date() + "Local-End");
    }
}
