package cn.cslg.pas.service.outApi;

import cn.cslg.pas.common.model.PersonnelVO;
import cn.cslg.pas.common.model.outApi.PatentStarDto;
import cn.cslg.pas.common.model.outApi.PatentStarListDto;
import cn.cslg.pas.common.model.vo.outApi.StarPatentVO;
import cn.cslg.pas.common.utils.*;
import cn.cslg.pas.common.utils.SecurityUtils.LoginUtils;
import cn.cslg.pas.domain.*;
import cn.cslg.pas.service.upLoadPatent.RetrieveRecordService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import io.swagger.v3.oas.models.security.SecurityScheme;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import org.joda.time.DateTime;
import org.joda.time.Days;
import org.joda.time.Months;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 调用外部接口的Service类 PCS:权限系统
 *
 * @Author chenyu
 * @Date 2023/4/25
 */
@RequiredArgsConstructor
@Slf4j
@Service

public class PatentStarApiService {
    private final RetrieveRecordService retrieveRecordService;
    private final CacheUtils cacheUtils;
    private final LoginUtils loginUtils;

    public static String formatValue(String value) {
        return value.replace("~", ">");
    }

    public static String formQuery(String query) {
        String regexSim = "\\'.*?\\'";
        Pattern patternSim = Pattern.compile(regexSim);
        Matcher matcherSim = patternSim.matcher(query);
        Map<String, String> map = new LinkedHashMap<>();
        Integer i = 1;
        while (matcherSim.find()) {
            String aa = matcherSim.group();
            map.put("$" + i, matcherSim.group());
            query = query.replaceFirst(matcherSim.group(), "\\$" + i);
            i++;
            System.out.println(query);
        }

        // 统一改成大写
        query = query.toUpperCase();
        query = "(" + query + ")";
        query = query
                .replace(" AND ", "*")
                .replace(" OR ", "+")
                .replace(" NOT ", "-");

        for (String key : map.keySet()) {
            query = query.replace(key, map.get(key));

        }
        //记录偏移量
        int t = 0;
        StringBuilder query2 = new StringBuilder(query);
        //匹配形如ab=(cd OR ef);
        String regexOrg = "([^=^\\*^\\+^\\(^\\)^\\-]+=\\([^=^\\)]+\\))+?";
        Pattern patternOrg = Pattern.compile(regexOrg);
        Matcher matcherOrg = patternOrg.matcher(query);
        while (matcherOrg.find()) {
            String a = matcherOrg.group();
            String[] bc = a.split("=");
            String b = bc[0];
            b.length();
            query2.delete(matcherOrg.start() + t, matcherOrg.start() + b.length() + 1 + t);
            t = t - b.length() - 1;
            String c = bc[1];
            String regexOrg1 = "([^\\+^\\*^\\-^\\(^\\)])+";
            Pattern patternOrg1 = Pattern.compile(regexOrg1);
            Matcher matcherOrg1 = patternOrg1.matcher(c);
            while (matcherOrg1.find()) {
                String r = matcherOrg1.group();
                System.out.println(r);
                query2.insert(matcherOrg.start() + b.length() + 1 + matcherOrg1.start() + t, b + "=");
                t = t + b.length() + 1;
            }
        }
        System.out.println(query2);
        return query2.toString();
    }

    public static String formatQuery(String query) {
        query = PatentStarApiService.formQuery(query);
        StringBuilder sb = new StringBuilder(query);
        String regex = "(?<=[\\(\\)\\+\\-=\\*])[^\\*^\\-^\\+^\\(^\\)]+?(?=[\\(\\+\\-=\\)\\*])";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(query);
        Map<Integer, Integer> map = new LinkedHashMap<>();
        while (matcher.find()) {
            String a = matcher.group();
            String regex2 = "[^\\(^\\)^\\+^-^=^*]";
            Pattern pattern2 = Pattern.compile(regex2);
            Matcher matcher2 = pattern2.matcher(a);
            Integer start = matcher.start();
            if (matcher2.find()) {
                start += matcher2.start();
            }
            map.put(start, matcher.end());
        }
        if (map.size() == 0) {
            return "";
        }
        List<Integer> list = new ArrayList<Integer>(map.keySet());
        for (int i = 0; i < list.size(); i += 2) {
            int start1 = list.get(i);
            int end1 = map.get(list.get(i));
            int len1 = end1 - start1;
            int start2 = list.get(i + 1);
            int end2 = map.get(list.get(i + 1));
            int len2 = end2 - start2;
            int diff = len2 - len1;
            if (diff > 0) {
                sb.replace(start1, end1, formatValue(query.substring(start2, end2)));
                sb.replace(start2 + diff, end2 + diff, query.substring(start1, end1));
            } else {
                sb.replace(start2, end2, query.substring(start1, end1));
                sb.replace(start1, end1, formatValue(query.substring(start2, end2)));
            }
        }
        String reStr = sb.toString();
        reStr = "FXX" + reStr.replace("=", "/");
        return reStr;
    }

    //装载专利信息
    public void loadStarPatentVOS(List<StarPatentVO> starPatentVOS, JSONObject Data) {
        String aa = Data.toString();
        starPatentVOS.forEach(item -> {

            //如果有公开号，则将公开号作为专利号
            if (item.getPublicNo() != null && !item.getPublicNo().equals("")) {
                item.setPatentNo(item.getPublicNo());

                //如果没有公开号，但是有公告号，则将公告号作为公开号和专利号
            } else if (item.getAnnounceNo() != null && !item.getAnnounceNo().equals("")) {
                item.setPublicNo(item.getAnnounceNo());
                item.setPatentNo(item.getAnnounceNo());
            } else {
                System.out.println("");

            }

            //陈宇 ↓ 如果没有公开日就将公告日作为公开日
            if (item.getPublicDate() == null || item.getPublicDate().equals("")) {
                item.setPublicDate(item.getPublicAccreditDate());
            }
            item.setApplicant(new ArrayList<>());
            item.setAgent(new ArrayList<>());
            item.setIpcList(Arrays.asList(item.getIpcListStr().split(";")));
            List<String> applicants = Arrays.asList(item.getApplicantStr().split(";"));
            //装载申请人
            applicants.forEach(
                    tem -> {
                        PatentApplicant patentApplicant = new PatentApplicant();
                        patentApplicant.setType(2);
                        patentApplicant.setDataType(2);
                        patentApplicant.setName(tem);
                        item.getApplicant().add(patentApplicant);
                    }
            );

            if (item.getCurrentApplicantStr() != null && !item.getCurrentApplicantStr().equals("")) {
                List<String> cApplicants = Arrays.asList(item.getCurrentApplicantStr().split(";"));
                cApplicants.forEach(
                        tem -> {
                            PatentApplicant patentApplicant = new PatentApplicant();
                            patentApplicant.setType(2);
                            patentApplicant.setDataType(1);
                            patentApplicant.setName(tem);
                            item.getApplicant().add(patentApplicant);
                        }
                );
            }

            //代理机构
            if (item.getAgencyStr() != null && !item.getAgencyStr().equals("")) {
                PatentAgency patentAgency = new PatentAgency();
                patentAgency.setName(item.getAgencyStr().split(" ")[0]);
                item.setAgency(patentAgency);
            }

            //发明人
            if (item.getInventorStr() != null && !item.getInventorStr().equals("")) {
                item.setInventor(new ArrayList<>());
                List<String> inventors = Arrays.asList(item.getInventorStr().split(";"));
                inventors.forEach(
                        tem -> {
                            PatentInventor patentInventor = new PatentInventor();
                            patentInventor.setName(tem);
                            item.getInventor().add(patentInventor);
                            ;
                        }
                );
            }

            //代理人
            if (item.getAgentStr() != null && !item.getAgentStr().equals("")) {
                List<String> agent = Arrays.asList(item.getAgentStr().split(";"));
                agent.forEach(
                        tem -> {
                            PatentAgent patentAgent = new PatentAgent();
                            patentAgent.setName(tem);
                            item.getAgent().add(patentAgent);
                        }
                );
            }
            //附图
            String apN = item.getApplicationNo().replace(".", "");
            item.setAbstractPath(this.getPictureApi(apN.substring(2)));
            if (item.getLG() != null) {
                switch (item.getLG()) {
                    case 1:
                        item.setSimpleStatus("有效");
                        break;
                    case 2:
                        item.setSimpleStatus("失效");
                        break;
                    case 3:
                        item.setSimpleStatus("审中");
                        break;
                }
            }
            //法律状态
        });
    }

    public Map<String, Object> patentStarSearchLocal(PatentStarListDto patentStarListDto) throws IOException {
        RetrieveRecord retrieveRecord = new RetrieveRecord();
        retrieveRecord.setConditions(patentStarListDto.getCurrentQuery());
        if (patentStarListDto.getRetrieveRecordId() != null) {
            //retrieveRecord = retrieveRecordService.getById(patentStarListDto.getRetrieveRecordId());
            //patentStarListDto.setCurrentQuery(retrieveRecord.getConditions());
            //patentStarListDto.setDBType(retrieveRecord.getDbType());
        }
        Map<String, Object> map = this.patentStarSearchApi(patentStarListDto);
        if (map == null) {
            ThrowException.throwXiaoShiException("检索失败,请检查检索式");
        }
        //记录检索历史
        retrieveRecord.setRetrieveTime(new Date());
        retrieveRecord.setTotalNum(Integer.parseInt(map.get("total").toString()));
        retrieveRecord.setDbType(patentStarListDto.getDBType());
        if (patentStarListDto.getRetrieveRecordId() == null) {
            //获取创建人信息
            PersonnelVO personnelVO = cacheUtils.getLoginUser(loginUtils.getId());
            retrieveRecord.setCreateTime(new Date());
            retrieveRecord.setCreateId(personnelVO.getId());
            retrieveRecord.setTenantId(personnelVO.getTenantId());
            retrieveRecord.insert();
        }
//        else {
//            retrieveRecord.updateById();
//        }
        map.put("retrieveRecordId", retrieveRecord.getId());
        return map;

    }


    public Map<String, Object> patentStarSearchApi(PatentStarListDto patentStarListDto) throws IOException {
        try {
if(patentStarListDto.getFormed()==null||patentStarListDto.getFormed()==false) {
    String formQuery = patentStarListDto.getCurrentQuery();
    patentStarListDto.setCurrentQuery(PatentStarApiService.formatQuery(formQuery));
}
        } catch (Exception e) {
            return null;
        }
        PatentStarDto patentStarDto = new PatentStarDto();
        BeanUtils.copyProperties(patentStarListDto, patentStarDto);
        String json = JSONObject.toJSONString(patentStarDto);
        String url = "http://s.patentstar.com.cn/SearchAPI/PatentSearch/ResultGet";
        Long currentTimeMillis = System.currentTimeMillis() / 1000;
        String Sign = "FNYJD7902206FFB741E163BE6536C3689D55" + currentTimeMillis.toString();
        String signMd5 = FormatUtil.MD5(Sign);
        // 创建一个OkHttpClient对象
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .build();
        // 创建一个RequestBody(参数1：数据类型 参数2传递的json串)
        FormBody.Builder builder = new FormBody.Builder();
        builder.add("AppID", "K8FFB741E163BE6536");
        builder.add("Stamp", currentTimeMillis.toString());
        builder.add("Sign", signMd5);
        builder.add("QueryJson", json);
        FormBody requestBody = builder.build();
        // 创建一个请求对象
        Request request = new Request.Builder().url(url).post(requestBody).build();
        // 发送请求获取响应
        try {
            Response response = okHttpClient.newCall(request).execute();
            // 判断请求是否成功
            if (response.isSuccessful()) {
                JSONObject jsonObject = JSONObject.parseObject(Objects.requireNonNull(response.body()).string());
                if (jsonObject.get("Ret").equals(500) || jsonObject.get("Data") == null) {
                    return null;
                }
                JSONObject Data = (JSONObject) jsonObject.get("Data");
                List<StarPatentVO> starPatentVOS = JSONArray.parseArray(Data.get("List").toString(), StarPatentVO.class);
                this.loadStarPatentVOS(starPatentVOS, Data);
                // 打印服务端返回结果
                //  return Objects.requireNonNull(response.body()).string();
                Map<String, Object> reMap = new HashMap<>();
                reMap.put("size", patentStarListDto.getRowCount());
                reMap.put("current", patentStarListDto.getPageNum());
                reMap.put("records", starPatentVOS);
                reMap.put("total", Data.get("HitCount"));
                return reMap;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        return null;
    }

    public List<PatentStarListDto> test(PatentStarListDto patentStarListDto) throws IOException {
        DateTime nowDate = new DateTime();
        DateTime date = DateUtils2.formStrToDateTime("2000-01-01");
        //超过1万的列表
        List<PatentStarListDto> patentStarListDtos = new ArrayList<>();
        //返回的列表
        List<PatentStarListDto> reDtos = new ArrayList<>();
        patentStarListDto.setStartTime(date);
        patentStarListDto.setEndTime(nowDate);
        String formQuery = patentStarListDto.getCurrentQuery();
        patentStarListDto.setOrginCondition(PatentStarApiService.formatQuery(formQuery));
        patentStarListDtos.add(patentStarListDto);
        while (patentStarListDtos.size() > 0) {
            PatentStarListDto dto = patentStarListDtos.get(0);
            patentStarListDtos.remove(dto);
            Map<String, Object> map1 = this.patentStarSearchApi(dto);
            Integer total1 = Integer.parseInt(map1.get("total").toString());
            dto.setTotal(total1);
            patentStarListDto.setFormed(true);
            if (total1 > 10000) {
                DateTime startTime1 = dto.getStartTime();
                DateTime endTime1 = dto.getEndTime();
                List<DateTime> dateTimes = DateUtils2.formStrToDateTime(startTime1, endTime1);
                PatentStarListDto dto1 = new PatentStarListDto();
                BeanUtils.copyProperties(dto, dto1);
                dto1.setStartTime(dateTimes.get(0));
                dto1.setEndTime(dateTimes.get(1));
                this.setConditions(dto1);
                PatentStarListDto dto2 = new PatentStarListDto();
                BeanUtils.copyProperties(dto, dto2);
                dto2.setStartTime(dateTimes.get(2));
                dto2.setEndTime(dateTimes.get(3));
                this.setConditions(dto2);
                patentStarListDtos.add(dto1);
                patentStarListDtos.add(dto2);
            }
            else{
                reDtos.add(dto);
            }

        }

        return reDtos;
    }

    public void setConditions(PatentStarListDto patentStarListDto) {
        DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyyMMdd");
        String startStr =formatter.print(patentStarListDto.getStartTime());
        String endStr =formatter.print(patentStarListDto.getEndTime());
        String cond = "*(" + startStr+ ">" + endStr + "/" + "AD)";
        Integer len =patentStarListDto.getOrginCondition().length();
        StringBuilder stringBuilder =new StringBuilder(patentStarListDto.getOrginCondition());
        stringBuilder.insert(len-1,cond);
        patentStarListDto.setCurrentQuery(stringBuilder.toString());
    }

    /**
     * @param appNo
     * @return
     * @throws IOException
     * @author 李仁杰
     * 从专利之星获取中国专利著录
     */
    public String getCnBibApi(String appNo) {
        String url = "https://api.patentstar.com.cn/api/Patent/CnBibo/" + appNo;
        String appId = "2000041";
        String appkey = "F0E183D5F02C48E391F5FADF1B646F54";
        Long currentTimeMillis = System.currentTimeMillis() / 1000;
        String Sign = appId + appkey + currentTimeMillis.toString();
        String signMd5 = FormatUtil.MD5(Sign);
        // 创建一个OkHttpClient对象
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .build();
        // 创建一个请求对象
        Request request = new Request.Builder().url(url)
                .addHeader("_appid", "2000041")
                .addHeader("_timestamp", currentTimeMillis.toString())
                .addHeader("_sign", signMd5)
                .get().build();
        // 发送请求获取响应
        try {
            Response response = okHttpClient.newCall(request).execute();
            // 判断请求是否成功
            if (response.isSuccessful()) {
                response.body().toString();
                // 打印服务端返回结果
                return Objects.requireNonNull(response.body()).string();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "{}";
    }


    /**
     * @param
     * @return
     * @throws IOException
     * @author 李仁杰
     * 从专利之星获取中国专利摘要附图
     */
    public String getPictureApi(String appNo) {
        String url = "https://api.patentstar.com.cn/api/Patent/CnMainImage/" + appNo;
        String appId = "2000041";
        String appkey = "F0E183D5F02C48E391F5FADF1B646F54";
        Long currentTimeMillis = System.currentTimeMillis() / 1000;
        String Sign = appId + appkey + currentTimeMillis.toString();
        String signMd5 = FormatUtil.MD5(Sign);
        // 创建一个OkHttpClient对象
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .build();
        // 创建一个请求对象
        Request request = new Request.Builder().url(url)
                .addHeader("_appid", "2000041")
                .addHeader("_timestamp", currentTimeMillis.toString())
                .addHeader("_sign", signMd5)
                .get().build();
        // 发送请求获取响应
        try {
            Response response = okHttpClient.newCall(request).execute();
            // 判断请求是否成功
            if (response.isSuccessful()) {
                response.body().toString();
                // 打印服务端返回结果
                return Objects.requireNonNull(response.body()).string();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "{}";
    }

    /**
     * @param appNo
     * @return
     * @throws IOException
     * @author 李仁杰
     * 从专利之星获取中国专利外观图
     */
    public String getWGPictureApi(String appNo) throws IOException {

        String url = "https://api.patentstar.com.cn/api/Patent/CnWGImage/" + appNo;
        String appId = "2000041";
        String appkey = "F0E183D5F02C48E391F5FADF1B646F54";
        Long currentTimeMillis = System.currentTimeMillis() / 1000;
        String Sign = appId + appkey + currentTimeMillis.toString();
        String signMd5 = FormatUtil.MD5(Sign);
        // 创建一个OkHttpClient对象
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .build();
        // 创建一个请求对象
        Request request = new Request.Builder().url(url)
                .addHeader("_appid", "2000041")
                .addHeader("_timestamp", currentTimeMillis.toString())
                .addHeader("_sign", signMd5)
                .get().build();
        // 发送请求获取响应
        try {
            Response response = okHttpClient.newCall(request).execute();
            // 判断请求是否成功
            if (response.isSuccessful()) {
                response.body().toString();
                // 打印服务端返回结果
                return Objects.requireNonNull(response.body()).string();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "{}";
    }

    /**
     * @param appNo
     * @return
     * @throws IOException
     * @author 李仁杰
     * 从专利之星获取中国专利法律状态
     */
    public String getCnLegalApi(String appNo) {
        String url = "https://api.patentstar.com.cn/api/Patent/CnLegal/" + appNo;
        String appId = "2000041";
        String appkey = "F0E183D5F02C48E391F5FADF1B646F54";
        Long currentTimeMillis = System.currentTimeMillis() / 1000;
        String Sign = appId + appkey + currentTimeMillis.toString();
        String signMd5 = FormatUtil.MD5(Sign);
        // 创建一个OkHttpClient对象
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .build();
        // 创建一个请求对象
        Request request = new Request.Builder().url(url)
                .addHeader("_appid", "2000041")
                .addHeader("_timestamp", currentTimeMillis.toString())
                .addHeader("_sign", signMd5)
                .get().build();
        // 发送请求获取响应
        try {
            Response response = okHttpClient.newCall(request).execute();
            // 判断请求是否成功
            if (response.isSuccessful()) {
                response.body().toString();
                // 打印服务端返回结果
                return Objects.requireNonNull(response.body()).string();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "{}";
    }

    /**
     * @param appNo
     * @return
     * @throws IOException
     * @author 李仁杰
     * 从专利之星获取中国专利全文图片
     */
    public String getCnPdfApi(String appNo) throws IOException {
        String url = "https://api.patentstar.com.cn/api/Patent/CnPdf/" + appNo;
        String appId = "2000041";
        String appkey = "F0E183D5F02C48E391F5FADF1B646F54";
        Long currentTimeMillis = System.currentTimeMillis() / 1000;
        String Sign = appId + appkey + currentTimeMillis.toString();
        String signMd5 = FormatUtil.MD5(Sign);
        // 创建一个OkHttpClient对象
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .build();
        // 创建一个请求对象
        Request request = new Request.Builder().url(url)
                .addHeader("_appid", "2000041")
                .addHeader("_timestamp", currentTimeMillis.toString())
                .addHeader("_sign", signMd5)
                .get().build();
        // 发送请求获取响应
        try {
            Response response = okHttpClient.newCall(request).execute();
            // 判断请求是否成功
            if (response.isSuccessful()) {
                response.body().toString();
                // 打印服务端返回结果
                return Objects.requireNonNull(response.body()).string();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "{}";
    }

    /**
     * @param appNo
     * @return
     * @throws IOException
     * @author 李仁杰
     * 从专利之星获取中国专利全文文本
     */

    public String getCnFullXmlApi(String appNo) throws IOException {
        String url = "https://api.patentstar.com.cn/api/Patent/CnFullXml/" + appNo;
        String appId = "2000041";
        String appkey = "F0E183D5F02C48E391F5FADF1B646F54";
        Long currentTimeMillis = System.currentTimeMillis() / 1000;
        String Sign = appId + appkey + currentTimeMillis.toString();
        String signMd5 = FormatUtil.MD5(Sign);
        // 创建一个OkHttpClient对象
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .build();
        // 创建一个请求对象
        Request request = new Request.Builder().url(url)
                .addHeader("_appid", "2000041")
                .addHeader("_timestamp", currentTimeMillis.toString())
                .addHeader("_sign", signMd5)
                .get().build();
        // 发送请求获取响应
        try {
            Response response = okHttpClient.newCall(request).execute();
            // 判断请求是否成功
            if (response.isSuccessful()) {
                response.body().toString();
                // 打印服务端返回结果
                return Objects.requireNonNull(response.body()).string();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "{}";
    }

    /**
     * @param patentNo
     * @return
     * @throws IOException
     * @author 李仁杰
     * 从专利之星获取世界专利pdf
     */
    public String getEnPdfApi(String patentNo) {
        String url = "  https://api.patentstar.com.cn/api/Patent/EnPdf/" + patentNo;
        String appId = "2000041";
        String appkey = "F0E183D5F02C48E391F5FADF1B646F54";
        Long currentTimeMillis = System.currentTimeMillis() / 1000;
        String Sign = appId + appkey + currentTimeMillis.toString();
        String signMd5 = FormatUtil.MD5(Sign);
        // 创建一个OkHttpClient对象
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .build();
        // 创建一个请求对象
        Request request = new Request.Builder().url(url)
                .addHeader("_appid", "2000041")
                .addHeader("_timestamp", currentTimeMillis.toString())
                .addHeader("_sign", signMd5)
                .get().build();
        // 发送请求获取响应
        try {
            Response response = okHttpClient.newCall(request).execute();
            // 判断请求是否成功
            if (response.isSuccessful()) {
                response.body().toString();
                // 打印服务端返回结果
                return Objects.requireNonNull(response.body()).string();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "{}";
    }

    /**
     * @param patentNo
     * @return
     * @throws IOException
     * @author 李仁杰
     * 从专利之星获取世界专利著录信息
     */
    public String getENBibApi(String patentNo) {
        String url = "https://api.patentstar.com.cn/api/Patent/ENBib/" + patentNo;
        String appId = "2000041";
        String appkey = "F0E183D5F02C48E391F5FADF1B646F54";
        Long currentTimeMillis = System.currentTimeMillis() / 1000;
        String Sign = appId + appkey + currentTimeMillis.toString();
        String signMd5 = FormatUtil.MD5(Sign);
        // 创建一个OkHttpClient对象
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .build();
        // 创建一个请求对象
        Request request = new Request.Builder().url(url)
                .addHeader("_appid", "2000041")
                .addHeader("_timestamp", currentTimeMillis.toString())
                .addHeader("_sign", signMd5)
                .get().build();
        // 发送请求获取响应
        try {
            Response response = okHttpClient.newCall(request).execute();
            // 判断请求是否成功
            if (response.isSuccessful()) {
                response.body().toString();
                // 打印服务端返回结果
                return Objects.requireNonNull(response.body()).string();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "{}";
    }

    /**
     * @param patentNo
     * @return
     * @throws IOException
     * @author 李仁杰
     * 从专利之星获取同族专利
     */
    public String getFamilyByPubNoApi(String patentNo) {
        String url = "https://api.patentstar.com.cn/api/Patent/FamilyByPubNo/" + patentNo;
        String appId = "2000041";
        String appkey = "F0E183D5F02C48E391F5FADF1B646F54";
        Long currentTimeMillis = System.currentTimeMillis() / 1000;
        String Sign = appId + appkey + currentTimeMillis.toString();
        String signMd5 = FormatUtil.MD5(Sign);
        // 创建一个OkHttpClient对象
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .build();
        // 创建一个请求对象
        Request request = new Request.Builder().url(url)
                .addHeader("_appid", "2000041")
                .addHeader("_timestamp", currentTimeMillis.toString())
                .addHeader("_sign", signMd5)
                .get().build();
        // 发送请求获取响应
        try {
            Response response = okHttpClient.newCall(request).execute();
            // 判断请求是否成功
            if (response.isSuccessful()) {
                response.body().toString();
                // 打印服务端返回结果
                return Objects.requireNonNull(response.body()).string();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "{}";
    }

    /**
     * @param patentNo
     * @return
     * @throws IOException
     * @author 李仁杰
     * 获得专利被引用次数api
     */
    public String getCitedNumByPubNoApi(String patentNo) throws IOException {
        String url = "https://api.patentstar.com.cn/api/Patent/CitedNumByPubNo/" + patentNo;
        String appId = "2000041";
        String appkey = "F0E183D5F02C48E391F5FADF1B646F54";
        Long currentTimeMillis = System.currentTimeMillis() / 1000;
        String Sign = appId + appkey + currentTimeMillis.toString();
        String signMd5 = FormatUtil.MD5(Sign);
        // 创建一个OkHttpClient对象
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .build();
        // 创建一个请求对象
        Request request = new Request.Builder().url(url)
                .addHeader("_appid", "2000041")
                .addHeader("_timestamp", currentTimeMillis.toString())
                .addHeader("_sign", signMd5)
                .get().build();
        // 发送请求获取响应
        try {
            Response response = okHttpClient.newCall(request).execute();
            // 判断请求是否成功
            if (response.isSuccessful()) {
                response.body().toString();
                // 打印服务端返回结果
                return Objects.requireNonNull(response.body()).string();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "{}";
    }


}
