package com.cslg.ppa.service.GetWebArticle;


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.Date;
import java.util.HashMap;
import java.util.Map;

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

    @Scheduled(cron = "0 30 1 * * ?")
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Throwable.class)
    public void getPCTArticle(){
        System.out.println(new Date() + "PCT-Begin");
        Map<String , String> urlMap = new HashMap<>();
        // 专题-专利合作条约（PCT)-重要通知
        urlMap.put("https://www.cnipa.gov.cn/col/col332/index.html", "669");

        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, 4);
                }
            } catch (Exception e) {
                System.out.println("Get Web Article Error:" + e);
            }
        }
        System.out.println(new Date() + "PCT-End");
    }
}
