package com.trs.project.timer;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.trs.project.entity.*;
import com.trs.project.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.quartz.DisallowConcurrentExecution;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.ObjectUtils;
import org.springframework.web.client.RestTemplate;
import us.codecraft.webmagic.selector.Json;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;

@Slf4j
@Component
public class BusinessTask {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private JusticeItemsInfoService justiceItemsInfoService;

    @Autowired
    private BusinessInfoService businessInfoService;

    @Autowired
    private MajorShareholdersService majorShareholdersService;

    @Autowired
    private PunishService punishService;

    @Autowired
    private PunishBiangengService punishBiangengService;

    @Autowired
    private PunishWeifaService punishWeifaService;

    @Autowired
    private JusticeService justiceService;

    @Autowired
    private IntellectualService intellectualService;

    @Autowired
    private EmpLabelsService empLabelsService;

    @Autowired
    private EmpLabelsUpService empLabelsUpService;

    @Autowired
    private InvestInfoService investInfoService;

    @Autowired
    private ClusterTagInfoService clusterTagInfoService;

    @Autowired
    private ValueInfoService valueInfoService;

    @Autowired
    private ReportInfoService reportInfoService;

    @Value("${gsl.keyUrl}")
    private String keyUrl;

    @Value("${gsl.requestUrl}")
    private String requestUrl;

    @Value("${gsl.key}")
    private String key;

    @Value("${gsl.uid}")
    private String uid;

    private Long timeMillis = System.currentTimeMillis();

    @Autowired
    private BusinessFtpTask businessFtpTask;

    public void execute() {
        log.info("enterTasks定时任务执行时间："+new Date());
        timeMillis = System.currentTimeMillis();
        QueryWrapper<BusinessInfo> qw=new QueryWrapper<>();
        qw.eq("business_type",1)/*.isNull("tag_size_code")*/;
        //qw.isNull("business_type");
        List<BusinessInfo> businessInfoList = businessInfoService.list(qw);
        for(BusinessInfo businessInfo : businessInfoList){
            //保存企业基本信息
            saveBusinessInfo(businessInfo.getName());
            //saveBusinessInfo(businessInfo);
            //保存对外投资invest_info
            saveInvestInfo(businessInfo);
            saveMajorShareholders(businessInfo);
            //保存价值分析
            saveValueInfo(businessInfo,225);
            //年报
            saveReportInfo(businessInfo,41);
            //知识产权
            saveIntellectual(businessInfo,186);//1.	软件著作权 186
            saveIntellectual(businessInfo,185);//2.	著作权 185
            saveIntellectual(businessInfo,183);//3.	专利列表 183
            saveIntellectual(businessInfo,187);//4.	域名信息 187
            //处罚
            saveJustice(businessInfo,209);
            //重点企业名单和风险标签
            savePunish(businessInfo, 108);//1.行政处罚 108
            savePunish(businessInfo,109);//2.环保处罚列表 109
            //savePunish(businessInfo,110);//3.	环保处罚详情110
            savePunish(businessInfo,111);//4.	动产抵押 111
            //savePunish(businessInfo,116);//5.	股权出质 116
            savePunish(businessInfo,120);//6.	经营异常 120
            //savePunishBiangeng(businessInfo);//7.	股权变更 211----
            //savePunish(businessInfo,212);//8.	股权冻结 212------
            savePunishWeifa(businessInfo);//9.	严重违法 121
            saveJusticeItemsInfo(businessInfo,169);//1.	被执行企业 169

            saveJusticeItemsInfo(businessInfo,170);//2.	失信被执行企业 170

            saveJusticeItemsInfo(businessInfo,173);//3.	法院公告 173

            saveJusticeItemsInfo(businessInfo,208);//4.	立案信息 208

            saveJusticeItemsInfo(businessInfo,209);//5.	整体诉讼 209

            saveJusticeItemsInfo(businessInfo,210);//6.	行贿违法 210
        }
    }

    public void saveBusinessInfo116AndOrther() {
        log.info("enterTasks定时任务执行时间："+new Date());
        timeMillis = System.currentTimeMillis();
        QueryWrapper<BusinessInfo> qw=new QueryWrapper<>();
        qw.eq("business_type",1)/*.isNull("tag_size_code")*/;
        //qw.isNull("business_type");
        List<BusinessInfo> businessInfoList = businessInfoService.list(qw);
        for(BusinessInfo businessInfo : businessInfoList){
            //保存企业基本信息
            saveBusinessInfo(businessInfo.getName());
            //saveBusinessInfo(businessInfo);
            //保存对外投资invest_info
            saveInvestInfo(businessInfo);
            saveMajorShareholders(businessInfo);
            //保存价值分析
            saveValueInfo(businessInfo,225);
            //年报
            saveReportInfo(businessInfo,41);
            //知识产权
            saveIntellectual(businessInfo,186);//1.	软件著作权 186
            saveIntellectual(businessInfo,185);//2.	著作权 185
            saveIntellectual(businessInfo,183);//3.	专利列表 183
            saveIntellectual(businessInfo,187);//4.	域名信息 187
            //处罚
            saveJustice(businessInfo,209);
            //重点企业名单和风险标签
            savePunish(businessInfo, 108);//1.行政处罚 108
            savePunish(businessInfo,109);//2.环保处罚列表 109
            //savePunish(businessInfo,110);//3.	环保处罚详情110
            savePunish(businessInfo,111);//4.	动产抵押 111
            //savePunish(businessInfo,116);//5.	股权出质 116
            savePunish(businessInfo,120);//6.	经营异常 120
            //savePunishBiangeng(businessInfo);//7.	股权变更 211----
            //savePunish(businessInfo,212);//8.	股权冻结 212------
            savePunishWeifa(businessInfo);//9.	严重违法 121
            saveJusticeItemsInfo(businessInfo,169);//1.	被执行企业 169

            saveJusticeItemsInfo(businessInfo,170);//2.	失信被执行企业 170

            saveJusticeItemsInfo(businessInfo,173);//3.	法院公告 173

            saveJusticeItemsInfo(businessInfo,208);//4.	立案信息 208

            saveJusticeItemsInfo(businessInfo,209);//5.	整体诉讼 209

            saveJusticeItemsInfo(businessInfo,210);//6.	行贿违法 210
        }
    }
    /**
     * 获取签名
     * @param timeMillis
     * @param param
     * @param classId
     * @return
     */
    public String getSign(Long timeMillis, String param, Integer classId){
        MultiValueMap<String, Object> map = new LinkedMultiValueMap<String, Object>();
        map.add("key",key);
        map.add("uid",uid);
        map.add("timestamp",timeMillis);
        map.add("classId",classId);
        map.add("param",param);
        log.info("==========getSign=============");
        log.info("classId==="+classId);
        log.info("requestUrl==="+requestUrl);
        //log.info("param==="+JSON.toJSONString(param));
        JSONObject result = httpSignMethod(keyUrl, map);
        log.info("result==="+JSON.toJSONString(result));
        return result.getString("data");
    }
    /**
     * 获取数据
     * @param timeMillis
     * @param sign
     * @param param
     * @param classId
     * @return
     */
    public JSONObject getRequestData(Long timeMillis, String sign, String param, Integer classId){
        JSONObject postParam = new JSONObject();
        postParam.put("key",key);
        postParam.put("uid",uid);
        postParam.put("timestamp",timeMillis);
        postParam.put("classId",classId);
        postParam.put("sign",sign);
        postParam.put("param",param);
        log.info("===========getRequestData============");
        log.info("classId==="+classId);
        log.info("requestUrl==="+requestUrl);
        log.info("param==="+JSON.toJSONString(param));
        JSONObject result = httpPostMethod(requestUrl, postParam);
        log.info("result==="+JSON.toJSONString(result));
        return result;
    }
    public JSONObject getData(String name, Integer classId){
        JSONObject postParam = new JSONObject();
        postParam.put("name",name);
        String param = JSON.toJSONString(postParam);
        String sign = getSign(timeMillis, param, classId);
        return getRequestData(timeMillis, sign, param, classId);
    }
    //工商信息
    public BusinessInfo saveBusinessInfo(String name){
        //String name = "";
        Integer classId = 20;
        JSONObject businessData = null;
        try {
            businessData = getData(name,classId).getJSONObject("data");
        }catch (Exception e){
            e.printStackTrace();
        }
        if(businessData!=null ){
            try{
                BusinessInfo businessInfo = JSONObject.parseObject(businessData.toJSONString(), BusinessInfo.class);
                //log.info("domain==="+businessData.get("domain").toString());
                businessInfo.setDomains(businessData.get("domain").toString());
                //name = businessInfo1.getName();
                //企业规模
                Map<String,String> jsonBusinessInfo_size = findBusinessInfo_size(name);
                if(jsonBusinessInfo_size.get("tag_size_code")!=null){
                    businessInfo.setTagSizeCode(jsonBusinessInfo_size.get("tag_size_code"));
                }
                if(jsonBusinessInfo_size.get("tag_size_name")!=null){
                    businessInfo.setTagSizeName(jsonBusinessInfo_size.get("tag_size_name"));
                }
                //其他基本信息
                Map<String,String> jsonBusinessInfo_other = findBusinessInfo_other(name);
                if(StringUtils.isNotBlank(jsonBusinessInfo_other.get("city"))){
                    if(StringUtils.isNotBlank(jsonBusinessInfo_other.get("city"))){
                        businessInfo.setCity(jsonBusinessInfo_other.get("city"));
                    }
                    if(StringUtils.isNotBlank(jsonBusinessInfo_other.get("managementLocation"))){
                        businessInfo.setManagementLocation(jsonBusinessInfo_other.get("managementLocation"));
                    }
                    if(StringUtils.isNotBlank(jsonBusinessInfo_other.get("bondNum"))){
                        businessInfo.setBondNum(jsonBusinessInfo_other.get("bondNum"));
                    }
                    if(StringUtils.isNotBlank(jsonBusinessInfo_other.get("industry"))){
                        businessInfo.setIndustry(jsonBusinessInfo_other.get("industry"));
                    }
                    if(StringUtils.isNotBlank(jsonBusinessInfo_other.get("bondName"))){
                        businessInfo.setBondName(jsonBusinessInfo_other.get("bondName"));
                    }
                    if(StringUtils.isNotBlank(jsonBusinessInfo_other.get("approvedTime"))){
                        businessInfo.setApprovedTime(jsonBusinessInfo_other.get("approvedTime"));
                    }
                    if(StringUtils.isNotBlank(jsonBusinessInfo_other.get("socialStaffNum"))){
                        businessInfo.setSocialStaffNum(jsonBusinessInfo_other.get("socialStaffNum"));
                    }
                    if(StringUtils.isNotBlank(jsonBusinessInfo_other.get("regInstitute"))){
                        businessInfo.setRegInstitute(jsonBusinessInfo_other.get("regInstitute"));
                    }
                    if(StringUtils.isNotBlank(jsonBusinessInfo_other.get("percentileScore"))){
                        businessInfo.setPercentileScore(jsonBusinessInfo_other.get("percentileScore"));
                    }
                }
                Map<String, String> getClusterTag = find_getClusterTag(name);
                String industryChainName = getClusterTag.get("industryChain");
                String entQualityName = getClusterTag.get("entQuality");
                int data1 = industryChainName.indexOf("data=null");
                if(data1 < 0){
                    ClusterTagInfo clusterTagInfo = new ClusterTagInfo();
                    clusterTagInfo.setEmpId(businessInfo.getId());
                    clusterTagInfo.setEmpCreditNo(businessInfo.getCreditNo());
                    clusterTagInfo.setIndustryChain(industryChainName);
                    clusterTagInfo.setEntQuality(entQualityName);
                    clusterTagInfo.setSavetime(LocalDateTime.now());
                    clusterTagInfoService.saveOrUpdate(clusterTagInfo);
                }
                //标签
                String industryChain = findBusinessInfo_major(name, "industryChain").get("industryChain");
                if(!ObjectUtils.isEmpty(industryChain)){
                    int dataChain= industryChain.indexOf("data=null");
                    if(dataChain < 0){
                        businessInfo.setIndustryChain(industryChain);
                    }
                }
                String entQuality = findBusinessInfo_major(name, "entQuality").get("entQuality");
                if(!ObjectUtils.isEmpty(entQuality)){
                    if(StringUtils.isNotBlank(entQuality)){
                        businessInfo.setEntQuality(entQuality);
                    }
                }
                businessInfo.setSavetime(LocalDateTime.now());
                boolean b = businessInfoService.saveOrUpdate(businessInfo);
                return businessInfo;
            }catch (Exception e){
                e.printStackTrace();
            }
        }else{
            log.info("不匹配，入库失败,工商信息:"+name/*+getData(name,classId)*/);
        }
        return null;
    }

    //工商信息
    public BusinessInfo saveBusinessInfo5000(String name){
        //String name = "";
        Integer classId = 20;
        JSONObject businessData = null;
        try {
            businessData = getData(name,classId).getJSONObject("data");
        }catch (Exception e){
            e.printStackTrace();
        }
        if(businessData!=null ){
            try{
                BusinessInfo businessInfo = JSONObject.parseObject(businessData.toJSONString(), BusinessInfo.class);
                businessInfo.setDomains(businessData.get("domain").toString());
                //name = businessInfo1.getName();
                //企业规模
                Map<String,String> jsonBusinessInfo_size = findBusinessInfo_size(name);
                if(jsonBusinessInfo_size.get("tag_size_code")!=null){
                    businessInfo.setTagSizeCode(jsonBusinessInfo_size.get("tag_size_code"));
                }
                if(jsonBusinessInfo_size.get("tag_size_name")!=null){
                    businessInfo.setTagSizeName(jsonBusinessInfo_size.get("tag_size_name"));
                }
                //其他基本信息
                Map<String,String> jsonBusinessInfo_other = findBusinessInfo_other(name);
                log.info("jsonBusinessInfo_other==="+jsonBusinessInfo_other);
                if(StringUtils.isNotBlank(jsonBusinessInfo_other.get("city"))){
                    businessInfo.setCity(jsonBusinessInfo_other.get("city"));
                }
                if(StringUtils.isNotBlank(jsonBusinessInfo_other.get("managementLocation"))){
                    businessInfo.setManagementLocation(jsonBusinessInfo_other.get("managementLocation"));
                }
                if(StringUtils.isNotBlank(jsonBusinessInfo_other.get("bondNum"))){
                    businessInfo.setBondNum(jsonBusinessInfo_other.get("bondNum"));
                }
                if(StringUtils.isNotBlank(jsonBusinessInfo_other.get("industry"))){
                    businessInfo.setIndustry(jsonBusinessInfo_other.get("industry"));
                }
                if(StringUtils.isNotBlank(jsonBusinessInfo_other.get("bondName"))){
                    businessInfo.setBondName(jsonBusinessInfo_other.get("bondName"));
                }
                if(StringUtils.isNotBlank(jsonBusinessInfo_other.get("approvedTime"))){
                    businessInfo.setApprovedTime(jsonBusinessInfo_other.get("approvedTime"));
                }
                if(StringUtils.isNotBlank(jsonBusinessInfo_other.get("socialStaffNum"))){
                    businessInfo.setSocialStaffNum(jsonBusinessInfo_other.get("socialStaffNum"));
                }
                if(StringUtils.isNotBlank(jsonBusinessInfo_other.get("regInstitute"))){
                    businessInfo.setRegInstitute(jsonBusinessInfo_other.get("regInstitute"));
                }
                if(StringUtils.isNotBlank(jsonBusinessInfo_other.get("percentileScore"))){
                    businessInfo.setPercentileScore(jsonBusinessInfo_other.get("percentileScore"));
                }
                Map<String, String> getClusterTag = find_getClusterTag(name);
                String industryChainName = getClusterTag.get("industryChain");
                String entQualityName = getClusterTag.get("entQuality");
                int data1 = industryChainName.indexOf("data=null");
                if(data1 < 0){
                    ClusterTagInfo clusterTagInfo = new ClusterTagInfo();
                    clusterTagInfo.setEmpId(businessInfo.getId());
                    clusterTagInfo.setEmpCreditNo(businessInfo.getCreditNo());
                    clusterTagInfo.setIndustryChain(industryChainName);
                    clusterTagInfo.setEntQuality(entQualityName);
                    clusterTagInfo.setSavetime(LocalDateTime.now());
                    clusterTagInfoService.saveOrUpdate(clusterTagInfo);
                }
                //标签
                String industryChain = findBusinessInfo_major(name, "industryChain").get("industryChain");
                if(!ObjectUtils.isEmpty(industryChain)){
                    int dataChain= industryChain.indexOf("data=null");
                    if(dataChain < 0){
                        businessInfo.setIndustryChain(industryChain);
                    }
                }
                String entQuality = findBusinessInfo_major(name, "entQuality").get("entQuality");
                if(!ObjectUtils.isEmpty(entQuality)){
                    if(StringUtils.isNotBlank(entQuality)){
                        businessInfo.setEntQuality(entQuality);
                    }
                }
                businessInfo.setBusinessType("2");
                businessInfo.setSavetime(LocalDateTime.now());
                boolean b = businessInfoService.saveOrUpdate(businessInfo);
                return businessInfo;
            }catch (Exception e){
                e.printStackTrace();
            }
        }else{
            log.info("不匹配，入库失败,工商信息:"+name/*+getData(name,classId)*/);
        }
        return null;
    }
    //企业规模
    public Map<String,String> findBusinessInfo_size(String name){
        Map<String,String> map = new HashMap();
        Integer classId = 204;
        JSONObject businessData = null;
        try {
            businessData = getData(name,classId).getJSONObject("data");
        }catch (Exception e){
            e.printStackTrace();
        }
        if(businessData!=null ){
            try{
                map.put("tag_size_code",businessData.getString("tag_code"));
                map.put("tag_size_name",businessData.getString("tag_name"));
            }catch (Exception e){
                e.printStackTrace();
            }
        }else{
            log.info("不匹配，入库失败,企业规模:"+name/*+getData(name,classId)*/);
        }
        return map;
    }
    //企业基本信息2
    public Map<String,String> findBusinessInfo_other(String name){
        Map<String,String> map = new HashMap();
        Integer classId = 226;
        JSONObject postParam = new JSONObject();
        postParam.put("name",name);
        postParam.put("uri","/tyc/baseinfo");
        String param = JSON.toJSONString(postParam);
        String sign = getSign(timeMillis, param, classId);
        JSONObject businessData = null;
        try {
            businessData = getRequestData(timeMillis, sign, param, classId).getJSONObject("data");
        }catch (Exception e){
            e.printStackTrace();
        }
        if(businessData!=null ){
            try{
                map.put("city",businessData.getString("city"));
                map.put("managementLocation",businessData.getString("managementLocation"));//注册地址
                map.put("bondNum",businessData.getString("bondNum"));//股票代码
                map.put("industry",businessData.getString("industry"));//行业门类中文字段（国标）
                map.put("bondName",businessData.getString("bondName"));//简称
                map.put("approvedTime",businessData.getString("approvedTime"));//核准日期
                map.put("socialStaffNum",businessData.getString("socialStaffNum"));//参保人数
                map.put("regInstitute",businessData.getString("regInstitute"));//等级机关
                map.put("percentileScore",businessData.getString("percentileScore"));//企业综合价值
            }catch (Exception e){
                e.printStackTrace();
            }
        }else{
            log.info("不匹配，入库失败,企业基本信息2:"+name/*+getData(name,classId)*/);
        }
        return map;
    }
    //9.主要信号 221
    public Map<String,String> find_getClusterTag(String name){
        Map<String,String> map = new HashMap();
        Integer classId = 221;
        JSONObject postParam = new JSONObject();
        postParam.put("entName",name);
        postParam.put("uri","/enterprise/getClusterTag");
        String param = JSON.toJSONString(postParam);
        String sign = getSign(timeMillis, param, classId);
        String businessData = null;
        try {
            businessData = getRequestData(timeMillis, sign, param, classId).getString("data");
        }catch (Exception e){
            e.printStackTrace();
        }
        if(businessData!=null ){
            map.put("industryChain",businessData);
            map.put("entQuality",businessData);
        }else{
            log.info("不匹配，入库失败,主要信号:"+name/*+getData(name,classId)*/);
        }
        return map;
    }
    //领域标签和信号标签
    public Map<String,String> findBusinessInfo_major(String name,String labelType){
        Map<String,String> map = new HashMap();
        Integer classId = 223;
        JSONObject postParam = new JSONObject();
        postParam.put("entName",name);
        postParam.put("timeKey",30);
        postParam.put("labelType",labelType);
        postParam.put("uri","/enterprise/getEnpMainInfo");
        String param = JSON.toJSONString(postParam);
        String sign = getSign(timeMillis, param, classId);
        String businessData = null;
        try {
            businessData = getRequestData(timeMillis, sign, param, classId).getString("data");
        }catch (Exception e){
            e.printStackTrace();
        }
        if(businessData!=null ){
            map.put("industryChain",businessData);
            map.put("entQuality",businessData);
        }else{
            log.info("不匹配，入库失败,领域标签和信号标签:"+name/*+getData(name,classId)*/);
        }
        return map;
    }
    //对外投资
    public void saveInvestInfo(BusinessInfo businessInfo){
        Integer classId = 28;
        JSONArray businessData = null;
        try {
            businessData = getData(businessInfo.getName(),classId).getJSONArray("data");
        }catch (Exception e){
            e.printStackTrace();
        }
        if(businessData!=null && businessData.size()>0){
            try{
                String data = businessData.toJSONString();
                JSONObject json = new JSONObject();
                json.put("data",data);
                InvestInfo info = JSONObject.parseObject(json.toJSONString(), InvestInfo.class);
                info.setData(JSON.toJSONString(businessData, SerializerFeature.WriteMapNullValue));
                info.setEmpId(businessInfo.getId());
                info.setEmpCreditNo(businessInfo.getCreditNo());
                info.setSavetime(LocalDateTime.now());
                boolean b = investInfoService.saveOrUpdate(info);
            }catch (Exception e){
                e.printStackTrace();
            }
        }else{
            log.info("不匹配，入库失败,对外投资:"+businessInfo.getName()+getData(businessInfo.getName(),classId));
        }
    }
    //工商股东
    public void saveMajorShareholders(BusinessInfo businessInfo) {
        Integer classId = 21;
        JSONObject businessData = null;
        try {
            businessData = getData(businessInfo.getCreditNo(),classId).getJSONObject("data");
        }catch (Exception e){
            e.printStackTrace();
        }
        if(businessData!=null && businessData.size()>0){
            try{
                MajorShareholders info = JSONObject.parseObject(businessData.toJSONString(), MajorShareholders.class);
                if(info.getTotal() != 0 && info.getTotal() != null && info.getItems() != null && info.getItems() != ""){
                    info.setEmpId(businessInfo.getId());
                    Object items = businessData.get("items");
                    if (!ObjectUtils.isEmpty(items)){
                        info.setItems(JSON.toJSONString(items, SerializerFeature.WriteMapNullValue));
                    }
                    info.setEmpCreditNo(businessInfo.getCreditNo());
                    info.setSavetime(LocalDateTime.now());
                    boolean b = majorShareholdersService.saveOrUpdate(info);
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }else{
            log.info("不匹配，入库失败,工商股东:"+businessInfo.getName()+getData(businessInfo.getName(),classId));
        }
    }
    public void saveBusinessRiskLabelCheckFTP(Integer pageNum) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        //现在日期
        String now = format.format(new Date());
        //过去七天
        calendar.setTime(new Date());
        calendar.add(Calendar.MONTH, -3);
        Date d = calendar.getTime();
        String day7 = format.format(d);
        Integer classId = 224;
        JSONObject postParam = new JSONObject();
        postParam.put("region","内蒙古");
        postParam.put("bgtime",day7);
        postParam.put("edtime",now);
        postParam.put("pageNum",pageNum);
        postParam.put("pageSize","20");
        String sign = getSign(timeMillis, postParam.toJSONString(), classId);
        JSONObject requestData = null;
        try {
            requestData = getRequestData(timeMillis, sign, postParam.toJSONString(), classId);
        }catch (Exception e){
            e.printStackTrace();
        }
        QueryWrapper<BusinessInfo> queryWrapper = new QueryWrapper<BusinessInfo>();
        queryWrapper.eq("BUSINESS_TYPE",1);
        List<BusinessInfo> list = businessInfoService.list(queryWrapper);

        Map<String,String> businessInfoMap = new HashMap<String,String>();
        for (BusinessInfo businessInfo : list) {
            businessInfoMap.put(businessInfo.getName(),businessInfo.getName());
        }
        if(requestData!=null && requestData.size()>0) {
            try {
                JSONArray items = requestData.getJSONObject("data").getJSONArray("list");
                for (int i = 0; i < items.size(); i++) {
                    String entName = items.getJSONObject(i).getString("entname");
                    String isMap = businessInfoMap.get(entName);
                    if(!ObjectUtils.isEmpty(isMap)){
                        log.info("跳出循环");
                        continue;
                    }
                    BusinessInfo businessInfo = saveBusinessInfo5000(entName);
                    String risk = items.getJSONObject(i).getString("risk");
                    EmpLabels empLabels = new EmpLabels();
                    empLabels.setEmpCreditNo(businessInfo.getCreditNo());
                    empLabels.setEntName(entName);
                    empLabels.setRisk(risk);
                    empLabels.setStartDate(day7);
                    empLabels.setEndDate(now);
                    QueryWrapper<EmpLabelsUp> empLabelsUpQueryWrapper = new QueryWrapper<EmpLabelsUp>();
                    empLabelsUpQueryWrapper.eq("EMP_CREDIT_NO",businessInfo.getCreditNo());
                    EmpLabelsUp empLabelsUp = new EmpLabelsUp();
                    empLabelsUp.setEmpCreditNo(businessInfo.getCreditNo());
                    empLabelsUp.setEntName(entName);
                    empLabelsUp.setRisk(risk);
                    empLabelsUp.setStartDate(day7);
                    empLabelsUp.setEndDate(now);
                    empLabelsUp.setSavetime(LocalDateTime.now());
                    empLabelsUpService.saveOrUpdate(empLabelsUp,empLabelsUpQueryWrapper);
                    empLabels.setSavetime(LocalDateTime.now());
                    boolean b = empLabelsService.saveOrUpdate(empLabels);
                    if(b){
                        log.info("入库成功");
                    }else {
                        log.info("入库失败");
                    }
                }
            } catch (Exception e) {
                log.info("入库失败，抛出异常");
                e.printStackTrace();
            }
        }
    }

    public void saveBusinessRiskLabel(Integer pageNum) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        //现在日期
        String now = format.format(new Date());
        //过去七天
        calendar.setTime(new Date());
        calendar.add(Calendar.MONTH, -3);
        Date d = calendar.getTime();
        String day7 = format.format(d);
        Integer classId = 224;
        JSONObject postParam = new JSONObject();
        postParam.put("region","内蒙古");
        postParam.put("bgtime",day7);
        postParam.put("edtime",now);
        postParam.put("pageNum",pageNum);
        postParam.put("pageSize","20");
        String sign = getSign(timeMillis, postParam.toJSONString(), classId);
        JSONObject requestData = null;
        try {
            requestData = getRequestData(timeMillis, sign, postParam.toJSONString(), classId);
        }catch (Exception e){
            e.printStackTrace();
        }
        if(requestData != null && requestData.size()>0) {
            try {
                JSONArray items = requestData.getJSONObject("data").getJSONArray("list");
                for (int i = 0; i < items.size(); i++) {
                    String entName = items.getJSONObject(i).getString("entname");
                    QueryWrapper<BusinessInfo> queryWrapper = new QueryWrapper<BusinessInfo>();
                    queryWrapper.eq("BUSINESS_TYPE",1);
                    queryWrapper.eq("NAME",entName);
                    List<BusinessInfo> list = businessInfoService.list(queryWrapper);
                    if(list.size() > 0){
                        continue;
                    }
                    BusinessInfo businessInfo = saveBusinessInfo5000(entName);
                    String risk = items.getJSONObject(i).getString("risk");
                    EmpLabels empLabels = new EmpLabels();
                    empLabels.setEmpCreditNo(businessInfo.getCreditNo());
                    empLabels.setEntName(entName);
                    empLabels.setRisk(risk);
                    empLabels.setStartDate(day7);
                    empLabels.setEndDate(now);
                    QueryWrapper<EmpLabelsUp> empLabelsUpQueryWrapper = new QueryWrapper<EmpLabelsUp>();
                    empLabelsUpQueryWrapper.eq("EMP_CREDIT_NO",businessInfo.getCreditNo());
                    EmpLabelsUp empLabelsUp = new EmpLabelsUp();
                    empLabelsUp.setEmpCreditNo(businessInfo.getCreditNo());
                    empLabelsUp.setEntName(entName);
                    empLabelsUp.setRisk(risk);
                    empLabelsUp.setStartDate(day7);
                    empLabelsUp.setEndDate(now);
                    empLabelsUp.setSavetime(LocalDateTime.now());
                    empLabelsUpService.saveOrUpdate(empLabelsUp,empLabelsUpQueryWrapper);
                    empLabels.setSavetime(LocalDateTime.now());
                    boolean b = empLabelsService.saveOrUpdate(empLabels);
                    if(b){
                        log.info("入库成功");
                    }else {
                        log.info("入库失败");
                    }
                }
            } catch (Exception e) {
                log.info("入库失败，抛出异常");
                e.printStackTrace();
            }
        }
    }
    //保存企业风险
    public void savePunish(BusinessInfo businessInfo,Integer classId){
        JSONObject businessData = null;
        try {
            businessData =  getData(businessInfo.getCreditNo(),classId).getJSONObject("data");
        }catch (Exception e){
            e.printStackTrace();
        }
        if(businessData!=null && businessData.size()>0){
            try{
                Punish info = JSONObject.parseObject(businessData.toJSONString(), Punish.class);
                if(info!=null && info.getTotal() != null && info.getTotal() != 0 && info.getItems() != null && info.getItems() != ""){
                    info.setId(businessInfo.getId()+classId);
                    Object items = businessData.get("items");
                    if (!ObjectUtils.isEmpty(items)){
                        info.setItems(JSON.toJSONString(items, SerializerFeature.WriteMapNullValue));
                    }
                    info.setEmpId(businessInfo.getId());
                    info.setEmpCreditNo(businessInfo.getCreditNo());
                    info.setType(classId);
                    info.setSavetime(LocalDateTime.now());
                    boolean b = punishService.saveOrUpdate(info);
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }else{
            log.info("不匹配，入库失败,保存企业风险:"+businessInfo.getName()+getData(businessInfo.getName(),classId));
        }
    }
    //保存股权变更
    public void savePunishBiangeng(BusinessInfo businessInfo){
        Integer classId = 211;
        JSONObject businessData = null;
        try {
            businessData = getData(businessInfo.getCreditNo(),classId).getJSONObject("data");
        }catch (Exception e){
            e.printStackTrace();
        }
        if(businessData!=null && businessData.size()>0){
            try{
                PunishBiangeng info = JSONObject.parseObject(businessData.toJSONString(), PunishBiangeng.class);
                if(info!=null){
                    info.setEmpId(businessInfo.getId());
                    info.setEmpCreditNo(businessInfo.getCreditNo());
                    info.setSavetime(LocalDateTime.now());
                    boolean b = punishBiangengService.saveOrUpdate(info);
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }else{
            log.info("不匹配，入库失败,保存股权变更:"+businessInfo.getName()+getData(businessInfo.getName(),classId));
        }
    }
    //保存严重违法
    public void savePunishWeifa(BusinessInfo businessInfo){
        Integer classId = 121;
        JSONObject businessData = null;
        try {
            businessData = getData(businessInfo.getCreditNo(),classId).getJSONObject("data");
        }catch (Exception e){
            e.printStackTrace();
        }
        if(businessData!=null && businessData.size()>0 ){
            try{
                PunishWeifa info = JSONObject.parseObject(businessData.toJSONString(), PunishWeifa.class);
                if(info!=null && businessInfo.getId() != null && businessInfo.getId() != "" && info.getExecution() != null && info.getExecution() != ""){
                    Object execution = businessData.get("execution");
                    if(!ObjectUtils.isEmpty(execution)){
                        info.setEmpCreditNo(JSON.toJSONString(execution, SerializerFeature.WriteMapNullValue));
                    }
                    info.setEmpId(businessInfo.getId());
                    info.setEmpCreditNo(businessInfo.getCreditNo());
                    info.setSavetime(LocalDateTime.now());
                    boolean b = punishWeifaService.saveOrUpdate(info);
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }else{
            log.info("不匹配，入库失败,保存严重违法:"+businessInfo.getName()+getData(businessInfo.getName(),classId));
        }
    }
    //保存司法诉讼
    public void saveJustice(BusinessInfo businessInfo,Integer classId){
        JSONObject businessData = null;
        try {
            businessData = getData(businessInfo.getCreditNo(),classId).getJSONObject("data");
        }catch (Exception e){
            e.printStackTrace();
        }
        if(businessData!=null && businessData.size() > 0){
            try{
                Justice info = JSONObject.parseObject(businessData.toJSONString(), Justice.class);
                if(!ObjectUtils.isEmpty(info)){
                    info.setEmpId(businessInfo.getId());
                    info.setEmpCreditNo(businessInfo.getCreditNo());
                    info.setSavetime(LocalDateTime.now());
                    boolean b = justiceService.saveOrUpdate(info);
                    if(b){
                        log.info("保存司法诉讼成功");
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }else{
            log.info("不匹配，入库失败,保存司法诉讼:"+businessInfo.getName()+getData(businessInfo.getName(),classId));
        }
    }
    //保存司法诉讼
    public void saveJusticeItemsInfo(BusinessInfo businessInfo,Integer classId){
        JSONObject businessData = null;
        try {
            businessData = getData(businessInfo.getCreditNo(),classId).getJSONObject("data");
        }catch (Exception e){
            e.printStackTrace();
        }
        if(businessData != null && businessData.size() > 0 ){
            try{
                JusticeItemsInfo justiceItemsInfo = JSONObject.parseObject(businessData.toJSONString(), JusticeItemsInfo.class);
                if(!ObjectUtils.isEmpty(justiceItemsInfo.getItems())){
                    Object items = businessData.get("items");
                    if (!ObjectUtils.isEmpty(items)){
                        justiceItemsInfo.setItems(JSON.toJSONString(items, SerializerFeature.WriteMapNullValue));
                    }
                    justiceItemsInfo.setId(businessInfo.getId()+classId);
                    justiceItemsInfo.setEmpId(businessInfo.getId());
                    justiceItemsInfo.setEmpCreditNo(businessInfo.getCreditNo());
                    justiceItemsInfo.setType(classId);
                    justiceItemsInfo.setSavetime(LocalDateTime.now());
                    justiceItemsInfoService.saveOrUpdate(justiceItemsInfo);
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }else{
            log.info("不匹配，入库失败,保存司法诉讼:"+businessInfo.getName()+getData(businessInfo.getName(),classId));
        }
    }

    //保存知识产权
    public void saveIntellectual(BusinessInfo businessInfo,Integer classId){
        JSONObject businessData = null;
        try {
            businessData = getData(businessInfo.getCreditNo(),classId).getJSONObject("data");
        }catch (Exception e){
            e.printStackTrace();
        }
        if(businessData!=null && businessData.size() > 0){
            try{
                Intellectual info = JSONObject.parseObject(businessData.toJSONString(), Intellectual.class);
                if(info!=null && businessInfo.getId() != null && businessInfo.getCreditNo() != null && info.getTotal() != 0 && info.getItems() != null){
                    info.setId(businessInfo.getId()+classId);
                    Object items = businessData.get("items");
                    if(!ObjectUtils.isEmpty(items)){
                        info.setItems(JSON.toJSONString(items, SerializerFeature.WriteMapNullValue));
                    }
                    info.setEmpId(businessInfo.getId());
                    info.setEmpCreditNo(businessInfo.getCreditNo());
                    info.setType(classId);
                    info.setSavetime(LocalDateTime.now());
                    boolean b = intellectualService.saveOrUpdate(info);
                    if(b){
                        log.info("保存知识产权成功");
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }else{
            log.info("不匹配，入库失败,保存知识产权,保存知识产权"+businessInfo.getName()+getData(businessInfo.getName(),classId));
        }
     }
    //保存企业价值
    public void saveValueInfo(BusinessInfo businessInfo,Integer classId){
        Map<String,String> map = new HashMap();
        JSONObject postParam = new JSONObject();
        postParam.put("entName",businessInfo.getName());
        postParam.put("uri","/strategy/getStrategy");
        String param = JSON.toJSONString(postParam);
        String sign = getSign(timeMillis, param, classId);
        JSONObject businessData = null;
        try {
            businessData = getRequestData(timeMillis, sign, param, classId).getJSONObject("data");
        }catch (Exception e){
            e.printStackTrace();
        }
        if(businessData != null){
            try{
                ValueInfo info = JSONObject.parseObject(businessData.toJSONString(), ValueInfo.class);
                if(info!=null && info.getCylzs() != null && info.getCylzs() != ""){
                    info.setEmpId(businessInfo.getId());
                    info.setEmpCreditNo(businessInfo.getCreditNo());
                    info.setSavetime(LocalDateTime.now());
                    boolean b = valueInfoService.saveOrUpdate(info);
                    if(b){
                        log.info("保存企业价值成功");
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }else{
            log.info("不匹配，入库失败,保存企业价值:"+businessInfo.getName()+getData(businessInfo.getName(),classId));
        }
    }
    //保存工商年报
    public void saveReportInfo(BusinessInfo businessInfo,Integer classId){
        JSONObject postParam2 = new JSONObject();
        postParam2.put("entname",businessInfo.getName());
        String param2 = JSON.toJSONString(postParam2);
        String sign2 = getSign(timeMillis, param2, 227);
        JSONArray businessData = null;
        try {
            String eid = getRequestData(timeMillis, sign2, param2, 227).getJSONObject("data").getString("eid");
            Map<String,String> map = new HashMap();
            JSONObject postParam = new JSONObject();
            postParam.put("eid",eid);
            postParam.put("pageNow",1);
            postParam.put("pageSize",100);
            String param = JSON.toJSONString(postParam);
            String sign = getSign(timeMillis, param, classId);
            businessData = getRequestData(timeMillis, sign, param, classId).getJSONObject("data").getJSONArray("data");
        }catch (Exception e){
            e.printStackTrace();
        }
        if(businessData!=null&&businessData.size()>0){
            try{
                String data = businessData.toJSONString();
                JSONObject json = new JSONObject();
                json.put("data",data);
                ReportInfo info = JSONObject.parseObject(json.toJSONString(), ReportInfo.class);
                info.setData(JSON.toJSONString(businessData, SerializerFeature.WriteMapNullValue));
                info.setEmpId(businessInfo.getId());
                info.setEmpCreditNo(businessInfo.getCreditNo());
                info.setSavetime(LocalDateTime.now());
                boolean b = reportInfoService.saveOrUpdate(info);
            }catch (Exception e){
                e.printStackTrace();
            }
        }else{
            log.info("不匹配，入库失败,保存工商年报:"+businessInfo.getName()+getData(businessInfo.getName(),classId));
        }
    }
    //http post方法
    public JSONObject httpSignMethod(String uri, MultiValueMap<String, Object> params){
        //设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        //用HttpEntity封装整个请求报文
        HttpEntity<MultiValueMap<String, Object>> files = new HttpEntity<>(params, headers);
        String template = restTemplate.postForObject(uri,files,String.class);
        JSONObject jsonObject = JSONObject.parseObject(template);
        return jsonObject;
    }
    //http方法
    public JSONObject httpPostMethod(String uri, JSONObject postData){
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity entity = new HttpEntity(JSON.toJSONString(postData), headers);
        ResponseEntity<JSONObject> response = restTemplate.exchange(uri, HttpMethod.POST, entity, JSONObject.class);
        return response.getBody();
    }
}
