package com.chinaweal.aiccs.aiccs.asyncTask;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chinaweal.aiccs.aiccs.abnormal.entity.EBaseinfo;
import com.chinaweal.aiccs.aiccs.abnormal.entity.TSAttachment;
import com.chinaweal.aiccs.aiccs.abnormal.entity.TSWrit;
import com.chinaweal.aiccs.aiccs.abnormal.service.EBaseinfoService;
import com.chinaweal.aiccs.aiccs.abnormal.service.IGzaiccodeService;
import com.chinaweal.aiccs.aiccs.abnormal.service.TSAttachmentService;
import com.chinaweal.aiccs.aiccs.abnormal.service.TSWritService;
import com.chinaweal.aiccs.aiccs.inspect.service.TSWorkNoService;
import com.chinaweal.aiccs.aiccs.revoke.entity.*;
import com.chinaweal.aiccs.aiccs.revoke.entity.dto.BizRevEntAttachDto;
import com.chinaweal.aiccs.aiccs.revoke.service.*;
import com.chinaweal.aiccs.aiccs.writs.entity.Tswrittemplate;
import com.chinaweal.aiccs.aiccs.writs.service.TswrittemplateService;
import com.chinaweal.aiccs.common.constant.BaseDataConstant;
import com.chinaweal.aiccs.common.constant.Constant;
import com.chinaweal.aiccs.common.util.ConstantsUtil;
import com.chinaweal.aiccs.common.util.WorkNoUtil;
import com.chinaweal.aiccs.common.util.filestorage.FileStorageService;
import com.chinaweal.aiccs.outside.service.TfRevokeServicelmpl;
import com.chinaweal.youfool.framework.springboot.util.SpringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.Future;

/**
 * 异步任务
 * @author Lee
 * @since 2022-02-23 11:04
 */
@Component
public class RevokeAsyncTask {

    @Autowired
    @Lazy
    private TSAttachmentService attachmentService;
    @Autowired
    private TswrittemplateService tswrittemplateService;
    @Autowired
    private TSWorkNoService tsWorkNoService;
    @Autowired
    private TSWritService tsWritService;
    @Autowired
    private CreateFileService createFileService;
    @Autowired
    private BizRevEntService bizRevEntService;
    @Autowired
    private EBaseinfoService eBaseinfoService;
    @Resource
    private CaseService caseService;
    @Resource
    private TfRevokeServicelmpl tfRevokeServicelmpl;
    @Resource
    private RevokelistService revokelistService;
    @Resource
    private IGzaiccodeService gzaiccodeService;
    @Resource
    private CancelRevokelistService cancelRevokelistService;

    public static final Logger LOGGER = LoggerFactory.getLogger(RevokeAsyncTask.class);

    @Async
    public void revHearingNoticeTask(String bizseq, String userOrgCode, LocalDateTime now, LocalDate nowDate) throws InterruptedException {
        try {
            LOGGER.info("》》》》》》》》》》》》业务号为{}听证告知书异步流程开始《《《《《《《《《", bizseq);
            TsCase caseDB = caseService.getByBizseq(bizseq);
            List<BizRevEntAttachDto> list = bizRevEntService.getBizEntAttachList(bizseq, "13");
            Long timeMilles = System.currentTimeMillis();
            // 生成听证告知书
            Map<String, Object> map = new HashMap<>();
            map.put("year", now.getYear());
            map.put("month", now.getMonthValue());
            map.put("day", now.getDayOfMonth());
            // 文书内容
            LambdaQueryWrapper<Tswrittemplate> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Tswrittemplate::getBizseq, bizseq)
                    .eq(Tswrittemplate::getIsTemplate, "0")
                    .eq(Tswrittemplate::getWritsType, WorkNoUtil.WORKNOTYPE_32);
            Tswrittemplate tswrittemplate = tswrittemplateService.getOne(wrapper);
            String content = tswrittemplate.getContent();
            String areaName = ConstantsUtil.getAreaName(userOrgCode);
            String decOrgName = gzaiccodeService.getNameByCode(userOrgCode);

            map.put("name", caseDB.getHandlerName() + "、" + caseDB.getAssistantName());
            map.put("noAttach", "noAttach");
            Integer total = list.size();
            Integer count = 0;  // 初始化 count 为 0
            int maxRetries = 50;  // 增加最大重试次数
            int retryCount = 0;   // 当前重试次数
            List<String> failedEntNames = new ArrayList<>();  // 记录失败的企业名
            Map<String, Integer> enterpriseRetryCounts = new HashMap<>();  // 记录每个企业的重试次数

            // 初始化每个企业的重试次数
            for (BizRevEntAttachDto dto : list) {
                enterpriseRetryCounts.put(dto.getPripid(), 0);
            }

            // 只要 count != total 且 retryCount < 20 就继续循环
            while (count < total && retryCount < maxRetries) {
                retryCount++;  // 每次循环增加重试计数
                LOGGER.info("第 {} 次尝试处理，已处理 {}/{}", retryCount, count, total);

                for (BizRevEntAttachDto bizRevEnt : list) {
                    if (count >= total) {
                        break;
                    }

                    // 检查是否已生成听证告知书
                    List<TSWrit> tsWritList = tsWritService.lambdaQuery()
                            .eq(TSWrit::getBizseq, bizseq)
                            .eq(TSWrit::getPripid, bizRevEnt.getPripid())
                            .eq(TSWrit::getWritstype, "32")
                            .list();
                    if (tsWritList.size() > 0) {
                        // 检查是否已计入count，避免重复计数
                        if (!enterpriseRetryCounts.containsKey(bizRevEnt.getPripid() + "_counted")) {
                            count++;
                            enterpriseRetryCounts.put(bizRevEnt.getPripid() + "_counted", 1);
                            LOGGER.info("业务号{}的企业{}已生成听证告知书，跳过处理", bizseq, bizRevEnt.getEntname());
                        }
                        continue;
                    }

                    // 检查单个企业重试次数，避免无限重试同一个失败企业
                    Integer entRetryCount = enterpriseRetryCounts.get(bizRevEnt.getPripid());
                    if (entRetryCount >= 10) {  // 单个企业最多重试10次
                        if (!failedEntNames.contains(bizRevEnt.getEntname())) {
                            failedEntNames.add(bizRevEnt.getEntname());
                            LOGGER.warn("业务号{}的企业{}已达最大重试次数，跳过处理", bizseq, bizRevEnt.getEntname());
                        }
                        continue;
                    }

                    try {

                        map.put("htmlContent", content);
                        BizRevEnt bizRevEntModel = new BizRevEnt();
                        bizRevEntModel.setRevlistid(bizRevEnt.getRevlistid());

                        // 生成文书号
                        TSWrit tsWritModel = new TSWrit();
                        tsWritModel.setWritsid(UUID.randomUUID().toString());
                        String workNoType = WorkNoUtil.WORKNOTYPE_32;
                        tsWritModel.setBizseq(bizseq);
                        tsWritModel.setAreaCode(userOrgCode);
                        tsWritModel.setWritsno(bizRevEnt.getPreHearNotWritsno());
                        tsWritModel.setWritstype(workNoType);
                        tsWritModel.setPripid(bizRevEnt.getPripid());
                        tsWritModel.setWritsname(WorkNoUtil.getWorkNoTypeName(workNoType));
                        tsWritModel.setCreatetime(now);
                        tsWritModel.setContent(tswrittemplateService.contentFormatter(content));

                        map.put("writsno", tsWritModel.getWritsno());
                        map.put("areaName", areaName);
                        map.put("entname", bizRevEnt.getEntname());
                        map.put("addr", decOrgName);
                        map.put("pripid", bizRevEnt.getPripid());

                        String fileName = bizRevEnt.getEntname() + "-听证告知书";
                        String path;
                        if (!userOrgCode.equals("440115") && !userOrgCode.equals("440110")) {
                            path = "static" + File.separator + "template" + File.separator + "hearingNotice.docx";
                        } else {
                            path = "static" + File.separator + "template" + File.separator + "hearingNoticeNS.docx";
                        }
                        String pdfPath = createFileService.createPdf(bizseq, fileName, "13", path, map);

                        // 验证PDF文件是否成功生成
                        if (pdfPath == null || pdfPath.trim().isEmpty()) {
                            throw new RuntimeException("PDF文件生成失败，返回路径为空");
                        }

                        // 更新文书、企业、附件信息
                        tsWritModel.setPath(pdfPath);
                        bizRevEntModel.setIshearingpublish("1");
                        bizRevEntModel.setHearingpublishdate(nowDate);

                        TSAttachment attachmentModel = new TSAttachment();
                        attachmentModel.setAttachmentid(bizRevEnt.getAttachmentid());
                        attachmentModel.setTemppath(pdfPath);

                        tsWritService.save(tsWritModel);
                        bizRevEntService.updateById(bizRevEntModel);
                        attachmentService.updateById(attachmentModel);

                        count++;  // 成功处理一个企业，count +1
                        enterpriseRetryCounts.put(bizRevEnt.getPripid() + "_counted", 1);  // 标记为已计数
                        LOGGER.info("业务号{}的企业{}听证告知书处理完成", bizseq, bizRevEnt.getEntname());
                    } catch (Exception e) {
                        // 增加该企业的重试计数
                        enterpriseRetryCounts.put(bizRevEnt.getPripid(), entRetryCount + 1);
                        LOGGER.error("业务号{}的企业{}处理听证告知书时出错（第{}次重试）：",
                                bizseq, bizRevEnt.getEntname(), entRetryCount + 1, e);
                    }
                }

                // 如果仍有未处理的企业，动态调整等待时间
                if (count < total) {
                    // 计算剩余未处理的企业数
                    int remaining = total - count;
                    // 根据重试次数和剩余数量动态调整等待时间
                    long waitTime = Math.min(10000, 3000 + (retryCount * 200) + (remaining * 500));  // 最长等待10秒
                    LOGGER.info("仍有 {} 家企业未处理，等待 {} 毫秒后重试", remaining, waitTime);
                    Thread.sleep(waitTime);
                }
            }

            // 最终状态检查
            if (count < total) {
                LOGGER.error("业务号{}处理完成，但仍有 {} 家企业未成功生成听证告知书", bizseq, total - count);
                if (!failedEntNames.isEmpty()) {
                    LOGGER.error("失败企业列表：{}", String.join(", ", failedEntNames));
                }
            } else {
                LOGGER.info("业务号{}所有企业听证告知书处理完成，共 {} 家", bizseq, count);
            }

            LOGGER.info("》》》》》》》》》》》》业务号为{}生成听证告知书附件总耗时:{}《《《《《《《《《",
                    bizseq, System.currentTimeMillis() - timeMilles);
        } catch (Exception e) {
            LOGGER.error("业务号{}异步生成听证告知书整体流程异常：", bizseq, e);
        }
    }
    @Async
    public Future<String> revPunishDecTask(String bizseq, String userOrgCode) throws InterruptedException {
        try {
            LOGGER.info("》》》》》》》》》》》》业务号为{}决定书异步流程开始《《《《《《《《《", bizseq);
            Long timeMilles = System.currentTimeMillis();
            List<BizRevEntAttachDto> list = bizRevEntService.getBizEntAttachList(bizseq, "14");

            // 生成决定书
            Map<String, Object> map = new HashMap<>();
            LocalDateTime now = LocalDateTime.now();
            LocalDate nowDate = LocalDate.now();
            map.put("year", now.getYear());
            map.put("month", now.getMonthValue());
            map.put("day", now.getDayOfMonth());

            // 文书内容
            LambdaQueryWrapper<Tswrittemplate> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Tswrittemplate::getBizseq, bizseq)
                    .eq(Tswrittemplate::getIsTemplate, "0")
                    .eq(Tswrittemplate::getWritsType, WorkNoUtil.WORKNOTYPE_33);
            Tswrittemplate tswrittemplate = tswrittemplateService.getOne(wrapper);
            String content = tswrittemplate.getContent();
            String areaName = ConstantsUtil.getAreaName(userOrgCode);
            map.put("noAttach", "noAttach");

            Integer total = list.size();
            Integer count = 0;  // 初始化已处理企业数
            int maxRetries = 50;  // 增加最大重试次数
            int retryCount = 0;   // 当前重试次数
            List<String> failedEntNames = new ArrayList<>();  // 记录失败的企业名
            Map<String, Integer> enterpriseRetryCounts = new HashMap<>();  // 记录每个企业的重试次数

            // 初始化每个企业的重试次数
            for (BizRevEntAttachDto dto : list) {
                enterpriseRetryCounts.put(dto.getPripid(), 0);
            }

            // 只要 count < total 且 retryCount < 20 就继续循环
            while (count < total && retryCount < maxRetries) {
                retryCount++;
                LOGGER.info("第 {} 次尝试处理，已处理 {}/{}", retryCount, count, total);

                for (BizRevEntAttachDto bizRevEnt : list) {
                    if (count >= total) {
                        break;
                    }
                    // 跳过已生成决定书的企业
                    if ("1".equals(bizRevEnt.getIsdecisionpublish())) {
                        // 检查是否已计入count，避免重复计数
                        if (!enterpriseRetryCounts.containsKey(bizRevEnt.getPripid() + "_counted")) {
                            count++;
                            enterpriseRetryCounts.put(bizRevEnt.getPripid() + "_counted", 1);
                            LOGGER.info("业务号{}的企业{}已生成决定书，跳过处理", bizseq, bizRevEnt.getEntname());
                        }
                        continue;
                    }

                    // 检查单个企业重试次数，避免无限重试同一个失败企业
                    Integer entRetryCount = enterpriseRetryCounts.get(bizRevEnt.getPripid());
                    if (entRetryCount >= 10) {  // 单个企业最多重试10次
                        if (!failedEntNames.contains(bizRevEnt.getEntname())) {
                            failedEntNames.add(bizRevEnt.getEntname());
                            LOGGER.warn("业务号{}的企业{}已达最大重试次数，跳过处理", bizseq, bizRevEnt.getEntname());
                        }
                        continue;
                    }

                    try {

                        BizRevEnt bizRevEntModel = new BizRevEnt();
                        bizRevEntModel.setRevlistid(bizRevEnt.getRevlistid());
                        map.put("htmlContent", content);

                        // 获取企业基本信息
                        EBaseinfo eBaseinfo = eBaseinfoService.getOne(
                                new LambdaQueryWrapper<EBaseinfo>()
                                        .eq(EBaseinfo::getPripid, bizRevEnt.getPripid())
                        );
                        if (eBaseinfo == null) {
                            throw new RuntimeException("未找到企业基本信息，pripid: " + bizRevEnt.getPripid());
                        }
                        map.put("entName", bizRevEnt.getEntname());
                        map.put("uniscid", bizRevEnt.getUniscid());
                        map.put("lerep", eBaseinfo.getLerep());
                        map.put("cerno", eBaseinfo.getCerno());
                        map.put("estdate", eBaseinfo.getEstdate());
                        map.put("entCerName", bizRevEnt.getEntname());
                        map.put("dom", eBaseinfo.getDom());
                        map.put("pripid", eBaseinfo.getPripid());
                        map.put("writsno", bizRevEnt.getPrePunDecWritsno());
                        map.put("areaName", areaName);

                        // 生成文书
                        TSWrit tsWritModel = new TSWrit();
                        tsWritModel.setWritsid(UUID.randomUUID().toString());
                        String workNoType = WorkNoUtil.WORKNOTYPE_33; // 批量吊销行政处罚决定书
                        tsWritModel.setBizseq(bizseq);
                        tsWritModel.setAreaCode(userOrgCode);
                        tsWritModel.setWritsno(bizRevEnt.getPrePunDecWritsno());
                        tsWritModel.setWritstype(workNoType);
                        tsWritModel.setPripid(bizRevEnt.getPripid());
                        tsWritModel.setWritsname(WorkNoUtil.getWorkNoTypeName(workNoType));
                        tsWritModel.setCreatetime(now);
                        tsWritModel.setContent(tswrittemplateService.revDecContentFormatter(content, map));

                        // 生成 PDF 文件
                        String fileName = bizRevEnt.getEntname() + "-处罚决定书";
                        String path = (!userOrgCode.equals("440115") && !userOrgCode.equals("440110"))
                                ? "static" + File.separator + "template" + File.separator + "punishDecision.docx"
                                : "static" + File.separator + "template" + File.separator + "punishDecisionNS.docx";
                        String pdfPath = createFileService.createPdf(bizseq, fileName, "14", path, map);

                        // 验证PDF文件是否成功生成
                        if (pdfPath == null || pdfPath.trim().isEmpty()) {
                            throw new RuntimeException("PDF文件生成失败，返回路径为空");
                        }

                        // 更新数据库记录
                        tsWritModel.setPath(pdfPath);
                        bizRevEntModel.setIsdecisionpublish("1");  // 标记为已生成决定书
                        bizRevEntModel.setDecisionpublishdate(nowDate);

                        TSAttachment attachmentModel = new TSAttachment();
                        attachmentModel.setAttachmentid(bizRevEnt.getAttachmentid());
                        attachmentModel.setTemppath(pdfPath);

                        Revokelist revokelistModel = new Revokelist();
                        revokelistModel.setRevlistid(bizRevEnt.getRevlistid());
                        revokelistModel.setWritsid(tsWritModel.getWritsid());

                        tsWritService.save(tsWritModel);
                        bizRevEntService.updateById(bizRevEntModel);
                        attachmentService.updateById(attachmentModel);
                        revokelistService.updateById(revokelistModel);

                        count++;  // 成功处理一个企业
                        LOGGER.info("业务号{}的企业{}处罚决定书处理完成", bizseq, bizRevEnt.getEntname());
                    } catch (Exception e) {
                        // 增加该企业的重试计数
                        enterpriseRetryCounts.put(bizRevEnt.getPripid(), entRetryCount + 1);
                        LOGGER.error("业务号{}的企业{}处理处罚决定书时出错（第{}次重试）：",
                                bizseq, bizRevEnt.getEntname(), entRetryCount + 1, e);
                    }
                }

                // 如果仍有未处理的企业，动态调整等待时间
                if (count < total) {
                    // 计算剩余未处理的企业数
                    int remaining = total - count;
                    // 根据重试次数和剩余数量动态调整等待时间
                    long waitTime = Math.min(10000, 3000 + (retryCount * 200) + (remaining * 500));  // 最长等待10秒
                    LOGGER.info("仍有 {} 家企业未处理，等待 {} 毫秒后重试", remaining, waitTime);
                    Thread.sleep(waitTime);
                }
            }

            // 最终状态检查
            if (count < total) {
                LOGGER.error("业务号{}处理完成，但仍有 {} 家企业未成功生成处罚决定书", bizseq, total - count);
                if (!failedEntNames.isEmpty()) {
                    LOGGER.error("失败企业列表：{}", String.join(", ", failedEntNames));
                }
                // 这里不抛出异常，让方法正常结束，避免影响后续的推送任务
            } else {
                LOGGER.info("业务号{}所有企业处罚决定书处理完成，共 {} 家", bizseq, count);
            }

            LOGGER.info("》》》》》》》》》》》》业务号为{}生成决定书附件总耗时:{}《《《《《《《《《",
                    bizseq, System.currentTimeMillis() - timeMilles);
        } catch (Exception e) {
            LOGGER.error("业务号{}异步生成决定书附件任务异常：", bizseq, e);
            // 不抛出InterruptedException，让方法继续执行推送任务
        }

        // 无论决定书生成是否成功，都执行推送任务
        try {
            revDataPushTFTask(bizseq);
        } catch (Exception e) {
            LOGGER.error("业务号{}执行推送任务失败：", bizseq, e);
        }

        return new AsyncResult<>("success");
    }

    /**
     * 根据bizseq重新推送
     * */
    public void tfTest(String bizseq) throws InterruptedException {
        revDataPushTFTask(bizseq);
    }

    /**
     * 根据统一码单独重新推送
     * */
    public void tfRevokeByUniscid(String uniscid) throws InterruptedException {
        try {
            LOGGER.info("》》》》》根据统一码单独重新推送:{}《《《《《", uniscid);
            String token = tfRevokeServicelmpl.queryTfToken();
            Revokelist revoke = revokelistService.getOne(new LambdaQueryWrapper<Revokelist>().eq(Revokelist::getUniscid,uniscid));

            LambdaQueryWrapper<TSWrit> tswritWrapper = new LambdaQueryWrapper<>();
            tswritWrapper.eq(TSWrit::getWritsid, revoke.getWritsid());
            TSWrit tswrit = tsWritService.getOne(tswritWrapper);

            //推送吊销主体数据
            Map<String, Object> param = new HashMap<>();
            Map<String, Object> params = new HashMap<>();
            param.put("pripid", revoke.getPripid());
            param.put("uniscid", revoke.getUniscid());
            param.put("entname", revoke.getEntname());
            param.put("revokerea", revoke.getRevokeRea());
            param.put("revokedate", revoke.getRevokedate().toLocalDate());
            param.put("apprdocno", tswrit.getWritsno());
            param.put("apprdept", revoke.getPunishOrgCn());
            param.put("affwriteno", "无");
            param.put("pubnewsname", "无");
            param.put("userid", revoke.getIntosponsorid());
            param.put("username", revoke.getIntosponsorname());

            params.put("aicode", "revocationAiccode");
            params.put("param", param);
            String result = tfRevokeServicelmpl.pushRevocation(token, params, revoke.getRevlistid());
            LOGGER.info("》》》》》根据统一码单独重新推送:{}，结果：{}《《《《《", uniscid, result);
        }catch (Exception e){
            e.printStackTrace();
            LOGGER.error("根据统一码单独重新推送市场主体吊销服务数据失败"+e);
            throw new InterruptedException("根据统一码单独重新推送推送市场主体吊销服务数据失败");
        }
    }

    private void revDataPushTFTask(String bizseq) throws InterruptedException {
        try {
            TsCase caseDB = caseService.getByBizseq(bizseq);
            List<Revokelist> revokelists = revokelistService.selectByCaseNo(caseDB.getCaseNo());
            LOGGER.info("》》》》》业务号为{}批次吊销数据开始推送,共{}家《《《《《", bizseq, revokelists.size());
            Long timeMilles = System.currentTimeMillis();
            String token = tfRevokeServicelmpl.queryTfToken();
            int successNum = 0;
            int errorNum = 0;
            for (Revokelist revokelist : revokelists) {
                if (revokelist.getReturnTime() != null) {
                    continue;
                }
                LambdaQueryWrapper<TSWrit> tswritWrapper = new LambdaQueryWrapper<>();
                tswritWrapper.eq(TSWrit::getWritsid, revokelist.getWritsid());
                TSWrit tswrit = tsWritService.getOne(tswritWrapper);

                //推送吊销主体数据
                Map<String, Object> param = new HashMap<>();
                Map<String, Object> params = new HashMap<>();
                param.put("pripid", revokelist.getPripid());
                param.put("uniscid", revokelist.getUniscid());
                param.put("entname", revokelist.getEntname());
                param.put("revokerea", revokelist.getRevokeRea());
                param.put("revokedate", revokelist.getRevokedate().toLocalDate());
                param.put("apprdocno", tswrit.getWritsno());
                param.put("apprdept", revokelist.getPunishOrgCn());
                param.put("affwriteno", "无");
                param.put("pubnewsname", "无");
                param.put("userid", revokelist.getIntosponsorid());
                param.put("username", revokelist.getIntosponsorname());

                params.put("aicode", "revocationAiccode");
                params.put("param", param);
                String result = tfRevokeServicelmpl.pushRevocation(token, params, revokelist.getRevlistid());
                if ("success".equals(result)) {
                    successNum++;
                }else {
                    errorNum++;
                }
            }
            LOGGER.info("》》》》》业务号为{}批次吊销数据推送完成,共{}家,成功数：{}，失败数：{}，耗时{}《《《《《",
                    bizseq,revokelists.size(),successNum,errorNum,System.currentTimeMillis()-timeMilles);
        }catch (Exception e){
            e.printStackTrace();
            LOGGER.error("推送市场主体吊销服务数据失败"+e);
            throw new InterruptedException("推送市场主体吊销服务数据失败");
        }

    }

    /**
     * 根据统一码推送撤销吊销数据
     */
    public String tfCancelRevocation(CancelRevokelist cancelRevoke) {
        if(cancelRevoke != null){
            try {
                String uniscid = cancelRevoke.getUniscid();
                LOGGER.info("》》》》》根据统一码推送撤销吊销数据:{}《《《《《", uniscid);
                //获取token
                String token = tfRevokeServicelmpl.queryTfToken("撤销吊销");
                if("error".equals(token)){  //当token返回error时
                    //返回异常代码
                    return token;
                } else {
                    //推送撤销吊销主体数据
                    Map<String, Object> param = new HashMap<>();
                    Map<String, Object> params = new HashMap<>();
                    param.put("pripid", cancelRevoke.getPripid());
                    param.put("uniscid", uniscid);
                    param.put("entname", cancelRevoke.getEntname());
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    String cancelrevokedate = sdf.format(new Date());
                    cancelRevoke.setCancelrevokedate(cancelrevokedate);
                    param.put("cancelrevokedate", cancelrevokedate);
                    param.put("cancelrevokeotherrea", cancelRevoke.getCancelapprdocno());
                    param.put("cancelapprdocno", cancelRevoke.getCancelapprdocno());
                    param.put("cancelapprdept", cancelRevoke.getCancelapprdept());
                    param.put("username", "信用监管系统");

                    params.put("aicode", BaseDataConstant.TFCANCELTOKEN_AICODE);
                    params.put("param", param);
                    String result = tfRevokeServicelmpl.cancelRevocation(token, params, cancelRevoke);
                    LOGGER.info("》》》》》根据统一码单独重新推送:{}，结果：{}《《《《《", uniscid, result);
                    return result;
                }
            }catch (Exception e){
                e.printStackTrace();
                LOGGER.error("根据统一码单独重新推送市场主体吊销服务数据失败"+e);
                return "error";
            }
        }
        return "success";
    }

    /**
     * 根据统一码推送撤销设立数据
     */
    public String tfRevocationReg(CancelRegisterList cancelRegister) {
        if(cancelRegister != null){
            try {
                String uniscid = cancelRegister.getUniscid();
                LOGGER.info("》》》》》根据统一码推送撤销设立数据token获取:{}《《《《《", uniscid);
                //获取token
                String token = tfRevokeServicelmpl.queryTfToken("撤销设立");
                if("error".equals(token)){  //当token返回error时
                    LOGGER.info("》》》》》根据统一码推送撤销设立数据token获取失败:{}《《《《《", uniscid);
                    //返回异常代码
                    return token;
                } else {
                    //推送撤销设立主体数据
                    Map<String, Object> param = new HashMap<>();
                    Map<String, Object> params = new HashMap<>();
                    param.put("pripid", cancelRegister.getPripid());
                    param.put("uniscid", uniscid);
                    param.put("entname", cancelRegister.getEntname());
                    param.put("canceldocno", cancelRegister.getCanceldocno());
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    String canceldate = sdf.format(new Date());
                    cancelRegister.setCanceldate(canceldate);
                    param.put("canceldate", canceldate);
                    param.put("cancelregtype", cancelRegister.getCancelregtype());
                    param.put("cancelrea", cancelRegister.getCancelrea());
                    param.put("autoaddresslock", cancelRegister.getAutoaddresslock());
                    param.put("username", "信用监管系统");
                    params.put("aicode", BaseDataConstant.TFCANCELREGTOKEN_AICODE);
                    params.put("param", param);
                    LOGGER.info("》》》》》根据统一码推送撤销设立:{},token:{}《《《《《", uniscid,token);
                    String result = tfRevokeServicelmpl.revocationReg(token, params, cancelRegister);
                    LOGGER.info("》》》》》根据统一码推送撤销设立:{}，结果：{}《《《《《", uniscid, result);
                    return result;
                }
            }catch (Exception e){
                e.printStackTrace();
                LOGGER.error("根据统一码推送撤销设立服务数据失败"+e);
                return "error";
            }
        }
        return "error";
    }

    /**
     * 推送撤销撤销设立数据
     */
    public String tfCancelRevocationReg(CancelRevocationRegList cancelRevocationRegList) {
        if(cancelRevocationRegList != null){
            try {
                String uniscid = cancelRevocationRegList.getUniscid();
                LOGGER.info("》》》》》推送撤销撤销设立数据token获取:{}《《《《《", uniscid);
                //获取token
                String token = tfRevokeServicelmpl.queryTfToken("撤销撤销设立");
                if("error".equals(token)){  //当token返回error时
                    LOGGER.info("》》》》》推送撤销撤销设立数据token获取失败:{}《《《《《", uniscid);
                    //返回异常代码
                    return token;
                } else {
                    //推送撤销撤销设立主体数据
                    Map<String, Object> param = new HashMap<>();
                    Map<String, Object> params = new HashMap<>();
                    param.put("pripid", cancelRevocationRegList.getPripid());
                    param.put("uniscid", uniscid);
                    param.put("entname", cancelRevocationRegList.getEntname());
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    String canceldate = sdf.format(new Date());
                    cancelRevocationRegList.setCanceldate(canceldate);
                    param.put("canceldate", canceldate);
                    param.put("cancelrea", cancelRevocationRegList.getCancelrea());
                    param.put("canceldocno", cancelRevocationRegList.getCanceldocno());
                    param.put("username", "信用监管系统");
                    params.put("aicode", BaseDataConstant.TFCANCELREVOCATIONREGTOKEN_AICODE);
                    params.put("param", param);
                    LOGGER.info("》》》》》推送撤销撤销设立:{},token:{}《《《《《", uniscid,token);
                    String result = tfRevokeServicelmpl.cancelRevocationReg(token, params, cancelRevocationRegList);
                    LOGGER.info("》》》》》推送撤销撤销设立:{}，结果：{}《《《《《", uniscid, result);
                    return result;
                }
            }catch (Exception e){
                e.printStackTrace();
                LOGGER.error("推送撤销撤销设立服务数据失败"+e);
                return "error";
            }
        }
        return "error";
    }
}
