package com.chinaweal.aiccs.aiccs.test;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chinaweal.aiccs.aiccs.abnormal.entity.*;
import com.chinaweal.aiccs.aiccs.abnormal.service.*;
import com.chinaweal.aiccs.aiccs.asyncTask.RevokeAsyncTask;
import com.chinaweal.aiccs.aiccs.auditing.entity.TSOpinion;
import com.chinaweal.aiccs.aiccs.auditing.service.TSOpinionService;
import com.chinaweal.aiccs.aiccs.business.entity.TSTaskList;
import com.chinaweal.aiccs.aiccs.business.service.TSTaskListService;
import com.chinaweal.aiccs.aiccs.business.service.TSTwfProcessNodeService;
import com.chinaweal.aiccs.aiccs.business.service.TSTwfTaskService;
import com.chinaweal.aiccs.aiccs.inspect.service.TSWorkNoService;
import com.chinaweal.aiccs.aiccs.market.ai.AreaSliceClaimAI;
import com.chinaweal.aiccs.aiccs.market.entity.AreaSlice;
import com.chinaweal.aiccs.aiccs.market.entity.BizOwnerAssign;
import com.chinaweal.aiccs.aiccs.market.entity.dto.AssignEntity;
import com.chinaweal.aiccs.aiccs.market.entity.dto.SliceAssignLogDto;
import com.chinaweal.aiccs.aiccs.market.service.AreaSliceService;
import com.chinaweal.aiccs.aiccs.market.service.BizOwnerAssignService;
import com.chinaweal.aiccs.aiccs.punishment.entity.EntLock;
import com.chinaweal.aiccs.aiccs.punishment.job.Task;
import com.chinaweal.aiccs.aiccs.revoke.entity.*;
import com.chinaweal.aiccs.door.entity.TUserportal;
import com.chinaweal.aiccs.aiccs.punishment.service.EntlockService;
import com.chinaweal.aiccs.aiccs.punishment.service.impl.TsbizPunishUnlockServiceImpl;
import com.chinaweal.aiccs.aiccs.punishment.service.impl.TsbizpunishlockServiceImpl;
import com.chinaweal.aiccs.aiccs.revoke.entity.dto.RevokeProcessDto;
import com.chinaweal.aiccs.aiccs.revoke.service.*;
import com.chinaweal.aiccs.aiccs.revoke.service.impl.CreateFileServiceImpl;
import com.chinaweal.aiccs.aiccs.statistic.entity.StatisticsResult;
import com.chinaweal.aiccs.aiccs.statistic.service.IStatisticsResultService;
import com.chinaweal.aiccs.aiccs.system.service.TRBaseCodeService;
import com.chinaweal.aiccs.aiccs.writs.entity.Tswrittemplate;
import com.chinaweal.aiccs.aiccs.writs.service.TswrittemplateService;
import com.chinaweal.aiccs.common.constant.Constant;
import com.chinaweal.aiccs.common.enums.StatisticsModuleEnum;
import com.chinaweal.aiccs.common.util.*;
import com.chinaweal.aiccs.common.util.filestorage.FileStorageService;
import com.chinaweal.aiccs.config.CommonConfig;
import com.chinaweal.aiccs.crgs.movein.job.DownLoadTask;
import com.chinaweal.aiccs.crgs.movein.job.MoveinSchedule;
import com.chinaweal.aiccs.door.service.ITUserportalService;
import com.chinaweal.aiccs.org.service.AicorgService;
import com.chinaweal.aiccs.org.service.TUsersService;
import com.chinaweal.aiccs.outside.api.LangChaoDoorApi;
import com.chinaweal.aiccs.outside.dto.LangChaoTokenDto;
import com.chinaweal.aiccs.outside.service.TfRevokeServicelmpl;
import com.chinaweal.aiccs.redis.RedisService;
import com.chinaweal.aiccs.schedule.EntAddressAnalysisSchedule;
import com.chinaweal.aicorg.model.AICUser;
import com.chinaweal.aicorg.services.OrgUM;
import com.chinaweal.youfool.framework.springboot.exception.custom.BusinessException;
import com.chinaweal.youfool.framework.springboot.log.service.IRestLogService;
import com.chinaweal.youfool.framework.springboot.rest.RestResult;
import com.chinaweal.youfool.framework.springboot.rest.ResultCode;
import com.chinaweal.youfool.framework.springboot.util.AssertUtils;
import com.deepoove.poi.XWPFTemplate;
import com.dtflys.forest.http.ForestResponse;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

import static com.chinaweal.aiccs.aiccs.asyncTask.RevokeAsyncTask.LOGGER;
import static com.chinaweal.aiccs.common.base.controller.BaseController.getLoginUser;

/**
 * @author Lee
 * @since 2021-09-13 14:12
 */
@Slf4j
@RestController
@RequestMapping("/test")
public class TestController {

    @Autowired
    private AreaSliceClaimAI areaSliceClaimAI;
    @Autowired
    private CaseReportService caseReportService;
    @Autowired
    private CreateFileService createFileService;
    @Autowired
    private TSTaskListService tsTaskListService;
    @Autowired
    private TSAbnListService tsAbnListService;
    @Autowired
    private OrgUM orgUM;
    @Autowired
    private AicorgService aicorgService;
    @Autowired
    private TswrittemplateService tswrittemplateService;
    @Autowired
    private TRBaseCodeService baseCodeService;
    @Autowired
    private TSWorkNoService workNoService;
    @Autowired
    private TSWritService tsWritService;
    @Autowired
    private TSOpinionService tsOpinionService;
    @Autowired
    private CreatePdfService createPdfService;
    @Autowired
    private TSBizRemListService tsBizRemListService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private TsbizpunishlockServiceImpl tsbizpunishlockService;
    @Autowired
    private EntlockService entlockService;
    @Autowired
    private TsbizPunishUnlockServiceImpl tsbizPunishUnlockService;
    @Resource
    private IRestLogService restLogService;
    @Resource
    private TSTwfProcessNodeService tsTwfProcessNodeService;
    @Autowired
    private UuidUtil uuidUtil;
    @Autowired
    private TSTwfTaskService tsTwfTaskService;

    @Autowired
    private DownLoadTask downLoadTask;
    @Autowired
    private EBaseinfoService eBaseinfoService;
    //    @Autowired
//    private AbnClueService abnClueService;
    @Autowired
    private TsbizrevlistService tsbizrevlistService;

    @Autowired
    private TUsersService usersService;

    //    @Autowired
//    private EBaseinfoMapper eBaseinfoMapper;
    @Autowired
    private Task task;
    @Autowired
    private BizOwnerAssignService bizOwnerAssignService;
    @Autowired
    private AreaSliceService areaSliceService;
    @Autowired
    MoveinSchedule moveinSchedule;
    @Resource
    private FileStorageService fileStorageService;
    @Autowired
    private TSAttachmentService attachmentService;
    @Autowired
    private RevokeAsyncTask revokeAsyncTask;
    @Autowired
    private CaseService caseService;
    @Autowired
    private IGzaiccodeService gzaiccodeService;
    @Resource
    private TfRevokeServicelmpl tfRevokeServicelmpl;
    @Resource
    private BizRevEntService bizRevEntService;
    @Autowired
    private AbnStatisticsService abnStatisticsService;
    @Autowired
    private IStatisticsResultService statisticsResultService;
    @Autowired
    private TSAbnListService abnListService;
    @Autowired
    private EntAddressAnalysisSchedule entAddressAnalysisSchedule;
    @Autowired
    private TSTaskListService taskListService;
    @Resource
    private LangChaoDoorApi langChaoDoorApi;

    @Resource
    private ITUserportalService itUserportalService;

    @Autowired
    private TsbizrevcancelService tsbizrevcancelService;


    @GetMapping("testDocx4jToPdf")
    public RestResult<?> testDocx4jToPdf() throws InterruptedException {

//        CountDownLatch countDownLatch = ThreadUtil.newCountDownLatch(50);
        for (int i = 1; i <= 100; i++) {
//            ThreadUtil.execute(() -> {
//                createPdfService.initPdfUtil();
//                countDownLatch.countDown();
//            });

            createPdfService.initPdfUtil();
        }
//        countDownLatch.await();

        return RestResult.ok();
    }

    @ApiOperation("天河区四万认领处理")
    @PostMapping("claimForTianHe")
    public RestResult<?> claimForTianHe() {
        String lastSql = "limit 10000";
        List<EBaseinfo> records = eBaseinfoService.lambdaQuery()
                .eq(EBaseinfo::getSuporg, "440126")
                .eq(EBaseinfo::getRegstate, "1")
                .and(i -> i.ne(EBaseinfo::getAssignId, "fty1").or().isNull(EBaseinfo::getAssignId))
                .orderByAsc(EBaseinfo::getPripid).last(lastSql).list();
        while (CollectionUtils.isNotEmpty(records)) {
            for (EBaseinfo each : records) {
                eBaseinfoService.clearRegulatory(each.getPripid());
                List<SliceAssignLogDto> claimLogList = bizOwnerAssignService.listBySliceInfo(null, each.getPripid());
                if (CollectionUtils.isNotEmpty(claimLogList)) {
                    for (SliceAssignLogDto atom : claimLogList) {
                        if (atom.getRemDate() == null) {
                            bizOwnerAssignService.updateById(new BizOwnerAssign()
                                    .setAssignId(atom.getAssignId())
                                    .setRemDate(LocalDateTime.now())
                                    .setRemReason("番禺公共片区调整到相应片区")
                                    .setRemType("1")
                                    .setRemOperatorName("fty")
                                    .setUpdateTime(LocalDateTime.now()));
                        }
                    }
                }

                AssignEntity entity = new AssignEntity()
                        .setAddress(StringUtils.isNotBlank(each.getDom()) ? each.getDom() : each.getAddress())
                        .setPripid(each.getPripid())
                        .setEntName(each.getEntname())
                        .setEntType(each.getEnttype())
                        .setLerep(each.getLerep())
                        .setRegNo(each.getRegno())
                        .setRegOrg(each.getRegorg())
                        .setRegulatory(each.getSuporg())
                        .setUniscid(each.getUniscid());

                try {
                    areaSliceClaimAI.claimInScope(entity, null);
                } catch (Exception e) {
                    log.error("系统出错, pripid: {}。原因：", each.getPripid(), e);
                }
            }
            records = eBaseinfoService.lambdaQuery()
                    .eq(EBaseinfo::getSuporg, "440126")
                    .eq(EBaseinfo::getRegstate, "1")
                    .and(i -> i.ne(EBaseinfo::getAssignId, "fty1").or().isNull(EBaseinfo::getAssignId))
                    .gt(EBaseinfo::getPripid, records.get(records.size() - 1).getPripid())
                    .orderByAsc(EBaseinfo::getPripid).last(lastSql).list();
        }
        return RestResult.ok();
    }

    @ApiOperation("按地址重新认领片区")
    @PostMapping("claimByAddress")
    public RestResult<?> claimByAddress(String address, String sliceId, String orgNumber) {
        //查出问题数据
        String lastSql = "limit 10000";
        List<EBaseinfo> records = eBaseinfoService.lambdaQuery()
                .ne(EBaseinfo::getSuporg, orgNumber)
                .eq(EBaseinfo::getRegstate, "1")
                .likeRight(EBaseinfo::getDom, address)
                .orderByAsc(EBaseinfo::getPripid).last(lastSql).list();

        AreaSlice slice = areaSliceService.getById(sliceId);
        while (CollectionUtils.isNotEmpty(records)) {
            for (EBaseinfo each : records) {
                areaSliceClaimAI.claimByAddress(each, slice, orgNumber, "fty");
            }
            records = eBaseinfoService.lambdaQuery()
                    .ne(EBaseinfo::getSuporg, orgNumber)
                    .eq(EBaseinfo::getRegstate, "1")
                    .likeRight(EBaseinfo::getDom, address)
                    .gt(EBaseinfo::getPripid, records.get(records.size() - 1).getPripid())
                    .orderByAsc(EBaseinfo::getPripid).last(lastSql).list();
        }


        //areaSliceClaimAI.claimByAddress(address, sliceId, orgNumber);
        return RestResult.ok();
    }

    @ApiOperation("经营异常统计各区")
    @PostMapping("staticAllRegionTsabnlist")
    public RestResult<?> staticAllRegionTsabnlist() {
        //展示全市各区的经营异常主体情况
        List<Map<String, String>> abnRegionList = statisticsResultService.staticAllRegionTsabnlist();
        List<Map<String, String>> list = new ArrayList<>();
        int n = 0;
        int k = 0;
        for (int i = 0; i < abnRegionList.size(); i++) {
            Map<String, String> m = abnRegionList.get(i);
            if (m.containsKey("region") && m.get("region") != null) {
                if (m.get("region").equals("440110")) {
                    n = i;
                    continue;
                }
                if (m.get("region").equals("440115")) {
                    k = i;
                    continue;
                }
                Map<String, String> map = m;
                map.put("region", Constant.NM_REGION_CODE.get(m.get("region")));
                list.add(map);
            }
        }
        Map mapNS = new HashMap<>();
        mapNS.put("region", Constant.NM_REGION_CODE.get("440110"));
        mapNS.put("num", Integer.parseInt(abnRegionList.get(n).get("num")) + Integer.parseInt(abnRegionList.get(k).get("num")));
        list.add(0, mapNS);

        StatisticsResult sResult = statisticsResultService.getOne(new QueryWrapper<StatisticsResult>()
                .lambda().eq(StatisticsResult::getModuleTag, "all_region_abn"));
        sResult.setDataJson(JSON.toJSONString(list));
        statisticsResultService.updateById(sResult);

        return RestResult.ok(list);
    }

    @ApiOperation("按年统计全市")
    @PostMapping("staticAbnByYear")
    public RestResult<?> staticAbnByYear() {
        //<!--    按年统计全市-->
        List<Map<String, Integer>> abnYearList = statisticsResultService.staticAbnByYear();
        StatisticsResult yResult = statisticsResultService.getOne(new QueryWrapper<StatisticsResult>()
                .lambda().eq(StatisticsResult::getModuleTag, "year_abn"));
        yResult.setDataJson(JSON.toJSONString(abnYearList));
        statisticsResultService.updateById(yResult);

        return RestResult.ok(abnYearList);
    }

    @ApiOperation("按月统计全市")
    @PostMapping("staticAbnByMonth")
    public RestResult<?> staticAbnByMonth() {
        //<!--    按月统计全市-->
        List<Map<String, Integer>> abnMonthList = statisticsResultService.staticAbnByMonth();
        StatisticsResult mResult = statisticsResultService.getOne(new QueryWrapper<StatisticsResult>()
                .lambda().eq(StatisticsResult::getModuleTag, "month_abn"));
        mResult.setDataJson(JSON.toJSONString(abnMonthList));
        statisticsResultService.updateById(mResult);

        return RestResult.ok(abnMonthList);
    }

    @ApiOperation("按周统计全市")
    @PostMapping("staticAbnByWeek")
    public RestResult<?> staticAbnByWeek() {
        //<!--    按周统计全市-->
        List<Map<String, Integer>> abnWeekList = statisticsResultService.staticAbnByWeek();
        List<Integer> r = new ArrayList<>(10);
        Calendar calendar = Calendar.getInstance();
        calendar.setFirstDayOfWeek(Calendar.MONDAY);//设置星期一为一周开始的第一天
        calendar.setTimeInMillis(System.currentTimeMillis());//获得当前的时间戳
        int weekYear = calendar.get(Calendar.YEAR);//获得当前的年
        int weekOfYear = calendar.get(Calendar.WEEK_OF_YEAR) - 1;//获得当前日期属于今年的第几周
        int w = weekYear * 100 + weekOfYear;
        int dw = 0;
        for (Map map : abnWeekList) {
            int week = Integer.parseInt(map.get("weeks").toString());
            int value = Integer.parseInt(map.get("num").toString());
            while (dw < 10) {
                if (w - week == 0) {
                    r.add(value);
                    w--;
                    dw++;
                    break;
                } else {
                    r.add(0);
                }
                w--;
                dw++;
            }
            if (dw == 10) break;
        }
        StatisticsResult wResult = statisticsResultService.getOne(new QueryWrapper<StatisticsResult>()
                .lambda().eq(StatisticsResult::getModuleTag, "week_abn"));
        wResult.setDataJson(JSON.toJSONString(r));
        statisticsResultService.updateById(wResult);
        return RestResult.ok(abnWeekList);
    }

    @ApiOperation("经营异常列入统计全市")
    @PostMapping("staticAbnByIn")
    public RestResult<?> staticAbnByIn() {
        //<!--    经营异常列入统计全市-->
        List<Map<String, String>> abnInList = statisticsResultService.staticAbnByIn();

        QueryWrapper<TSAbnList> abnWrappper = new QueryWrapper<>();
        abnWrappper.lambda().isNotNull(TSAbnList::getSpecause);
        abnWrappper.lambda().isNotNull(TSAbnList::getEnttype);
        abnWrappper.select("DISTINCT PRIPID");
        int sum = abnListService.count(abnWrappper);

        abnWrappper.clear();
        abnWrappper.lambda().isNotNull(TSAbnList::getSpecause);
        abnWrappper.lambda().eq(TSAbnList::getEnttype, "9910");
        abnWrappper.select("DISTINCT PRIPID");
        int individualSum = abnListService.count(abnWrappper);

        abnWrappper.clear();
        abnWrappper.lambda().isNotNull(TSAbnList::getSpecause);
        abnWrappper.lambda().in(TSAbnList::getEnttype, "9100", "9200");
        abnWrappper.select("DISTINCT PRIPID");
        int farmerSum = abnListService.count(abnWrappper);

        abnWrappper.clear();
        abnWrappper.lambda().isNotNull(TSAbnList::getSpecause);
        abnWrappper.lambda().notIn(TSAbnList::getEnttype, "9100", "9200", "9910");
        abnWrappper.select("DISTINCT PRIPID");
        int companySum = abnListService.count(abnWrappper);

        Map<String, String> sumMap = new HashMap<>();
        sumMap.put("sum", sum + "");
        sumMap.put("individualSum", individualSum + "");
        sumMap.put("farmerSum", farmerSum + "");
        sumMap.put("companySum", companySum + "");

        abnInList.add(0, sumMap);

        StatisticsResult inResult = statisticsResultService.getOne(new QueryWrapper<StatisticsResult>()
                .lambda().eq(StatisticsResult::getModuleTag, "in_abn"));
        inResult.setDataJson(JSON.toJSONString(abnInList));
        statisticsResultService.updateById(inResult);
        return RestResult.ok(abnInList);
    }

    @ApiOperation("经营异常移出统计全市")
    @PostMapping("staticAbnByOut")
    public RestResult<?> staticAbnByOut() {
        //<!--    经营异常移出统计全市-->
        List<Map<String, Integer>> abnOutList = statisticsResultService.staticAbnByOut();
        StatisticsResult outResult = statisticsResultService.getOne(new QueryWrapper<StatisticsResult>()
                .lambda().eq(StatisticsResult::getModuleTag, "out_abn"));
        outResult.setDataJson(JSON.toJSONString(abnOutList));
        statisticsResultService.updateById(outResult);

        return RestResult.ok(abnOutList);
    }

    @ApiOperation("全市各区的严重违法主体情况")
    @PostMapping("staticAllRegionTsserill")
    public RestResult<?> staticAllRegionTsserill() {
        //全市各区的严重违法主体情况
        List<Map<String, String>> illRegionList = statisticsResultService.staticAllRegionTsserill();
        List<Map<String, String>> list = new ArrayList<>();
        int n = 0;
        int k = 0;
        for (int i = 0; i < illRegionList.size(); i++) {
            Map<String, String> m = illRegionList.get(i);
            if (m.containsKey("region") && m.get("region") != null) {
                if (m.get("region").equals("440110")) {
                    n = i;
                    continue;
                }
                if (m.get("region").equals("440115")) {
                    k = i;
                    continue;
                }
                Map<String, String> map = m;
                map.put("region", Constant.NM_REGION_CODE.get(m.get("region")));
                list.add(map);
            }
        }
        Map mapNS = new HashMap<>();
        mapNS.put("region", Constant.NM_REGION_CODE.get("440110"));
        mapNS.put("num", Integer.parseInt(illRegionList.get(n).get("num")) + Integer.parseInt(illRegionList.get(k).get("num")));
        list.add(0, mapNS);

        StatisticsResult regionResult = statisticsResultService.getOne(new QueryWrapper<StatisticsResult>()
                .lambda().eq(StatisticsResult::getModuleTag, "all_region_ill"));
        regionResult.setDataJson(JSON.toJSONString(list));
        statisticsResultService.updateById(regionResult);

        return RestResult.ok(list);
    }

    @ApiOperation("按年统计严重违法主体情况")
    @PostMapping("staticTsserillByYear")
    public RestResult<?> staticTsserillByYear() {
        //按年统计严重违法主体情况
        List<Map<String, Integer>> illYearList = statisticsResultService.staticTsserillByYear();
        StatisticsResult yResult = statisticsResultService.getOne(new QueryWrapper<StatisticsResult>()
                .lambda().eq(StatisticsResult::getModuleTag, "year_ill"));
        yResult.setDataJson(JSON.toJSONString(illYearList));
        statisticsResultService.updateById(yResult);

        return RestResult.ok(illYearList);
    }

//    @ApiOperation("按列入原因统计严重违法主体情况")
//    @PostMapping("staticTsserillByIn")
//    public RestResult<?> staticTsserillByIn() {
//        //按列入原因统计严重违法主体情况
//        List<Map<String, Integer>> illInList = statisticsResultService.staticTsserillByIn();
//        StatisticsResult inResult = statisticsResultService.getOne(new QueryWrapper<StatisticsResult>()
//                .lambda().eq(StatisticsResult::getModuleTag, "in_ill"));
//        inResult.setDataJson(JSON.toJSONString(illInList));
//        statisticsResultService.updateById(inResult);
//
//        return RestResult.ok(illInList);
//    }
//
//    @ApiOperation("按移出原因统计严重违法主体情况")
//    @PostMapping("staticTsserillByOutRe")
//    public RestResult<?> staticTsserillByOutRe() {
//        //按移出原因和地区统计严重违法主体情况
//        List<Map<String, String>> illOutByRegorgList = statisticsResultService.staticTsserillByOutRe();
//        List<Map<String, Object>> result = new ArrayList<>();
//        for (String regorg : Constant.All_REGORG_GZ) {
//            Map<String, Object> atomMap = new HashMap<>();
//            List<Map<String, String>> atomList = new ArrayList<>();
//            for (Map<String, String> m : illOutByRegorgList) {
//                if (m.containsKey("regorg") && m.get("regorg").equals(regorg)) {
//                    if (m.containsKey("REMEXCPRES")) {
//                        Map<String, String> atom = new HashMap<>();
//                        atom.put("REMEXCPRES", m.get("REMEXCPRES"));
//                        atom.put("num", m.get("num"));
//                        atomList.add(atom);
//                    }
//                }
//            }
//            if (atomList.size() > 0) {
//                atomMap.put("name", Constant.NM_REGION_CODE.get(regorg));
//                atomMap.put("detail", atomList);
//                result.add(atomMap);
//            }
//        }
//
//        Map<String, Object> atomMap = new HashMap<>();
//        List<Map<String, String>> atomList = new ArrayList<>();
//        for (Map<String, String> m : illOutByRegorgList) {
//            if (m.containsKey("regorg") && m.get("regorg").equals("全市")) {
//                if (m.containsKey("REMEXCPRES")) {
//                    Map<String, String> atom = new HashMap<>();
//                    atom.put("REMEXCPRES", m.get("REMEXCPRES"));
//                    atom.put("num", m.get("num"));
//                    atomList.add(atom);
//                }
//            }
//            if (atomList.size() > 0) {
//                atomMap.put("name", "全市");
//                atomMap.put("detail", atomList);
//                result.add(0, atomMap);
//            }
//        }
//
//        StatisticsResult outRegionResult = statisticsResultService.getOne(new QueryWrapper<StatisticsResult>()
//                .lambda().eq(StatisticsResult::getModuleTag, "out_region_ill"));
//        outRegionResult.setDataJson(JSON.toJSONString(result));
//        statisticsResultService.updateById(outRegionResult);
//
//        return RestResult.ok(illOutByRegorgList);
//    }

    @ApiOperation("协同监管结果分析")
    @PostMapping("staticTsusualinspectType")
    public RestResult<?> staticTsusualinspectType() {
        //<!--    按年统计全市-->
        List<Map<String, Integer>> usuaTypeList = statisticsResultService.staticTsusualinspectType();
        StatisticsResult yResult = statisticsResultService.getOne(new QueryWrapper<StatisticsResult>()
                .lambda().eq(StatisticsResult::getModuleTag, "result_usua"));
        yResult.setDataJson(JSON.toJSONString(usuaTypeList));
        statisticsResultService.updateById(yResult);
        return RestResult.ok(usuaTypeList);
    }


    @ApiOperation("协同监管主体分布")
    @PostMapping("staticTsusualinspectRegion")
    public RestResult<?> staticTsusualinspectRegion() {
        //<!--    按年统计全市-->
        List<Map<String, String>> usuaRegionList = statisticsResultService.staticTsusualinspectRegion();
        for (Map<String, String> m : usuaRegionList) {
            if (m.containsKey("region") && m.get("region") != null) {
                m.put("region", Constant.NM_REGION_CODE.get(m.get("region")));
            }
        }
        StatisticsResult yResult = statisticsResultService.getOne(new QueryWrapper<StatisticsResult>()
                .lambda().eq(StatisticsResult::getModuleTag, "all_region_usua"));
        yResult.setDataJson(JSON.toJSONString(usuaRegionList));
        statisticsResultService.updateById(yResult);
        return RestResult.ok(usuaRegionList);
    }

    @ApiOperation("撤销登记涉嫌登记类型分析")
    @PostMapping("staticFraudType")
    public RestResult<?> staticFraudType() {
        //<!--    按年统计全市-->
        List<Map<String, Integer>> fraudTypeList = statisticsResultService.staticFraudType();

        StatisticsResult yResult = statisticsResultService.getOne(new QueryWrapper<StatisticsResult>()
                .lambda().eq(StatisticsResult::getModuleTag, "type_fraud"));
        yResult.setDataJson(JSON.toJSONString(fraudTypeList));
        statisticsResultService.updateById(yResult);
        return RestResult.ok(fraudTypeList);
    }

    @ApiOperation("撤销登记增长分析(年)")
    @PostMapping("staticFraudYear")
    public RestResult<?> staticFraudYear() {
        //<!--    按年统计全市-->
        List<Map<String, Integer>> fraudYearList = statisticsResultService.staticFraudYear();
        StatisticsResult yResult = statisticsResultService.getOne(new QueryWrapper<StatisticsResult>()
                .lambda().eq(StatisticsResult::getModuleTag, "year_fraud"));
        yResult.setDataJson(JSON.toJSONString(fraudYearList));
        statisticsResultService.updateById(yResult);
        return RestResult.ok(fraudYearList);
    }

    @ApiOperation("撤销登记主体分布")
    @PostMapping("staticFraudRegion")
    public RestResult<?> staticFraudRegion() {
        //<!--    按年统计全市-->
        List<Map<String, String>> fraudRegionList = statisticsResultService.staticFraudRegion();
        for (Map<String, String> m : fraudRegionList) {
            if (m.containsKey("region") && m.get("region") != null) {
                m.put("region", Constant.NM_REGION_CODE.get(m.get("region")));
            }
        }
        StatisticsResult yResult = statisticsResultService.getOne(new QueryWrapper<StatisticsResult>()
                .lambda().eq(StatisticsResult::getModuleTag, "all_region_fraud"));
        yResult.setDataJson(JSON.toJSONString(fraudRegionList));
        statisticsResultService.updateById(yResult);
        return RestResult.ok(fraudRegionList);
    }

    @ApiOperation("联合惩戒来源分析")
    @PostMapping("staticLockType")
    public RestResult<?> staticLockType() {
        //<!--    按年统计全市-->
        List<Map<String, Integer>> lockInList = statisticsResultService.staticLockType();

        StatisticsResult yResult = statisticsResultService.getOne(new QueryWrapper<StatisticsResult>()
                .lambda().eq(StatisticsResult::getModuleTag, "in_lock"));
        yResult.setDataJson(JSON.toJSONString(lockInList));
        statisticsResultService.updateById(yResult);
        return RestResult.ok(lockInList);
    }

    @ApiOperation("联合惩戒主体分布")
    @PostMapping("staticLockRegion")
    public RestResult<?> staticLockRegion() {
        //<!--    按年统计全市-->
        List<Map<String, String>> lockRegionList = statisticsResultService.staticLockRegion();
        for (Map<String, String> m : lockRegionList) {
            if (m.containsKey("region") && m.get("region") != null) {
                m.put("region", Constant.NM_REGION_CODE.get(m.get("region")));
            }
        }
        StatisticsResult yResult = statisticsResultService.getOne(new QueryWrapper<StatisticsResult>()
                .lambda().eq(StatisticsResult::getModuleTag, "all_region_lock"));
        yResult.setDataJson(JSON.toJSONString(lockRegionList));
        statisticsResultService.updateById(yResult);
        return RestResult.ok(lockRegionList);
    }

    @ApiOperation("批量吊销增长分析(年)")
    @PostMapping("staticRevYear")
    public RestResult<?> staticRevYear() {
        //<!--    按年统计全市-->
        List<Map<String, Integer>> revYearList = statisticsResultService.staticRevYear();
        StatisticsResult yResult = statisticsResultService.getOne(new QueryWrapper<StatisticsResult>()
                .lambda().eq(StatisticsResult::getModuleTag, "year_rev"));
        yResult.setDataJson(JSON.toJSONString(revYearList));
        statisticsResultService.updateById(yResult);
        return RestResult.ok(revYearList);
    }

    @ApiOperation("批量吊销主体分布")
    @PostMapping("staticRevRegion")
    public RestResult<?> staticRevRegion() {
        //<!--    按年统计全市-->
        List<Map<String, String>> revRegionList = statisticsResultService.staticRevRegion();
        for (Map<String, String> m : revRegionList) {
            if (m.containsKey("region") && m.get("region") != null) {
                m.put("region", Constant.NM_REGION_CODE.get(m.get("region")));
            }
        }
        StatisticsResult yResult = statisticsResultService.getOne(new QueryWrapper<StatisticsResult>()
                .lambda().eq(StatisticsResult::getModuleTag, "all_region_rev"));
        yResult.setDataJson(JSON.toJSONString(revRegionList));
        statisticsResultService.updateById(yResult);
        return RestResult.ok(revRegionList);
    }

    /**
     * 通过模块数据获取最新的定时统计数据
     */
    @GetMapping("latest/{moduleTag}")
    @ApiOperation("通过模块数据获取最新的定时统计数据")
    public RestResult<?> getLatestStatisticsByModuleTag(@ApiParam("模块标签") @PathVariable String moduleTag) {
        StatisticsModuleEnum moduleEnum = StatisticsModuleEnum.getEnumByModuleTag(moduleTag);
        if (moduleEnum == null) return RestResult.error(ResultCode.PARAM_IS_INVALID);
        StatisticsResult result = statisticsResultService.getLatest(moduleTag);
        return result == null ? RestResult.ok() : RestResult.ok(JSON.parse(result.getDataJson()));
    }

//    @Autowired
//    private SolrSearchTemplate solrSearchTemplate;
//    @Autowired
//    private CompanyDetailRepository companyDetailRepository;
//    @Autowired
//    private EBaseInfoRepository eBaseInfoRepository;
//    @Resource
//    private SolrTemplate solrTemplate;// springboot+solrj原装模版接口

//    @ApiOperation("根据key值删除缓存")
//    @PostMapping("queryBySolrByid")
//    public RestResult<?> queryBySolrByid(String id) {
//        EBaseInfoSolrBean byId = solrSearchTemplate.getById(id, EBaseInfoSolrBean.class);
//        EBaseInfoSolrBean byId3 = solrSearchTemplate.getOneByField(EBaseInfoSolrBean.PRIPID, id, EBaseInfoSolrBean.class);
//        EBaseInfoSolrBean byId1 = eBaseInfoRepository.findById(id).orElse(null);
//        EBaseInfoSolrBean byId2 = solrTemplate.getById(BeanUtil.getId(EBaseInfoSolrBean.class), id, EBaseInfoSolrBean.class).orElse(null);
//        return RestResult.ok();
//    }


//    @ApiOperation("验证码")
//    @GetMapping("pageCodeTest")
//    public void pageCodeTest(HttpServletResponse response, HttpServletRequest request) throws IOException {
//        ServletOutputStream outputStream=null;
//        try {
//            outputStream = response.getOutputStream();
//            PageCodeUtils.outputVerifyImage(200, 100, outputStream, 4);
//        }catch (Exception e) {
//            outputStream.close();
//            e.printStackTrace();
//        } finally {
//            outputStream.close();
//        }
//    }

    @PostMapping("Ptest")
    public RestResult<?> Ptest(String... bizseq) {
        System.out.println(bizseq + "==================");
        return RestResult.ok(bizseq);
    }

    @PostMapping("Jtest")
    public RestResult<?> Jtest(@RequestBody String data) {
        Map map = JSONObject.parseObject(data, Map.class);
        System.out.println(data + "==================");
        return RestResult.ok(map.get("bizseq"));
    }

    @ApiOperation("手动预生成听证报告书")
    @PostMapping("createHearingBatch")
    public RestResult<?> createHearingBatch(String bizseq, String nowTime, int y, int m, int d) {
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime now = LocalDateTime.parse(nowTime, df);
        LocalDate nowDate = LocalDate.of(y, m, d);
        List<BizRevEnt> bizRevEntList = bizRevEntService.getListByBizseq(bizseq);
        for (BizRevEnt bizRevEnt : bizRevEntList) {
            TSAttachment tsAttachmentModel = new TSAttachment();
            tsAttachmentModel.setAttachmentid(UUID.randomUUID().toString());
            tsAttachmentModel.setCreatetype("1");// 文件为系统生成
            tsAttachmentModel.setBizseq(bizseq);
            tsAttachmentModel.setPripid(bizRevEnt.getPripid());
            tsAttachmentModel.setFileext(".pdf");
            tsAttachmentModel.setFilename(bizRevEnt.getEntname() + "-听证告知书.pdf");
            tsAttachmentModel.setUploaddate(nowDate);
            tsAttachmentModel.setLauptime(now);
            tsAttachmentModel.setAttachtype("13");// 听证告知书
//            BizRevEnt bizRevEntModel = new BizRevEnt();
//            bizRevEntModel.setRevlistid(bizRevEnt.getRevlistid());
//            bizRevEntModel.setPreHearNotWritsno(tsWorkNoService.updateWritsNo(bizrevlistDB.getHearFirstWrit(), startNo));
//            startNo++;// 生成一份就加一
//            bizRevEntService.updateById(bizRevEntModel);
            attachmentService.save(tsAttachmentModel);
        }

        return RestResult.ok();
    }

    @ApiOperation("手动生成听证报告书")
    @PostMapping("FtyTest")
    public RestResult<?> FtyTest(String bizseq, String handleOrg, String nowTime, int y, int m, int d) {
        try {
            DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            LocalDateTime now = LocalDateTime.parse(nowTime, df);
            LocalDate nowDate = LocalDate.of(y, m, d);
            // 异步生成听证告知书
            revokeAsyncTask.revHearingNoticeTask(bizseq, handleOrg, now, nowDate);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return RestResult.ok();
    }

    @ApiOperation("批吊结果推送至泰富(整笔业务重新推送)")
    @PostMapping("TfServiceApi")
    public RestResult<?> TfServiceApi(String bizseq) {
        //RevokeAsyncTask rs = new RevokeAsyncTask();
        try {
            revokeAsyncTask.tfTest(bizseq);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return RestResult.ok();
    }

    @ApiOperation("批吊结果推送至泰富(根据统一码单独重新推送)")
    @PostMapping("tfRevokeByUniscid")
    public RestResult<?> tfRevokeByUniscid(String uniscid) {
        //RevokeAsyncTask rs = new RevokeAsyncTask();
        try {
            revokeAsyncTask.tfRevokeByUniscid(uniscid);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return RestResult.ok();
    }

    @ApiOperation("联合惩戒自动解锁测试")
    @PostMapping("automaticUnEntLock")
    public RestResult<?> automaticUnEntLock() {
        task.automaticUnEntLock();
        return RestResult.ok();
    }

    @ApiOperation("联合惩戒拟锁定表初始化")
    @GetMapping("/entlockinit")
    public RestResult<?> entlockinit() {
        task.initTable();
        return RestResult.ok();
    }

    @ApiOperation("迁入企业数据下载测试")
    @PostMapping("MoveinSchedule")
    public RestResult<?> MoveinSchedule(String pripid) {
        try {
            LambdaQueryWrapper<EBaseinfo> wrapper = new LambdaQueryWrapper();
            wrapper.eq(EBaseinfo::getPripid, pripid);
            EBaseinfo eBaseinfo = eBaseinfoService.getOne(wrapper);
            // 访问接口
            Object obj = moveinSchedule.getFromUri(eBaseinfo.getUniscid());
            if (obj == null) return RestResult.ok();

            moveinSchedule.insertData(obj, eBaseinfo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return RestResult.ok();
    }

    @ApiOperation("迁入企业数据全量下载")
    @PostMapping("MoveinDownloadAll")
    public RestResult<?> MoveinDownloadAll() {
        try {
            moveinSchedule.task();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return RestResult.ok();
    }

    @ApiOperation("解析数据测试")
    @PostMapping("sendDownLoadTask")
    public RestResult<?> sendDownLoadTask(String uniscid) {
        LambdaQueryWrapper<EBaseinfo> wrapper = new LambdaQueryWrapper();
        wrapper.eq(EBaseinfo::getUniscid, uniscid);
        EBaseinfo eBaseinfo = eBaseinfoService.getOne(wrapper);
        try {
            // 访问接口
            String fileStr = downLoadTask.getFromUri(uniscid);
            // 解析生成临时文件
            String decompressionPath = downLoadTask.createTemporaryFile(fileStr, eBaseinfo.getUniscid());
            // 解析入库
            downLoadTask.insertData(decompressionPath, eBaseinfo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return RestResult.ok();
    }

    @ApiOperation("下载文件流")
    @PostMapping("sendDownLoadStr")
    public RestResult<?> sendDownLoadStr(String uniscid) {
        LambdaQueryWrapper<EBaseinfo> wrapper = new LambdaQueryWrapper();
        wrapper.eq(EBaseinfo::getUniscid, uniscid);
        EBaseinfo eBaseinfo = eBaseinfoService.getOne(wrapper);
        try {
            // 访问接口
            String fileStr = downLoadTask.getFromUri(uniscid);
            log.info("返回文件流：{}", fileStr);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return RestResult.ok();
    }

    @ApiOperation("锁定数据推送测试")
    @PostMapping("sendLockdata")
    public RestResult<?> sendLockdata(String id) {
        EntLock entLock = entlockService.getById(id);
        String rs = tsbizpunishlockService.sendEntLock(entLock);
        return RestResult.ok(rs);
    }

    @ApiOperation("解锁数据推送测试")
    @PostMapping("sendunLockdata")
    public RestResult<?> sendunLockdata(String id) {
        EntLock entLock = entlockService.getById(id);
        tsbizPunishUnlockService.sendUnEntLock(entLock);
        return RestResult.ok();
    }

    @ApiOperation("checkRegionID")
    @PostMapping("checkRegionID")
    public RestResult<?> checkRegionID(HttpServletRequest request) {
        AICUser aicUser = getLoginUser(request);
        System.out.println(aicUser.getRegionID());
        String region = aicorgService.getRegionCodeByUser(aicUser);
        System.out.println(region + "====");
        return RestResult.ok();
    }

    @ApiOperation("根据key值删除缓存")
    @PostMapping("remove")
    public RestResult<?> remove(String key) {
        redisService.remove(key);
        return RestResult.ok();
    }

    @ApiOperation("set缓存")
    @PostMapping("set")
    public RestResult<?> set(String key, String value) {
        String rs = redisService.set(key, value);
        return RestResult.ok(rs);
    }

    @ApiOperation("set缓存带时间")
    @PostMapping("setwithTime")
    public RestResult<?> setwithTime(String key, String value, String s) {
        Long i = Long.parseLong(s);
        int j = Integer.valueOf(s);
        String rs = redisService.set(key, value, j);
        return RestResult.ok(rs);
    }

    @ApiOperation("get缓存")
    @PostMapping("getbykey")
    public RestResult<?> getbykey(String key) {
        System.out.println(redisService.exists(key));
        String obj = redisService.get(key);
        if (obj != null) {
            System.out.println(obj);
            return RestResult.ok(obj);
        }
        return RestResult.ok(obj);
    }

    @ApiOperation("接口测试Controller")
    @PostMapping("test")
    public RestResult<?> test(String str) {
/*          // 生成案件调查终结报告附件
        LambdaQueryWrapper<CaseReport> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CaseReport::getBizseq,bizseq);
        CaseReport report = caseReportService.getOne(wrapper);
        String areaName = ConstantsUtil.getAreaName(report.getAreaCode());
//            report.setAreaName(areaName);
        Map<String, Object> map = new HashMap<>();
        map.put("areaName",areaName);
        map.put("htmlContent",report.getReportContent());


        String path = "static" + File.separator +  "template" + File.separator + "caseReport.docx";
        createFileService.createDocxWithModel(bizseq,"案件调查终结报告","12", path,map);
        return null;*/
//        Document htmldoc = Jsoup.parse(str);
//        Elements links = htmldoc.getElementsByTag("p");
//        HashMap<String, Object> map = new HashMap<>();
//
//        ArrayList<Object> list = new ArrayList<>();
//        for (Element link : links) {
//            if(link.getElementsByAttributeValue("style","text-align:right;").size() > 0){
//                Elements value = link.getElementsByAttributeValue("style", "text-align:right;");
//                HashMap<String, Object> map2 = new HashMap<>();
//                map2.put("rightContent",value.text().trim());
//                list.add(map2);
//            }else if(link.getElementsByAttributeValue("style","text-align:left;").size() > 0){
//                Elements value = link.getElementsByAttributeValue("style", "text-align:left;");
//                HashMap<String, Object> map3 = new HashMap<>();
//                map3.put("leftContent",value.text().trim());
//                list.add(map3);
//            }else {
//                HashMap<String, Object> map1 = new HashMap<>();
//                map1.put("pragraph", link.text().trim());
//                list.add(map1);
//            }
//        }
//        map.put("htmlContent",list);

//        Document document = Jsoup.parseBodyFragment(str);
//        String text = document.selectFirst("p").text();

/*
        Document htmldoc = Jsoup.parse(str);
        Elements links = htmldoc.getElementsByTag("p");
        StringBuffer text = new StringBuffer("");
        for (Element link : links) {
            text.append("<p>");
            text.append(link.text());
            text.append("</p>");
        }
*/
        Document htmldoc = Jsoup.parse(str);
        Elements links = htmldoc.getElementsByTag("p");
        StringBuilder text = new StringBuilder("");
        for (Element link : links) {
            if (link.text().contains("身份证件号码") || link.text().contains("联系电话")) {
                continue;
            }
            text.append("<p>");
            text.append(link.text());
            text.append("</p>");
        }

        return RestResult.ok(text);
    }

/*
    @Transactional
    @ApiOperation("恢复业务表相关数据接口")
    @PostMapping("testRecover")
    public String testRecover(String tasklistid, String abnlistid, String applicant, String applicantNo, String remdate, String remexcpres) {
        // 找到待办
        TSTaskList taskList = tsTaskListService.getById(tasklistid);
        String bizseq = taskList.getBizseqid();
        if (bizseq == null) {
            return "无法恢复";
        }
        LambdaQueryWrapper<TSOpinion> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TSOpinion::getWorkflowid, taskList.getWorkflowid())
                .eq(TSOpinion::getOpiniontype, "2").orderByDesc(TSOpinion::getHandledate);
        List<TSOpinion> list = tsOpinionService.list(queryWrapper);
        LocalDateTime approveDate = list.get(0).getHandledate();

        String msg = "";
        TSAbnList tsabnlist = tsAbnListService.getById(abnlistid);
        String busname = taskList.getBusname();
        // 要恢复的业务表，
        TSBizRemList bizRemList = new TSBizRemList();
        //设置信息
        bizRemList.setBizseq(bizseq);
        bizRemList.setAbnlistid(tsabnlist.getAbnlistid());
        bizRemList.setPripid(tsabnlist.getPripid());
        bizRemList.setRegno(tsabnlist.getRegno());
        bizRemList.setEntname(tsabnlist.getEntname());
        bizRemList.setSpecause(tsabnlist.getSpecause());
        bizRemList.setAbntime(tsabnlist.getAbntime());
        bizRemList.setSpereasons(tsabnlist.getSpereasons());
        bizRemList.setApplicant(applicant);
        bizRemList.setApplicantNo(applicantNo);
        bizRemList.setLauptime(LocalDateTime.now());
        bizRemList.setAppOrPc("0");//移动端
        bizRemList.setApplyTime(taskList.getCreateTime());
        bizRemList.setRemSponsor(taskList.getCreateUsername());// 移出主办人
        bizRemList.setRemSponsorID(taskList.getCreateUserid());// 移出主办人id
        AICUser user = orgUM.findUserByPrimaryKey(taskList.getCreateUserid());
        bizRemList.setDecorg(aicorgService.getRegionCodeByUser(user));
        bizRemList.setAreaCode(aicorgService.getRegionCodeByUser(user));


        String specauseType = bizRemList.getSpecauseType();
        if ("nb".equals(specauseType)) {
            bizRemList.setRemreasons("按照《市场监督管理信用修复管理办法》国市监信规〔2021〕3号 第五条，被列入经营异常或者被标记为经营异常状态的当事人，符合补报未报年份年度报告并公示，移出经营异常名录。");// 作出决定的事实、理由、依据及主要内容
        } else if ("sd".equals(specauseType)) {
            bizRemList.setRemreasons("按照《市场监督管理信用修复管理办法》国市监信规〔2021〕3号 第五条，被列入经营异常或者被标记为经营异常状态的当事人，符合依法办理住所或者经营场所变更登记，或者当事人提出通过登记的住所或者经营场所可以重新取得联系，移出经营异常名录。");// 作出决定的事实、理由、依据及主要内容
        } else if ("xj".equals(specauseType)) {
            bizRemList.setRemreasons("按照《市场监督管理信用修复管理办法》国市监信规〔2021〕3号 第五条，被列入经营异常或者被标记为经营异常状态的当事人，符合已经更正其隐瞒真实情况、弄虚作假的公示信息，移出经营异常名录。");
        }


        String specause = tsabnlist.getSpecause();// 列入原因码值
        if (taskList.getBustype().equals("7")) {
            if ("1".equals(specause)) {
                bizRemList.setRemexcpres("1");// 移出原因
            } else if ("2".equals(specause)) {
                bizRemList.setRemexcpres("2");
            } else if ("3".equals(specause)) {
                bizRemList.setRemexcpres("3");
            } else if ("4".equals(specause)) {
                bizRemList.setRemexcpres(remexcpres);
            }
            bizRemList.setType("company");
        } else if (taskList.getBustype().equals("12")) {
            if ("1".equals(specause)) {
                bizRemList.setRemexcpres("1");// 移出原因
            } else if ("2".equals(specause)) {
                bizRemList.setRemexcpres("2");
            } else if ("3".equals(specause)) {
                bizRemList.setRemexcpres(remexcpres);
            }
            bizRemList.setType("individual");
        }

        if (taskList.getBusstatus().equals("2")) {// 业务已办结
            bizRemList.setIsAccept("1");
            bizRemList.setStatus("2");

            // 查找模板表是否有保存了文书信息
            LambdaQueryWrapper<Tswrittemplate> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Tswrittemplate::getBizseq, bizseq);
            Tswrittemplate tswrittemplate = tswrittemplateService.getOne(wrapper);
            if (tswrittemplate != null) {
                String writsType = tswrittemplate.getWritsType();
                if (WorkNoUtil.WORKNOTYPE_56.equals(writsType) || WorkNoUtil.WORKNOTYPE_59.equals(writsType)) {//企业农专-准予信用修复
                    bizRemList.setHandleStatus("3");
                    bizRemList.setIsAgreeRepair("1");
                    String codeId = "";
                    if (WorkNoUtil.WORKNOTYPE_56.equals(writsType)) {
                        codeId = "CD72";
                    } else {
                        codeId = "CD76";
                    }
                    tsabnlist.setRemexcpres(bizRemList.getRemexcpres());
                    Map<String, TRBaseCode> remCodeMap = baseCodeService.getBaseCodeMapFormCache(codeId);
                    TRBaseCode code = remCodeMap.get(bizRemList.getRemexcpres());
                    if (code != null) {
                        tsabnlist.setRemreasons(code.getName());
                    }
                    tsabnlist.setRemSponsor(bizRemList.getRemSponsor()); // 移出主办人
                    tsabnlist.setRemdate(approveDate.toLocalDate());
                    tsabnlist.setOperatestatus("0");
                    tsabnlist.setLauptime(LocalDateTime.now());
//                    tsabnlist.setReDecorg(bizRemList.getDecorg());// 移出决定机关码值
                    tsabnlist.setRemDecorg(bizRemList.getDecorg());// 移出决定机关码值
                    String decOrgName = gzaiccodeService.getNameByCode(bizRemList.getDecorg());
//                    tsabnlist.setRemDecorg(decOrgName);// 移出决定机关中文
                    tsabnlist.setReDecorg(decOrgName);// 移出决定机关中文

                    // 文书表恢复
                    TSWrit tsWritModel = new TSWrit();
                    String tswritId = UUID.randomUUID().toString();
                    tsWritModel.setWritsid(tswritId);
                    tsWritModel.setBizseq(bizRemList.getBizseq());
                    //获取用户所在部门辖区码值
                    tsWritModel.setAreaCode(bizRemList.getAreaCode());
                    tsWritModel.setWritsno(workNoService.getOperatingWrirsno(WorkNoUtil.WORKNOTYPE_53, tsWritModel.getAreaCode())); //当前用户的regionID
                    tsWritModel.setWritstype(writsType);
                    tsWritModel.setPripid(bizRemList.getPripid());
                    tsWritModel.setWritsname(WorkNoUtil.getWorkNoTypeName(writsType));
                    tsWritModel.setCreatetime(taskList.getLauptime());
                    if (tswrittemplate != null) {
                        tsWritModel.setContent(tswrittemplate.getContent());
                    }
                    tsWritService.save(tsWritModel);
                    tsabnlist.setRemwritid(tswritId);
                    tsAbnListService.updateById(tsabnlist);

                    // 生成决定书附件
                    HashMap<String, Object> map = new HashMap<>();
                    String areaName = Constant.NM_REGION_CODE.get(tsWritModel.getAreaCode());
                    areaName = areaName.contains("广州市") ? areaName : ("广州市" + areaName);
                    map.put("areaName", areaName);
                    map.put("writsNo", tsWritModel.getWritsno());
                    map.put("htmlContent", tsWritModel.getContent());
                    String approveDate1 = DateUtils.localDateFormat(list.get(0).getHandledate().toLocalDate(), "yyyy年MM月dd日");
                    map.put("approveDate", approveDate1);

                    String path = "static" + File.separator + "template" + File.separator + "repairDec.docx";
                    String pdfPath = createPdfService.createPdfWithHtmlTemplate(bizseq, path, map);
                    if (com.chinaweal.aiccs.common.util.StringUtils.isNotBlank(pdfPath)) {
                        tsWritModel.setPath(pdfPath);
                        tsWritService.updateById(tsWritModel);
                    }
                    boolean save = tsBizRemListService.save(bizRemList);
                    if (save) {
                        msg = "成功";
                    }
                } else if (WorkNoUtil.WORKNOTYPE_55.equals(writsType)) {//企业农专-不予信用修复

                } else if (WorkNoUtil.WORKNOTYPE_58.equals(writsType)) {//个体户-不予信用修复

                }
            }

        }
        return msg;
    }
*/

/*
    @Transactional
    @ApiOperation("恢复在办理中业务的业务表")
    @PostMapping("testRecoverNoEnd")
    public String testRecoverNoEnd(String tasklistid, String abnlistid, String applicant, String applicantNo, String remdate, String remexcpres) {
        // 找到待办
        TSTaskList taskList = tsTaskListService.getById(tasklistid);
        String bizseq = taskList.getBizseqid();
        if (bizseq == null) {
            return "无法恢复";
        }

        TSAbnList tsabnlist = tsAbnListService.getById(abnlistid);
        // 要恢复的业务表，
        TSBizRemList bizRemList = new TSBizRemList();
        //设置信息
        bizRemList.setBizseq(bizseq);
        bizRemList.setAbnlistid(tsabnlist.getAbnlistid());
        bizRemList.setPripid(tsabnlist.getPripid());
        bizRemList.setRegno(tsabnlist.getRegno());
        bizRemList.setEntname(tsabnlist.getEntname());
        bizRemList.setSpecause(tsabnlist.getSpecause());
        bizRemList.setAbntime(tsabnlist.getAbntime());
        bizRemList.setSpereasons(tsabnlist.getSpereasons());
        bizRemList.setApplicant(applicant);
        bizRemList.setApplicantNo(applicantNo);
        bizRemList.setLauptime(LocalDateTime.now());
        bizRemList.setAppOrPc("0");//移动端
        bizRemList.setApplyTime(taskList.getCreateTime());
        bizRemList.setRemSponsor(taskList.getCreateUsername());// 移出主办人
        bizRemList.setRemSponsorID(taskList.getCreateUserid());// 移出主办人id
        AICUser user = orgUM.findUserByPrimaryKey(taskList.getCreateUserid());
        bizRemList.setDecorg(aicorgService.getRegionCodeByUser(user));
        bizRemList.setAreaCode(aicorgService.getRegionCodeByUser(user));


        String msg = "";


        String specauseType = bizRemList.getSpecauseType();
        if ("nb".equals(specauseType)) {
            bizRemList.setRemreasons("按照《市场监督管理信用修复管理办法》国市监信规〔2021〕3号 第五条，被列入经营异常或者被标记为经营异常状态的当事人，符合补报未报年份年度报告并公示，移出经营异常名录。");// 作出决定的事实、理由、依据及主要内容
        } else if ("sd".equals(specauseType)) {
            bizRemList.setRemreasons("按照《市场监督管理信用修复管理办法》国市监信规〔2021〕3号 第五条，被列入经营异常或者被标记为经营异常状态的当事人，符合依法办理住所或者经营场所变更登记，或者当事人提出通过登记的住所或者经营场所可以重新取得联系，移出经营异常名录。");// 作出决定的事实、理由、依据及主要内容
        } else if ("xj".equals(specauseType)) {
            bizRemList.setRemreasons("按照《市场监督管理信用修复管理办法》国市监信规〔2021〕3号 第五条，被列入经营异常或者被标记为经营异常状态的当事人，符合已经更正其隐瞒真实情况、弄虚作假的公示信息，移出经营异常名录。");
        }


        String specause = tsabnlist.getSpecause();// 列入原因码值
        if (taskList.getBustype().equals("7")) {
            if ("1".equals(specause)) {
                bizRemList.setRemexcpres("1");// 移出原因
            } else if ("2".equals(specause)) {
                bizRemList.setRemexcpres("2");
            } else if ("3".equals(specause)) {
                bizRemList.setRemexcpres("3");
            } else if ("4".equals(specause)) {
                bizRemList.setRemexcpres(remexcpres);
            }
            bizRemList.setType("company");
        } else if (taskList.getBustype().equals("12")) {
            if ("1".equals(specause)) {
                bizRemList.setRemexcpres("1");// 移出原因
            } else if ("2".equals(specause)) {
                bizRemList.setRemexcpres("2");
            } else if ("3".equals(specause)) {
                bizRemList.setRemexcpres(remexcpres);
            }
            bizRemList.setType("individual");
        }
        bizRemList.setStatus("1");
        bizRemList.setHandleStatus("1");
        bizRemList.setIsAccept("1");

        if (taskList.getBusstatus().equals("0")) {// 为办结
            // 查找模板表是否有保存了文书信息
            LambdaQueryWrapper<Tswrittemplate> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Tswrittemplate::getBizseq, bizseq);
            Tswrittemplate tswrittemplate = tswrittemplateService.getOne(wrapper);
            if (tswrittemplate != null) {
                String writsType = tswrittemplate.getWritsType();
                if (WorkNoUtil.WORKNOTYPE_56.equals(writsType) || WorkNoUtil.WORKNOTYPE_59.equals(writsType)) {
                    bizRemList.setIsAgreeRepair("1");
                    boolean save = tsBizRemListService.save(bizRemList);
                    if (save) {
                        return msg = "业务表保存成功";
                    }
                }
            }
            return "文书模板为空";
        } else {
            return msg = "业务状态不为0";
        }
    }
*/

 /*   @ApiOperation("2021-11-24恢复待办接口")
    @PostMapping("testRecoverTstasklist")
    public String testRecoverTstasklist(String bizseq) {
        //经营异常： 查询业务表在办记录,2021-11-19 20:23:00之后的，意见表有过更新操作的记录
        List<TSOpinion> opinionList = tsOpinionService.getRecoverList();
        log.info("2021-11-19 20:23:00之后有过更新的在办的条数：{}条", opinionList.size());
        if (CollectionUtils.isNotEmpty(opinionList)) {
            for (TSOpinion tsOpinion : opinionList) {
                String workflowid = tsOpinion.getWorkflowid();
                LambdaQueryWrapper<RestLog> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(RestLog::getUri, "/aiccs-api/bizRemList/bizRemoveNext")
                        .like(RestLog::getQuery, "workflowid:" + workflowid)
                        .orderByDesc(RestLog::getTime);
                List<RestLog> list = restLogService.list(wrapper);
                if (CollectionUtils.isEmpty(list)) {
                    log.info("接口日志查询不到数据{}", workflowid);
                    continue;
                }
                String query = list.get(0).getQuery();
                Map<String, String> stringMap = StringUtils.changeRestLogQuery(query);
                String bizseqid = stringMap.get("bizseq");
                String nextPerformerids = stringMap.get("nextPerformerids");
                AICUser user = orgUM.findUserByPrimaryKey(nextPerformerids);
                String nextPerformerNames = (user == null ? null : user.getName());

                // 获取业务号，及业务信息
//                String bizseqid = query.substring(query.indexOf("bizseq:") + 7, query.indexOf("workflowid:") - 1);
                String curuserid = null;
                String curusername = null;
                String bustype = null;
                TSBizRemList bizRemList = null;
                if (StringUtils.isNotEmpty(bizseqid)) {
                    List<TSBizRemList> tsBizRemLists = tsBizRemListService.selectbizRembizseq(bizseqid);
                    bizRemList = tsBizRemLists.get(0);
                    if (bizRemList == null) {
                        log.info("工作流id{}业务表找不到{}", workflowid, bizseqid);
                        continue;
                    }
                    curuserid = bizRemList.getRemSponsorID();
                    curusername = bizRemList.getRemSponsor();
                    if (bizRemList.getType().equals("farmer")) {
                        bustype = "14";
                    } else if (bizRemList.getType().equals("company")) {
                        bustype = "7";
                    } else if (bizRemList.getType().equals("individual")) {
                        bustype = "12";
                    }
                }


                // 用workflowid获取 2021-11-19 20:23:00之后的，意见列表
                LambdaQueryWrapper<TSOpinion> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(TSOpinion::getWorkflowid, workflowid)
                        .gt(TSOpinion::getHandledate, "2021-11-19 20:23:00")
                        .orderByDesc(TSOpinion::getHandledate);
                List<TSOpinion> tsOpinionList = tsOpinionService.list(queryWrapper);

                TSOpinion theNewestOpinion = tsOpinionList.get(0);
                //获取下一个人，下一个人id
                String opiniontype = theNewestOpinion.getOpiniontype();
                String currentnode = null;// 下一节点
                String nodeflow = null;
                String nextId = null;
                String nextName = null;
                String busstatus = null;
                boolean isreturn = false;
                if ("1".equals(theNewestOpinion.getIsagree()) || "0".equals(theNewestOpinion.getIsagree())) {//前进流程


                    if ("0".equals(opiniontype)) {
                        currentnode = "handleExptlist";
                        nodeflow = "exptlistEnter_handleExptlist";
                    } else if ("1".equals(opiniontype)) {
                        currentnode = "approvelist";
                        nodeflow = "handleExptlist_approvelist";
                    } else if ("2".equals(opiniontype)) {
                        log.info("出现已办记录，排查{}", workflowid);
                    }
                    nextId = nextPerformerids; // 下一个人

                } else if ("2".equals(theNewestOpinion.getIsagree())) {// 下一个人为经办人
                    if (opiniontype.equals("9")) {
                        currentnode = "exptlistEnter";
                        nodeflow = "exptlistEnter";
                        nextId = theNewestOpinion.getHandlerid();
                        isreturn = true;
                    } else if ("1".equals(opiniontype)) {
                        currentnode = "exptlistEnter";
                        nodeflow = "handleExptlist_exptlistEnter";
                    } else if ("2".equals(opiniontype)) {
                        currentnode = "exptlistEnter";
                        nodeflow = "approvelist_exptlistEnter";
                    }
                    nextId = curuserid;
                }
                LambdaQueryWrapper<TSTwfProcessNode> wrapper1 = new LambdaQueryWrapper<>();
                wrapper1.eq(TSTwfProcessNode::getProcessid, workflowid);
                List<TSTwfProcessNode> processNodeList = tsTwfProcessNodeService.list(wrapper1);
                if (CollectionUtils.isNotEmpty(processNodeList)) {
                    for (TSTwfProcessNode tsTwfProcessNode : processNodeList) {
                        tsTwfProcessNode.setStatus(1);
                        tsTwfProcessNodeService.updateById(tsTwfProcessNode);
                    }
                }
                TSTwfProcessNode tsTwfProcessNode = new TSTwfProcessNode();
                tsTwfProcessNode.setStatus(0);
                tsTwfProcessNode.setCurrentnode(currentnode);
                tsTwfProcessNode.setNodeflow(nodeflow);
                tsTwfProcessNode.setProcessid(workflowid);
                tsTwfProcessNode.setCurruserid(nextId);//下一个人id
                tsTwfProcessNode.setLauptime(LocalDateTime.now());
                tsTwfProcessNodeService.save(tsTwfProcessNode);
                log.info("新增一条节点记录：{}", tsTwfProcessNode.toString());

                // 先去待办表查是否有待办
                LambdaQueryWrapper<TSTaskList> queryWrapper1 = new LambdaQueryWrapper<>();
                queryWrapper1.eq(TSTaskList::getCreateUserid, bizRemList.getRemSponsorID())
                        .eq(TSTaskList::getWorkflowid, workflowid);
                List<TSTaskList> taskList = tsTaskListService.list(queryWrapper1);
                TSTaskList tsTaskList = null;
                if (CollectionUtils.isNotEmpty(taskList)) {
                    tsTaskList = taskList.get(0);
                }
                if (tsTaskList != null) {
                    log.info("待办{}存在,作更新", tsTaskList.toString());
                    tsTaskList.setSignuserid(nextId);
                    tsTaskList.setSignloginname(nextPerformerNames);
                    tsTaskList.setSigntime(tsOpinion.getHandledate());
                    tsTaskList.setSenderuserid(theNewestOpinion.getHandlerid());
                    tsTaskList.setSendername(theNewestOpinion.getHandler());
                    tsTaskList.setSendertime(theNewestOpinion.getHandledate());
                    if (isreturn) {
                        tsTaskList.setBusstatus("5");
                    }
                    tsTaskList.setRemarks("20日经营异常在办更新");
                    tsTaskListService.updateById(tsTaskList);

                    LambdaQueryWrapper<TSTaskList> wrapper2 = new LambdaQueryWrapper<>();
                    wrapper2.eq(TSTaskList::getBizseqid, bizseqid)
                            .ne(TSTaskList::getCreateUserid, bizRemList.getRemSponsorID())
                            .ne(TSTaskList::getBusstatus, "4");
                    List<TSTaskList> list2 = tsTaskListService.list(wrapper2);
                    if (CollectionUtils.isNotEmpty(list2)) {
                        for (TSTaskList tsTaskList1 : list2) {
                            tsTaskList1.setBusstatus("4");
                            tsTaskListService.updateById(tsTaskList1);
                        }
                    }
                    LambdaQueryWrapper<TSTwfTask> wrapper3 = new LambdaQueryWrapper<>();
                    wrapper3.eq(TSTwfTask::getProcessid, workflowid);
                    TSTwfTask twfTask = tsTwfTaskService.getOne(wrapper3, false);
                    if (twfTask == null) {

                        TSTwfTask tsTwfTask = new TSTwfTask();
                        tsTwfTask.setProcessid(workflowid);
                        tsTwfTask.setStatus(2);
                        tsTwfTask.setCreatedon(tsTaskList.getCreateTime());
                        tsTwfTask.setActualownerid(tsTaskList.getCreateUserid());
                        tsTwfTask.setCreatedbyid(tsTaskList.getCreateUserid());
                        tsTwfTaskService.save(tsTwfTask);
                        log.info("twfTask表查无记录,新增一条{}", tsTwfTask.toString());
                    }

                } else {
                    TSTaskList taskListNew = new TSTaskList();
                    taskListNew.setWorkflowid(workflowid);
                    taskListNew.setBizseqid(bizseqid);
                    if (isreturn) {
                        taskListNew.setBusstatus("5");
                    } else {
                        taskListNew.setBusstatus("0");
                    }
                    taskListNew.setBustype(bustype);
                    taskListNew.setCreateUserid(curuserid);
                    taskListNew.setCreateUsername(curusername);
                    taskListNew.setSenderuserid(theNewestOpinion.getHandlerid());
                    taskListNew.setSendername(theNewestOpinion.getHandler());
                    taskListNew.setSendertime(theNewestOpinion.getHandledate());
                    taskListNew.setLinkname("经营异常名录");
                    taskListNew.setIssignon("1");
                    taskListNew.setSignuserid(nextId);
                    taskListNew.setSignloginname(nextPerformerNames);
                    taskListNew.setSigntime(theNewestOpinion.getHandledate());
                    log.info("{}业务号的主办人id{}", bizseqid, curuserid);
                    AICUser aicUser = orgUM.findUserByPrimaryKey(curuserid);
                    taskListNew.setAcceptno(aicUser.getRegionID().substring(0, Math.min(aicUser.getRegionID().length(), 6)) + uuidUtil.getCurAcceptNo());
                    if (bizRemList != null) {
                        taskListNew.setBusname(bizRemList.getEntname());
                        taskListNew.setCreateTime(bizRemList.getApplyTime());
                    }
                    taskListNew.setRemarks("20日经营异常在办重推");
                    taskListNew.setLauptime(LocalDateTime.now());
                    tsTaskListService.save(taskListNew);
                    log.info("待办不存在,新增: 业务号为{}，工作流id为{},新增待办为{}", bizRemList.getBizseq(), workflowid, taskListNew.toString());

                    LambdaQueryWrapper<TSTwfTask> wrapper3 = new LambdaQueryWrapper<>();
                    wrapper3.eq(TSTwfTask::getProcessid, workflowid);
                    TSTwfTask twfTask = tsTwfTaskService.getOne(wrapper3, false);
                    if (twfTask == null) {
                        TSTwfTask tsTwfTask = new TSTwfTask();
                        tsTwfTask.setProcessid(workflowid);
                        tsTwfTask.setStatus(2);
                        tsTwfTask.setCreatedon(taskListNew.getCreateTime());
                        tsTwfTask.setActualownerid(taskListNew.getCreateUserid());
                        tsTwfTask.setCreatedbyid(taskListNew.getCreateUserid());
                        tsTwfTaskService.save(tsTwfTask);
                        log.info("twfTask表查无记录,新增一条{}", tsTwfTask.toString());
                    }
                }


            }
        }
        return null;
    }
*/
/*
    @ApiOperation("2021-11-24恢复待办接口（回退至申请人）")
    @PostMapping("testRecoverTstasklistReturn")
    public String testRecoverTstasklistReturn() {
        List<TSOpinion> opinionList = tsOpinionService.getRecoverListReturn();
        log.info("(回退)2021-11-19 20:23:00之后有过更新的回退至申请人的条数：{}条", opinionList.size());
        if (CollectionUtils.isNotEmpty(opinionList)) {
            for (TSOpinion tsOpinion : opinionList) {
                LambdaQueryWrapper<TSOpinion> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(TSOpinion::getWorkflowid, tsOpinion.getWorkflowid())
                        .gt(TSOpinion::getHandledate, "2021-11-19 20:23:00")
                        .orderByDesc(TSOpinion::getHandledate);
                List<TSOpinion> list = tsOpinionService.list(wrapper);
                TSOpinion theNewestOpinion = list.get(0);
                String workflowid = theNewestOpinion.getWorkflowid();
                if (!theNewestOpinion.getOpiniontype().equals("9")) {
                    log.info("(回退)最新意见类型不是回退至申请人类型{}", workflowid);
                }
                LambdaQueryWrapper<RestLog> wrapper1 = new LambdaQueryWrapper<>();
                wrapper1.eq(RestLog::getUri, "/aiccs-api/bizRemList/returnToApplyer")
                        .like(RestLog::getQuery, "handlerid:" + theNewestOpinion.getHandlerid())
                        .like(RestLog::getQuery, "backProposal:" + theNewestOpinion.getOpinioncontent())
                        .orderByDesc(RestLog::getTime);
                List<RestLog> list1 = restLogService.list(wrapper1);
                if (CollectionUtils.isEmpty(list1)) {
                    log.info("(回退)接口日志查询不到数据{}", workflowid);
                    continue;
                } else if (list1.size() > 1) {
                    log.info("(回退)接口日志查询到的数据有多条，待检验{}", workflowid);
                    continue;
                }
                String query = list1.get(0).getQuery();
                Map<String, String> stringMap = StringUtils.changeRestLogQuery(query);
                String bizseqid = stringMap.get("bizseq");

                if (StringUtils.isNotEmpty(bizseqid)) {
                    List<TSBizRemList> tsBizRemLists = tsBizRemListService.selectbizRembizseq(bizseqid);
                    TSBizRemList bizRemList = tsBizRemLists.get(0);
                    if (bizRemList == null) {
                        log.info("(回退)工作流id{}业务表找不到{}", workflowid, bizseqid);
                        continue;
                    } else if (!bizRemList.getHandleStatus().equals("2")) {
                        log.info("(回退)工作流id{}业务表状态不是回退{}", workflowid, bizseqid);
                    }


                    // 先去待办表查是否有待办
                    LambdaQueryWrapper<TSTaskList> queryWrapper1 = new LambdaQueryWrapper<>();
                    queryWrapper1.eq(TSTaskList::getCreateUserid, bizRemList.getRemSponsorID())
                            .eq(TSTaskList::getBizseqid, bizseqid);
                    List<TSTaskList> taskList = tsTaskListService.list(queryWrapper1);
                    TSTaskList tsTaskListdb = null;
                    if (CollectionUtils.isNotEmpty(taskList)) {
                        tsTaskListdb = taskList.get(0);
                    }
                    if (tsTaskListdb != null) {
                        log.info("(回退)待办{}存在,作更新", tsTaskListdb.toString());
                        tsTaskListdb.setBusstatus("5");
                        tsTaskListdb.setRemarks("20日经营异常在办更新");
                        tsTaskListService.updateById(tsTaskListdb);

                        LambdaQueryWrapper<TSTaskList> wrapper3 = new LambdaQueryWrapper<>();
                        wrapper3.eq(TSTaskList::getBizseqid, bizseqid)
                                .ne(TSTaskList::getCreateUserid, bizRemList.getRemSponsorID())
                                .ne(TSTaskList::getBusstatus, "4");
                        List<TSTaskList> list2 = tsTaskListService.list(wrapper3);
                        if (CollectionUtils.isNotEmpty(list2)) {
                            for (TSTaskList tsTaskList1 : list2) {
                                tsTaskList1.setBusstatus("4");
                                tsTaskListService.updateById(tsTaskList1);
                            }
                        }

                        LambdaQueryWrapper<TSTwfTask> wrapper4 = new LambdaQueryWrapper<>();
                        wrapper4.eq(TSTwfTask::getProcessid, workflowid);
                        TSTwfTask twfTask = tsTwfTaskService.getOne(wrapper4, false);
                        if (twfTask == null) {

                            TSTwfTask tsTwfTask = new TSTwfTask();
                            tsTwfTask.setProcessid(workflowid);
                            tsTwfTask.setStatus(2);
                            tsTwfTask.setCreatedon(tsTaskListdb.getCreateTime());
                            tsTwfTask.setActualownerid(tsTaskListdb.getCreateUserid());
                            tsTwfTask.setCreatedbyid(tsTaskListdb.getCreateUserid());
                            tsTwfTaskService.save(tsTwfTask);
                            log.info("(回退)twfTask表查无记录,新增一条{}", tsTwfTask.toString());
                        }
                    } else {
                        TSTaskList tsTaskList = new TSTaskList();
                        tsTaskList.setWorkflowid(workflowid);
                        tsTaskList.setBizseqid(bizseqid);
                        tsTaskList.setCreateTime(bizRemList.getApplyTime());
                        tsTaskList.setCreateUserid(bizRemList.getRemSponsorID());
                        tsTaskList.setCreateUsername(bizRemList.getRemSponsor());
                        tsTaskList.setSignuserid(bizRemList.getRemSponsorID());
                        tsTaskList.setSignloginname(bizRemList.getRemSponsor());
                        tsTaskList.setBusstatus("5");
                        if (bizRemList.getType().equals("farmer")) {
                            tsTaskList.setBustype("14");
                        } else if (bizRemList.getType().equals("company")) {
                            tsTaskList.setBustype("7");
                        } else if (bizRemList.getType().equals("individual")) {
                            tsTaskList.setBustype("12");
                        }
                        tsTaskList.setSenderuserid(theNewestOpinion.getHandlerid());
                        tsTaskList.setSendername(theNewestOpinion.getHandler());
                        tsTaskList.setSendertime(theNewestOpinion.getHandledate());
                        tsTaskList.setLinkname("经营异常名录");
                        tsTaskList.setIssignon("1");
                        tsTaskList.setSigntime(theNewestOpinion.getHandledate());
                        log.info("(回退){}业务号的主办人id{}", bizseqid, bizRemList.getRemSponsorID());
                        AICUser aicUser = orgUM.findUserByPrimaryKey(bizRemList.getRemSponsorID());
                        tsTaskList.setAcceptno(aicUser.getRegionID().substring(0, Math.min(aicUser.getRegionID().length(), 6)) + uuidUtil.getCurAcceptNo());
                        tsTaskList.setBusname(bizRemList.getEntname());
                        tsTaskList.setRemarks("20日经营异常在办重推");
                        tsTaskList.setLauptime(LocalDateTime.now());
                        tsTaskListService.save(tsTaskList);
                        log.info("(回退)待办不存在,新增: 业务号为{}，工作流id为{},新增待办为{}", bizseqid, workflowid, tsTaskList.toString());

                        LambdaQueryWrapper<TSTwfTask> wrapper4 = new LambdaQueryWrapper<>();
                        wrapper4.eq(TSTwfTask::getProcessid, workflowid);
                        TSTwfTask twfTask = tsTwfTaskService.getOne(wrapper4, false);
                        if (twfTask == null) {

                            TSTwfTask tsTwfTask = new TSTwfTask();
                            tsTwfTask.setProcessid(workflowid);
                            tsTwfTask.setStatus(2);
                            tsTwfTask.setCreatedon(tsTaskList.getCreateTime());
                            tsTwfTask.setActualownerid(tsTaskList.getCreateUserid());
                            tsTwfTask.setCreatedbyid(tsTaskList.getCreateUserid());
                            tsTwfTaskService.save(tsTwfTask);
                            log.info("(回退)twfTask表查无记录,新增一条{}", tsTwfTask.toString());
                        }
                    }
                    LambdaQueryWrapper<TSTwfProcessNode> wrapper2 = new LambdaQueryWrapper<>();
                    wrapper2.eq(TSTwfProcessNode::getProcessid, workflowid);
                    List<TSTwfProcessNode> processNodeList = tsTwfProcessNodeService.list(wrapper2);
                    if (CollectionUtils.isNotEmpty(processNodeList)) {
                        for (TSTwfProcessNode tsTwfProcessNode : processNodeList) {
                            tsTwfProcessNode.setStatus(1);
                            tsTwfProcessNodeService.updateById(tsTwfProcessNode);
                        }
                    }
                    TSTwfProcessNode tsTwfProcessNode = new TSTwfProcessNode();
                    tsTwfProcessNode.setStatus(0);
                    tsTwfProcessNode.setCurrentnode("exptlistEnter");
                    tsTwfProcessNode.setNodeflow("exptlistEnter");
                    tsTwfProcessNode.setProcessid(workflowid);
                    tsTwfProcessNode.setCurruserid(theNewestOpinion.getHandlerid());
                    tsTwfProcessNode.setLauptime(LocalDateTime.now());
                    tsTwfProcessNodeService.save(tsTwfProcessNode);
                    log.info("(回退)新增一条节点记录：{}", tsTwfProcessNode.toString());
                }
            }
        }
        return null;
    }
*/

/*
    @ApiOperation("2021-11-24恢复待办接口（已办）")
    @PostMapping("testRecoverTstasklistFinish")
    public String testRecoverTstasklistFinish() {
        //经营异常： 查询已办记录,2021-11-19 20:23:00之后的，意见表有过更新操作的记录
        List<TSOpinion> opinionList = tsOpinionService.getRecoverListFinish();
        log.info("(已办)2021-11-19 20:23:00之后已办的条数：{}条", opinionList.size());
        StringBuilder stringBuilder = new StringBuilder();
        try {


            if (CollectionUtils.isNotEmpty(opinionList)) {
                for (TSOpinion tsOpinion : opinionList) {
                    String workflowid = tsOpinion.getWorkflowid();
                    LambdaQueryWrapper<RestLog> wrapper = new LambdaQueryWrapper<>();
                    wrapper.eq(RestLog::getUri, "/aiccs-api/bizRemList/bizRemoveNext")
                            .like(RestLog::getQuery, "workflowid:" + workflowid)
                            .orderByDesc(RestLog::getTime);
                    List<RestLog> list = restLogService.list(wrapper);
                    if (CollectionUtils.isEmpty(list)) {
                        log.info("(已办)接口日志查询不到数据{}", workflowid);
                        stringBuilder.append("(已办)接口日志查询不到数据[").append(workflowid).append("]");
                        continue;
                    }
                    String query = list.get(0).getQuery();
                    Map<String, String> stringMap = StringUtils.changeRestLogQuery(query);
                    String bizseq = stringMap.get("bizseq");
//                String nextPerformerids = stringMap.get("nextPerformerids");
//                AICUser user = orgUM.findUserByPrimaryKey(nextPerformerids);
//                String nextPerformerNames = (user == null ? null : user.getName());
                    if (StringUtils.isEmpty(bizseq)) {
                        log.info("(已办)获取不到业务号数据{}", workflowid);
                        stringBuilder.append("获取不到业务号数据[").append(workflowid).append("]");
                        continue;
                    }
                    List<TSBizRemList> tsBizRemLists = tsBizRemListService.selectbizRembizseq(bizseq);
                    if (tsBizRemLists.size() > 1) {
                        stringBuilder.append("业务号[").append(bizseq).append("]的业务表数据有多条");
                    } else if (CollectionUtils.isEmpty(tsBizRemLists)) {
                        log.info("(已办)工作流id{}业务表找不到{}", workflowid, bizseq);
                        stringBuilder.append("工作流id[").append(workflowid).append("]的业务表[").append(bizseq).append("]找不到");
                        continue;
                    }
                    TSBizRemList bizRemList = tsBizRemLists.get(0);

                    // 用workflowid获取 2021-11-19 20:23:00之后的，意见列表
                    LambdaQueryWrapper<TSOpinion> wrapper1 = new LambdaQueryWrapper<>();
                    wrapper1.eq(TSOpinion::getWorkflowid, workflowid)
                            .gt(TSOpinion::getHandledate, "2021-11-19 20:23:00")
                            .eq(TSOpinion::getOpiniontype, "2")
                            .orderByDesc(TSOpinion::getHandledate);
                    List<TSOpinion> tsOpinionList = tsOpinionService.list(wrapper1);

                    TSOpinion theNewestOpinion = tsOpinionList.get(0);

                    LambdaQueryWrapper<TSTaskList> queryWrapper = new LambdaQueryWrapper<>();
                    queryWrapper.eq(TSTaskList::getBizseqid, bizseq)
                            .eq(TSTaskList::getWorkflowid, workflowid)
                            .eq(TSTaskList::getCreateUserid, bizRemList.getRemSponsorID());
                    List<TSTaskList> taskLists = tsTaskListService.list(queryWrapper);
                    // 符合主办人的待办找不到
                    if (CollectionUtils.isEmpty(taskLists)) {
                        queryWrapper = new LambdaQueryWrapper<>();
                        queryWrapper.eq(TSTaskList::getBizseqid, bizseq);
                        List<TSTaskList> list1 = tsTaskListService.list(queryWrapper);
                        // 设置其他人待办为无效
                        if (CollectionUtils.isNotEmpty(list1)) {
                            for (TSTaskList tsTaskList : list1) {
                                tsTaskList.setBusstatus("4");
                                tsTaskListService.updateById(tsTaskList);
                            }
                        }
                        // 新建待办保存
                        TSTaskList taskListNew = new TSTaskList();
                        taskListNew.setWorkflowid(workflowid);
                        taskListNew.setBizseqid(bizseq);
                        taskListNew.setBusstatus("2");
                        if (bizRemList.getType().equals("farmer")) {
                            taskListNew.setBustype("14");
                        } else if (bizRemList.getType().equals("company")) {
                            taskListNew.setBustype("7");
                        } else if (bizRemList.getType().equals("individual")) {
                            taskListNew.setBustype("12");
                        }
                        taskListNew.setCreateUserid(bizRemList.getRemSponsorID());
                        taskListNew.setCreateUsername(bizRemList.getRemSponsor());

                        taskListNew.setSenderuserid(theNewestOpinion.getHandlerid());
                        taskListNew.setSendername(theNewestOpinion.getHandler());
                        taskListNew.setSendertime(theNewestOpinion.getHandledate());
                        taskListNew.setLinkname("经营异常名录");
                        taskListNew.setIssignon("1");
                        taskListNew.setSignuserid(theNewestOpinion.getHandlerid());
                        taskListNew.setSignloginname(theNewestOpinion.getHandler());
                        taskListNew.setSigntime(theNewestOpinion.getHandledate());
                        log.info("(已办){}业务号的主办人id{}", bizseq, bizRemList.getRemSponsorID());
                        AICUser aicUser = orgUM.findUserByPrimaryKey(bizRemList.getRemSponsorID());
                        taskListNew.setAcceptno(aicUser.getRegionID().substring(0, Math.min(aicUser.getRegionID().length(), 6)) + uuidUtil.getCurAcceptNo());
                        taskListNew.setBusname(bizRemList.getEntname());
                        taskListNew.setCreateTime(bizRemList.getApplyTime());
                        taskListNew.setRemarks("20日经营异常已办重推");
                        taskListNew.setLauptime(LocalDateTime.now());
                        tsTaskListService.save(taskListNew);
                        log.info("(已办)待办不存在,新增: 业务号为{}，工作流id为{},新增待办为{}", bizRemList.getBizseq(), workflowid, taskListNew.toString());

                    } else {// 找到
                        // 用第一条
                        TSTaskList tsTaskList = taskLists.get(0);
                        log.info("待办{}存在,作更新", tsTaskList.toString());
                        queryWrapper = new LambdaQueryWrapper<>();
                        queryWrapper.eq(TSTaskList::getBizseqid, bizseq).ne(TSTaskList::getTasklistid, tsTaskList.getTasklistid());
                        List<TSTaskList> list1 = tsTaskListService.list(queryWrapper);
                        // 设置其他人待办为无效
                        if (CollectionUtils.isNotEmpty(list1)) {
                            for (TSTaskList each : list1) {
                                each.setBusstatus("4");
                                tsTaskListService.updateById(each);
                            }
                        }
                        tsTaskList.setBusstatus("2");
                        tsTaskList.setSenderuserid(theNewestOpinion.getHandlerid());
                        tsTaskList.setSendername(theNewestOpinion.getHandler());
                        tsTaskList.setSendertime(theNewestOpinion.getHandledate());
                        tsTaskList.setLinkname("经营异常名录");
                        tsTaskList.setIssignon("1");
                        tsTaskList.setSignuserid(theNewestOpinion.getHandlerid());
                        tsTaskList.setSignloginname(theNewestOpinion.getHandler());
                        tsTaskList.setSigntime(theNewestOpinion.getHandledate());
                        tsTaskList.setRemarks("20日经营异常已办更新");
                        tsTaskList.setLauptime(LocalDateTime.now());
                        tsTaskListService.updateById(tsTaskList);
                    }

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(stringBuilder);
        }


        return null;
    }
*/

    @PostMapping("testExcel")
    public RestResult<?> testExcel(String bizseq, String attachtype, String pripids) {
        String[] split = pripids.split(",");
//        String path = createFileService.createEntExcel(bizseq, attachtype, Arrays.asList(split));
//        return RestResult.ok(path);
        return RestResult.ok();
    }

//    @GetMapping("initAddress")
//    public RestResult<?> initAddress() {
//        final int pageSize = 10000;
//        new Thread(() -> {
//            List<EBaseinfo> list = eBaseinfoMapper.getNotExistsAddress(null, pageSize);
//            while (list != null && list.size() == pageSize) {
//                for (EBaseinfo address : list) {
//                    try {
//                        areaSliceClaimAI.getPointByAddress(address.getAddress());
//                    } catch (BusinessException e) {
//                        if (e.getMessage().equals("配额不足")) {
//                            return;
//                        }
//                        log.warn(e.getMessage());
//                    }
//                }
//                list = eBaseinfoMapper.getNotExistsAddress(list.get(list.size() - 1).getAddress(), pageSize);
//            }
//            if (list != null) {
//                for (EBaseinfo address : list) {
//                    try {
//                        areaSliceClaimAI.getPointByAddress(address.getAddress());
//                    } catch (BusinessException e) {
//                        if (e.getMessage().equals("配额不足")) {
//                            return;
//                        }
//                        log.warn(e.getMessage());
//                    }
//                }
//            }
//        }).start();
//        return RestResult.ok();
//    }

    @PostMapping("testSSJ")
    public RestResult<?> testSSJ() {
//        HashMap<String, String> map = new HashMap<>();
//        map.put("datafromId","7cb2a21f-28d6-479b-9ddd-9a205daaefcb");
//        map.put("reason","退回测试");
//        ForestResponse<Map<String, Object>> mapForestResponse = abnClueService.clueReturn("7cb2a21f-28d6-479b-9ddd-9a205daaefcb","退回测试");
//        Map<String, Object> result = mapForestResponse.getResult();
//        String status = StringUtils.tranObject(result.get("status"));
//        System.out.println(status);
        return RestResult.ok();
    }

    @PostMapping("testTable")
    public RestResult<?> testTable(String bizseq) {
        List<Tsbizrevlist> tsbizrevlists = tsbizrevlistService.list(
                new LambdaQueryWrapper<Tsbizrevlist>().eq(Tsbizrevlist::getBizseq, bizseq)
                        .eq(Tsbizrevlist::getIsRemove, "0").orderByDesc(Tsbizrevlist::getInsertTime));
        HashMap<String, Object> map = new HashMap<>();
        // 存入名单附录
        map.put("nameList", tsbizrevlists);


        map.put("htmlContent", "123");
        String path = "static" + File.separator + "template" + File.separator + "caseReport.docx";
        createFileService.createDocxWithModel(bizseq, "案件调查终结报告", "12", path, map);
        return RestResult.ok();
    }

    @PostMapping("testPdf")
    public RestResult<?> testPdf(String temppath, String bizseq) {
        String realPath = CommonConfig.getUploadPath();
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        fileStorageService.writeToStream(realPath + File.separator + temppath, bos);
        String fileName = temppath.substring(temppath.lastIndexOf(File.separator) + 1, temppath.lastIndexOf(Constant.DOT));
        String pdfTemppath = bizseq + File.separator + "PDF" + File.separator + fileName + ".pdf";
        String pdfPath = realPath + File.separator + pdfTemppath;
        PdfUtil.convertDocx2Pdf(bos, pdfPath);
        return RestResult.ok(pdfPath);
    }

    @Transactional()
    @PostMapping("testCode")
    public RestResult<?> testCode(HttpServletRequest request) {
        AICUser user = getLoginUser(request);
        if (user == null) return RestResult.error(ResultCode.USER_NOT_LOGGED_IN);
        HashMap<String, Object> map = new HashMap<>();

        System.out.println(user.getRegionID());
        String code = aicorgService.getRegionCodeByUser(user);
        System.out.println(code);
//        map.put("oldCode", code);
//        Gzaiccode gzaiccode = usersService.findOrganization(SSOUtil.getUser().getPrimaryKey());
//        String scountrycode = gzaiccode.getScountrycode();
//        map.put("newCode", scountrycode);
        // 市局 440100  新：440101
        // 南沙 440115  新：440110
        // 增城 440118  新：440125
        // 从化 440117  新：440122
        // 花都 440114  新：440121

//        TSAttachment tsAttachment = new TSAttachment();
//        tsAttachment.setAttachmentid("52a7a015689a186b70a9703f89e460ac");
//        tsAttachment.setRemNo(9);
//        attachmentService.updateById(tsAttachment);
//        System.out.println(tsAttachment);
        throw new BusinessException("123");
    }

    @GetMapping("oldSliceDataClear")
    public RestResult<?> oldSliceDataClear() {
        new Thread(() -> {
            String supOrg = "天河";
            int fetch = 10000;
            List<EBaseinfo> eBaseinfos = bizOwnerAssignService.selectNoAssignRecordInfo(null, fetch, supOrg);
            while (CollectionUtils.isNotEmpty(eBaseinfos)) {
                for (EBaseinfo each : eBaseinfos) {
                    String sareacodeJx = each.getSareacodeJx();

                    if (sareacodeJx.length() > 13) {
                        sareacodeJx = sareacodeJx.substring(0, 12);
                    }
                    List<String> areaSlices = new ArrayList<>();
                    AreaSlice byId = areaSliceService.getById(sareacodeJx);
                    if (byId == null) continue;
                    areaSlices.add(byId.getSliceId());
                    while (byId != null && StringUtils.isNotBlank(byId.getPSliceId())) {
                        areaSlices.add(byId.getPSliceId());
                        byId = areaSliceService.getById(byId.getPSliceId());
                    }
                    areaSlices.sort(Comparator.naturalOrder());
                    for (String areaSlice : areaSlices) {
                        bizOwnerAssignService.areaClaim(areaSlice, each.getPripid(), AreaSliceClaimAI.OPERATOR);
                    }
                }
                eBaseinfos =
                        bizOwnerAssignService.selectNoAssignRecordInfo(eBaseinfos.get(eBaseinfos.size() - 1).getPripid(), fetch, supOrg);
            }
        }).start();
        return RestResult.ok();
    }

    @GetMapping("allSliceDataClear")
    public RestResult<?> allSliceDataClear(@RequestParam String supOrg) {
        if (StringUtils.isBlank(supOrg))
            return RestResult.error(ResultCode.PARAM_IS_BLANK);

        new Thread(() -> {
            log.info("==========自动认领开始==========");
            int fetch = 10000;
            List<EBaseinfo> eBaseinfos = bizOwnerAssignService.selectNoAssignRecordInfo(null, fetch, supOrg);
            while (CollectionUtils.isNotEmpty(eBaseinfos)) {
                for (EBaseinfo each : eBaseinfos) {
                    AssignEntity entity = new AssignEntity()
                            .setAddress(StringUtils.isNotBlank(each.getDom()) ? each.getDom() : each.getAddress())
                            .setPripid(each.getPripid())
                            .setEntName(each.getEntname())
                            .setEntType(each.getEnttype())
                            .setLerep(each.getLerep())
                            .setRegNo(each.getRegno())
                            .setRegOrg(each.getRegorg())
                            .setRegulatory(each.getSuporg())
                            .setUniscid(each.getUniscid());
                    try {
                        areaSliceClaimAI.claimInScope(entity, AreaSliceClaimAI.OPERATOR);
                    } catch (Exception e) {
                        if (e.getMessage() != null && e.getMessage().startsWith("地址：")) {
                            log.info("priPid: {}, {}", each.getPripid(), e.getMessage());
                        } else {
                            log.error("认领异常: {}", each.getPripid(), e);
                        }
                        if ("配额不足".equals(e.getMessage())) {
                            log.error("配额不足");
                            return;
                        }
                        continue;
                    }
                }
                eBaseinfos =
                        bizOwnerAssignService.selectNoAssignRecordInfo(eBaseinfos.get(eBaseinfos.size() - 1).getPripid(), fetch, supOrg);
            }
            log.info("==========自动认领结束==========");
        }).start();
        return RestResult.ok();
    }

    @PostMapping("/next")
    public RestResult<?> processControl(@RequestBody @Validated RevokeProcessDto revokeProcessDto, BindingResult bindingResult, HttpServletRequest request) {
        AssertUtils.isBndingValidit(bindingResult);
        @Valid TsCase caseModel = revokeProcessDto.getCaseModel();
        @Valid TSOpinion opinion = revokeProcessDto.getOpinion();
        return RestResult.ok();
    }

    /**
     * word转pdf
     *
     * @param attachmentid
     * @param bizseq
     * @return
     */
    @PostMapping("word2Pdf")
    public RestResult<?> word2Pdf(String attachmentid, String bizseq, HttpServletResponse response) {
        TSAttachment attachment = attachmentService.getById(attachmentid);
        String temppath = attachment.getTemppath();
        String realPath = CommonConfig.getUploadPath();
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        fileStorageService.writeToStream(realPath + File.separator + temppath, bos);
        String fileName = temppath.substring(temppath.lastIndexOf(File.separator) + 1, temppath.lastIndexOf(Constant.DOT));
        String pdfTemppath = bizseq + File.separator + "PDF" + File.separator + fileName + ".pdf";
        String pdfPath = realPath + File.separator + pdfTemppath;
        PdfUtil.convertDocx2PdfStream(bos, pdfPath, response);
        return RestResult.ok(pdfPath);

    }

    /**
     * 测试异步
     *
     * @return
     */
    @PostMapping("testAsync")
    public RestResult<?> testAsync(String bizseq) throws Exception {

        ArrayList<BizRevEnt> list = new ArrayList<>();
        TsCase aCase = caseService.getByBizseq(bizseq);
//        asyncTask.revHearingNoticeTask(list,bizseq,"440100",aCase);

        String token = tfRevokeServicelmpl.queryTfToken();
        return RestResult.ok(token);

    }

    /**
     * 更新覆盖修改了文书号的听证告知书
     *
     * @return
     */
    @PostMapping("reUploadHearingNotice")
    public RestResult<?> reUploadHearingNotice(String bizseq, String userOrgCode) throws Exception {
        Long timeMilles = System.currentTimeMillis();
        try {
            log.info("》》》》》》》》》》》》业务号为{}听证告知书更新文书号开始《《《《《《《《《", bizseq);
            TsCase caseDB = caseService.getByBizseq(bizseq);
            TSWrit writQueryModel = new TSWrit();
            writQueryModel.setBizseq(bizseq);
            writQueryModel.setWritstype(WorkNoUtil.WORKNOTYPE_32);
            List<TSWrit> writs = tsWritService.listTswrit(writQueryModel);
            Map<String, Object> map = new HashMap<>();
            map.put("name", caseDB.getHandlerName() + "、" + caseDB.getAssistantName());
            map.put("noAttach", "noAttach");
            // 文书内容
            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 = ConstantsUtil.getDecOrgName(userOrgCode);
            for (TSWrit writ : writs) {
                LambdaQueryWrapper<EBaseinfo> lqw = new LambdaQueryWrapper<>();
                lqw.eq(EBaseinfo::getPripid, writ.getPripid());
                EBaseinfo baseinfo = eBaseinfoService.getOne(lqw, false);
                LocalDateTime createtime = writ.getCreatetime();
                map.put("htmlContent", content);
                map.put("year", createtime.getYear());
                map.put("month", createtime.getMonthValue());
                map.put("day", createtime.getDayOfMonth());
                map.put("writsno", writ.getWritsno());
                map.put("areaName", areaName);
                map.put("entname", baseinfo.getEntname());
                map.put("addr", decOrgName);
                map.put("pripid", writ.getPripid());
                // 生成听证告知书
                String path = "static" + File.separator + "template" + File.separator + "hearingNotice.docx";

                // 标题


                try {
                    ByteArrayOutputStream wordOs = new ByteArrayOutputStream(); // word输出流
                    String resource = CreateFileServiceImpl.class.getClassLoader().getResource(path).getPath();

                    //配置
                    // html内容处理
                    String htmlContent = map.get("htmlContent").toString();
                    Document htmldoc = Jsoup.parse(htmlContent);
                    Elements links = htmldoc.getElementsByTag("p");
                    ArrayList<Object> list = new ArrayList<>();
                    for (Element link : links) {
                        if (link.getElementsByAttributeValue("style", "text-align:right;").size() > 0) {
                            Elements value = link.getElementsByAttributeValue("style", "text-align:right;");
                            HashMap<String, Object> map2 = new HashMap<>();
                            map2.put("rightContent", value.text().trim());
                            list.add(map2);
                        } else if (link.getElementsByAttributeValue("style", "text-align:left;").size() > 0) {
                            Elements value = link.getElementsByAttributeValue("style", "text-align:left;");
                            HashMap<String, Object> map3 = new HashMap<>();
                            map3.put("leftContent", value.text().trim());
                            list.add(map3);
                        } else {
                            HashMap<String, Object> map1 = new HashMap<>();
                            map1.put("pragraph", link.text().trim());
                            list.add(map1);
                        }
                    }
                    map.put("htmlContent", list);
                    XWPFTemplate.compile(resource).render(map).write(wordOs);
                    PdfUtil.convertDocx2Pdf(wordOs, writ.getPath());

                } catch (Exception e) {
                    e.printStackTrace();
                    throw new BusinessException("批吊附件文书pdf上传失败");
                }
            }

            log.info("》》》》》》》》》》》》业务号为{}听证告知书更新文书号耗时:{}《《《《《《《《《", bizseq, System.currentTimeMillis() - timeMilles);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("业务号{}听证告知书更新文书号任务异常" + e, bizseq);
            return RestResult.ok("业务号" + bizseq + "听证告知书更新文书号失败");
        }
        return RestResult.ok("业务号" + bizseq + "听证告知书更新文书号耗时" + (System.currentTimeMillis() - timeMilles));
    }

    /**
     * 清洗地址调用
     *
     * @return 响应
     * @author lroyia
     * @since 2024年6月14日 09:30:47
     */
    @GetMapping("flush/address")
    public RestResult<?> flushAddress() {
        new Thread(() -> {
            entAddressAnalysisSchedule.analysisAddress();
        }).start();
        return RestResult.ok();
    }

    /**
     * 处罚决定书重新生成推送泰富
     * @author ymc
     * @since 2024年11月4日 17:04
     * @param
     * @return
     */
    @GetMapping("push/tf/penalty")
    public RestResult<?> pushTfPenalty(@RequestParam String bizSeq, @RequestParam String orgCode) throws InterruptedException {
        revokeAsyncTask.revPunishDecTask(bizSeq, orgCode);
        return RestResult.ok();
    }

   /**
    * 重新生成信用修复决定书(因XC服务器字体问题导致这些时间段生成的信用修复决定书都显示异常)
    * @author ymc
    * @since 2024年12月19日 9:56
    * @return
    */
    @GetMapping("again/cert")
    public RestResult<?> pushTfCredit() {
        Set<String> bizSeqSet = tsWritService.lambdaQuery()
                .select(TSWrit::getBizseq)
                .in(TSWrit::getWritstype, "55", "56", "57", "58", "59", "60", "62", "63")
                .between(TSWrit::getCreatetime, "2026-01-01 00:00:00", "2026-01-07 12:00:00")
                .list().stream().map(TSWrit::getBizseq).collect(Collectors.toSet());

        for (String bizSeq : bizSeqSet) {
            List<TSBizRemList> tsBizRemListModels = tsBizRemListService.selectbizRembizseq(bizSeq);

            for (TSBizRemList tsBizRemListModel : tsBizRemListModels) {
                List<TSWrit> tsWritModels = tsWritService.listTswrit(new TSWrit().setBizseq(bizSeq));

                for (TSWrit tsWritModel : tsWritModels) {
                    String path = null;
                    String workNoType = tsWritModel.getWritstype();
                    // 生成决定书附件
                    HashMap<String, Object> map = new HashMap<>();
                    String areaName = Constant.NM_REGION_CODE.get(tsWritModel.getAreaCode());
                    map.put("areaName", areaName);
                    map.put("writsNo", tsWritModel.getWritsno());
                    map.put("htmlContent", tsWritModel.getContent());
                    String approveDate = DateUtils.localDateFormat(tsBizRemListModel.getApprovaldate(), "yyyy年MM月dd日");
                    map.put("approveDate", approveDate);

                    // 无印章
                    if (WorkNoUtil.WORKNOTYPE_57.equals(workNoType) || WorkNoUtil.WORKNOTYPE_60.equals(workNoType)
                            || WorkNoUtil.WORKNOTYPE_62.equals(workNoType) || WorkNoUtil.WORKNOTYPE_63.equals(workNoType)) {

                        if ("0".equals(tsBizRemListModel.getIsAgreeRepair())) {
                            path = "static" + File.separator + "template" + File.separator + "noRepairDecNoSeal.docx";
                            String pdfPath = createPdfService.createPdfWithHtmlTemplate(tsBizRemListModel.getBizseq(), path, map);
                            if (StringUtils.isNotBlank(pdfPath)) {
                                tsWritModel.setPath(pdfPath);
                                tsWritService.updateById(tsWritModel);
                            }
                        } else if ("1".equals(tsBizRemListModel.getIsAgreeRepair())) {
                            path = "static" + File.separator + "template" + File.separator + "repairDecNoSeal.docx";
                            String pdfPath = createPdfService.createPdfWithHtmlTemplate(tsBizRemListModel.getBizseq(), path, map);
                            if (StringUtils.isNotBlank(pdfPath)) {
                                tsWritModel.setPath(pdfPath);
                                tsWritService.updateById(tsWritModel);
                            }
                        }
                    } else {
                        if ("0".equals(tsBizRemListModel.getIsAgreeRepair())) {
                            path = "static" + File.separator + "template" + File.separator + "noRepairDec.docx";
                        } else if ("1".equals(tsBizRemListModel.getIsAgreeRepair())) {
                            path = "static" + File.separator + "template" + File.separator + "repairDec.docx";
                        }
                        String pdfPath = createPdfService.createPdfWithHtmlTemplate(tsBizRemListModel.getBizseq(), path, map);
                        if (StringUtils.isNotBlank(pdfPath)) {
                            tsWritModel.setPath(pdfPath);
                            tsWritService.updateById(tsWritModel);
                        }
                    }
                }
            }
        }
        return RestResult.ok();
    }


    /**
     * 重新生成信用修复决定书(因XC服务器字体问题导致这些时间段生成的信用修复决定书都显示异常)
     * @author lwd
     * @since 2025年03月24日 9:56
     * @return
     */
    @GetMapping("again/certrm")
    public RestResult<?> pushTfCreditrm() {
        Set<String> bizSeqSet = tsWritService.lambdaQuery()
                .select(TSWrit::getBizseq)
                .in(TSWrit::getWritstype, "55", "56", "57", "58", "59", "60", "62", "63")
                .between(TSWrit::getCreatetime, "2025-03-20 00:00:00", "2025-03-24 20:00:00").list().stream().map(TSWrit::getBizseq).collect(Collectors.toSet());
        try {
            for (String bizSeq : bizSeqSet) {
                List<TSBizRemList> tsBizRemListModels = tsBizRemListService.selectbizRembizseq(bizSeq);
                List<TSTaskList> tsTaskList = taskListService.selectByBizSeqID(bizSeq);

                TSTaskList tsTaskList1 = tsTaskList.get(0);
                if (tsTaskList1 != null) {
                    if ("1".equals(tsTaskList1.getIsSmartProcessing())) {
                        for (TSBizRemList tsBizRemListModel : tsBizRemListModels) {
                            List<TSWrit> tsWritModels = tsWritService.listTswrit(new TSWrit().setBizseq(bizSeq));

                            for (TSWrit tsWritModel : tsWritModels) {
                                String path = null;
                                String workNoType = tsWritModel.getWritstype();
                                // 生成决定书附件
                                HashMap<String, Object> map = new HashMap<>();
                                String areaName = Constant.NM_REGION_CODE.get(tsWritModel.getAreaCode());
                                areaName = areaName.contains("广州市") ? areaName : ("广州市" + areaName);
                                map.put("areaName", areaName);
                                map.put("writsNo", tsWritModel.getWritsno());
                                map.put("htmlContent", tsWritModel.getContent());
                                String approveDate = DateUtils.localDateFormat(tsBizRemListModel.getApprovaldate(), "yyyy年MM月dd日");
                                map.put("approveDate", approveDate);

                                // 无印章
                                if (WorkNoUtil.WORKNOTYPE_57.equals(workNoType) || WorkNoUtil.WORKNOTYPE_60.equals(workNoType)
                                        || WorkNoUtil.WORKNOTYPE_62.equals(workNoType) || WorkNoUtil.WORKNOTYPE_63.equals(workNoType)) {

                                    if ("0".equals(tsBizRemListModel.getIsAgreeRepair())) {
                                        path = "static" + File.separator + "template" + File.separator + "noRepairDecNoSeal.docx";
                                        String pdfPath = createPdfService.createPdfWithHtmlTemplate(tsBizRemListModel.getBizseq(), path, map);
                                        if (StringUtils.isNotBlank(pdfPath)) {
                                            tsWritModel.setPath(pdfPath);
                                            tsWritService.updateById(tsWritModel);
                                        }
                                    } else if ("1".equals(tsBizRemListModel.getIsAgreeRepair())) {
                                        path = "static" + File.separator + "template" + File.separator + "repairDecNoSeal.docx";
                                        String pdfPath = createPdfService.createPdfWithHtmlTemplate(tsBizRemListModel.getBizseq(), path, map);
                                        if (StringUtils.isNotBlank(pdfPath)) {
                                            tsWritModel.setPath(pdfPath);
                                            tsWritService.updateById(tsWritModel);
                                        }
                                    }
                                } else {
                                    if ("0".equals(tsBizRemListModel.getIsAgreeRepair())) {
                                        path = "static" + File.separator + "template" + File.separator + "noRepairDec.docx";
                                    } else if ("1".equals(tsBizRemListModel.getIsAgreeRepair())) {
                                        path = "static" + File.separator + "template" + File.separator + "repairDec.docx";
                                    }
                                    String pdfPath = createPdfService.createPdfWithHtmlTemplate(tsBizRemListModel.getBizseq(), path, map);
                                    if (StringUtils.isNotBlank(pdfPath)) {
                                        tsWritModel.setPath(pdfPath);
                                        tsWritService.updateById(tsWritModel);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
        return RestResult.ok();
    }

    /**
     * 重新生成南沙批量吊销告知书（不是补缺，是全部重新生成）
     * @author lwd
     * @since 2025年03月24日 9:56
     * @return
     */
    @GetMapping("again/nstsWrit")
    public RestResult<?> pushNstsWrit(@RequestParam String bizSeq,@RequestParam String regorg) {

        try {
                List<TSWrit> tsWritList = tsWritService.lambdaQuery().eq(TSWrit::getBizseq, bizSeq)
                        .in(TSWrit::getWritstype, "32").list();
                TsCase caseDB = caseService.getByBizseq(bizSeq);
//                TsCase caseDB = caseService.getByBizseq("00FC1774-0FE4-B488-AF02-7E22C4995021");
                // 文书内容
                LambdaQueryWrapper<Tswrittemplate> wrapper = new LambdaQueryWrapper<>();
//                wrapper.eq(Tswrittemplate::getBizseq, "5cd3702d-63a3-4f3a-b7fd-fdb266f31771")
                wrapper.eq(Tswrittemplate::getBizseq, bizSeq)
                        .eq(Tswrittemplate::getIsTemplate, "0")
                        .eq(Tswrittemplate::getWritsType, WorkNoUtil.WORKNOTYPE_32);
                Tswrittemplate tswrittemplate = tswrittemplateService.getOne(wrapper);
                String content = tswrittemplate.getContent();
                if (tsWritList.size() > 0) {
                    for (int i = 0; i < tsWritList.size(); i++) {
                        TSWrit tsWrit = tsWritList.get(i);
                        EBaseinfo baseinfo = eBaseinfoService.getOneByPripid(tsWrit.getPripid());
                        Map<String, Object> map = new HashMap<>();
                        map.put("year", tsWrit.getCreatetime().getYear());
                        map.put("month", tsWrit.getCreatetime().getMonthValue());
                        map.put("day", tsWrit.getCreatetime().getDayOfMonth());
                        map.put("name", caseDB.getHandlerName() + "、" + caseDB.getAssistantName());
                        map.put("noAttach", "noAttach");
                        map.put("htmlContent", content);
                        map.put("writsno", tsWrit.getWritsno());
                        if (regorg.equals("440115") || regorg.equals("440110")) {
                            map.put("areaName", "广州市南沙区市场监督管理局");
                            map.put("addr", "广州市南沙区市场监督管理局");
                        }else if (regorg.equals("440101") || regorg.equals("440100")) {
                            map.put("areaName", "广州市");
                            map.put("addr", "广州市");
                        }else if (regorg.equals("440103")) {
                            map.put("areaName", "广州市荔湾区");
                            map.put("addr", "广州市荔湾区");
                        }else if (regorg.equals("440104")) {
                            map.put("areaName", "广州市越秀区");
                            map.put("addr", "广州市越秀区");
                        }else if (regorg.equals("440105")) {
                            map.put("areaName", "广州市海珠区");
                            map.put("addr", "广州市海珠区");
                        }else if (regorg.equals("440106")) {
                            map.put("areaName", "广州市天河区");
                            map.put("addr", "广州市天河区");
                        }else if (regorg.equals("440111")) {
                            map.put("areaName", "广州市白云区");
                            map.put("addr", "广州市白云区");
                        }else if (regorg.equals("440112")) {
                            map.put("areaName", "广州市黄埔区");
                            map.put("addr", "广州市黄埔区");
                        }else if (regorg.equals("440113") || regorg.equals("440126")) {
                            map.put("areaName", "广州市番禺区");
                            map.put("addr", "广州市番禺区");
                        }else if (regorg.equals("440114") || regorg.equals("440121")) {
                            map.put("areaName", "广州市花都区");
                            map.put("addr", "广州市花都区");
                        }else if (regorg.equals("440117") || regorg.equals("440122")) {
                            map.put("areaName", "广州市从化区");
                            map.put("addr", "广州市从化区");
                        }else if (regorg.equals("440118") || regorg.equals("440125")) {
                            map.put("areaName", "广州市增城区");
                            map.put("addr", "广州市增城区");
                        }
//                        map.put("areaName", "广州市南沙区市场监督管理局");
                        map.put("entname", baseinfo.getEntname());
//                        map.put("addr", "广州市南沙区市场监督管理局");
                        map.put("pripid", baseinfo.getPripid());
                        String fileName = baseinfo.getEntname() + "-听证告知书";
                        String path = "";
                        if (!regorg.equals("440115") && !regorg.equals("440110")) {
                            path = "static" + File.separator + "template" + File.separator + "hearingNotice.docx";
                        } else {
                            path = "static" + File.separator + "template" + File.separator + "hearingNoticeNS.docx";
                        }
                        // 标题
                        String title = path.substring(path.lastIndexOf(File.separator) + 1,path.lastIndexOf(Constant.DOT));
                        String ext = ".pdf";
                        String urlFileName = UUID.randomUUID().toString() + ext;

                        try {
                            ByteArrayOutputStream wordOs = new ByteArrayOutputStream(); // word输出流
                            String resource = CreateFileServiceImpl.class.getClassLoader().getResource(path).getPath();

                            //配置
                            // html内容处理
                            String htmlContent = map.get("htmlContent").toString();
                            Document htmldoc = Jsoup.parse(htmlContent);
                            Elements links = htmldoc.getElementsByTag("p");
                            ArrayList<Object> list = new ArrayList<>();
                            for (Element link : links) {
                                if(link.getElementsByAttributeValue("style","text-align:right;").size() > 0){
                                    Elements value = link.getElementsByAttributeValue("style", "text-align:right;");
                                    HashMap<String, Object> map2 = new HashMap<>();
                                    map2.put("rightContent",value.text().trim());
                                    list.add(map2);
                                }else if(link.getElementsByAttributeValue("style","text-align:left;").size() > 0){
                                    Elements value = link.getElementsByAttributeValue("style", "text-align:left;");
                                    HashMap<String, Object> map3 = new HashMap<>();
                                    map3.put("leftContent",value.text().trim());
                                    list.add(map3);
                                }else {
                                    HashMap<String, Object> map1 = new HashMap<>();
                                    map1.put("pragraph", link.text().trim());
                                    list.add(map1);
                                }
                            }
                            map.put("htmlContent",list);
                            String pdfPath = CommonConfig.getUploadPath() + File.separator + "BatchRevocation" + File.separator + bizSeq + File.separator + title + File.separator + urlFileName;
                            XWPFTemplate.compile(resource).render(map).write(wordOs);
                            PdfUtil.convertDocx2Pdf(wordOs,pdfPath);

                        } catch (Exception e) {
                            e.printStackTrace();
                            throw new BusinessException("批吊附件文书pdf上传失败");
                        }

                        if (StringUtils.isBlank(fileName)) {
                            fileName = urlFileName;
                        }else if(fileName.lastIndexOf(Constant.DOT) > -1){
                            fileName = fileName.substring(0, fileName.lastIndexOf(Constant.DOT)) + ext;
                        }else {
                            fileName = fileName + ext;
                        }
                        String tempPath = CommonConfig.getUploadPath() + File.separator + "BatchRevocation" + File.separator + bizSeq + File.separator + title + File.separator + urlFileName;

                        tsWrit.setPath(tempPath);
                        tsWritService.updateById(tsWrit);
                    }
                }

                List<BizRevEnt> bizRevEntList = bizRevEntService.lambdaQuery()
                        .eq(BizRevEnt::getBizseq, bizSeq).list();

                for (int i = 0; i < bizRevEntList.size(); i++) {
                    BizRevEnt bizRevEnt = bizRevEntList.get(i);

                    List<TSWrit> tsWritList1 = tsWritService.lambdaQuery()
                            .eq(TSWrit::getBizseq, bizRevEnt.getBizseq())
                            .eq(TSWrit::getPripid, bizRevEnt.getPripid())
                            .eq(TSWrit::getWritstype,"32")
                            .list();
                    if (tsWritList1.size() > 0) {
                        bizRevEnt.setHearingpublishdate(LocalDate.from(tsWritList1.get(0).getCreatetime()));
                        List<TSAttachment>  tsAttachmentList= attachmentService.lambdaQuery()
                                .eq(TSAttachment::getBizseq,tsWritList1.get(0).getBizseq())
                                .eq(TSAttachment::getPripid,tsWritList1.get(0).getPripid())
                                .eq(TSAttachment::getAttachtype,"13").list();
                        if (tsAttachmentList.size() > 0) {
                            TSAttachment tsAttachment = tsAttachmentList.get(0);
                            tsAttachment.setTemppath(tsWritList1.get(0).getPath());
                            attachmentService.updateById(tsAttachment);
                            bizRevEntService.updateById(bizRevEnt);
                        }
                    }
                }
//            看代码好像没啥问题，但是不知道哪一步有问题，tsAttachment的Path没更新到，用下面的语句更新吧
//            UPDATE tsattachment a
//            SET a.TEMPPATH = t.path
//            FROM TSWRIT t
//            WHERE a.BIZSEQ = t.BIZSEQ
//            AND a.pripid = t.pripid
//            AND t.BIZSEQ = 'aacab407-3370-4ba7-97b7-9b04972c21ba'
//            AND t.WRITSTYPE = '32'
//            AND a.ATTACHTYPE = '13'

        }catch (Exception e) {
            e.printStackTrace();
        }

        return RestResult.ok();
    }

    /**
     * 重新生成批量吊销处罚决定书（不是补缺，是全部重新生成）
     * @author lwd
     * @since 2025年05月08日 14:56
     * @return
     */
    @GetMapping("again/nscfWrit")
    public RestResult<?> pushNscfWrit(@RequestParam String bizSeq,@RequestParam String regorg) {
        try {
            List<TSWrit> tsWritList = tsWritService.lambdaQuery().eq(TSWrit::getBizseq, bizSeq)
                    .in(TSWrit::getWritstype, "33").list();

            // 文书内容
            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();

            if (tsWritList.size() > 0) {
                for (int i = 0; i < tsWritList.size(); i++) {
                    try { // 为每个循环添加独立的异常处理
                        TSWrit tsWrit = tsWritList.get(i);
                        EBaseinfo baseinfo = eBaseinfoService.getOneByPripid(tsWrit.getPripid());
                        Map<String, Object> map = new HashMap<>();
                        map.put("year", tsWrit.getCreatetime().getYear());
                        map.put("month", tsWrit.getCreatetime().getMonthValue());
                        map.put("day", tsWrit.getCreatetime().getDayOfMonth());
                        map.put("noAttach", "noAttach");
                        map.put("htmlContent", content);
                        map.put("entName", baseinfo.getEntname());
                        map.put("uniscid", baseinfo.getUniscid());
                        map.put("lerep", baseinfo.getLerep());
                        map.put("cerno", baseinfo.getCerno());
                        map.put("estdate", baseinfo.getEstdate());
                        map.put("entCerName", baseinfo.getEntname());
                        map.put("dom", baseinfo.getDom());
                        map.put("pripid", baseinfo.getPripid());
                        map.put("writsno", tsWrit.getWritsno());
//                        map.put("areaName", "广州市黄埔区");//注意只有南沙的是全称广州南沙区市场监督管理局
                        if (regorg.equals("440115") || regorg.equals("440110")) {
                            map.put("areaName", "广州市南沙区市场监督管理局");
                        }else if (regorg.equals("440101") || regorg.equals("440100")) {
                            map.put("areaName", "广州市");
                        }else if (regorg.equals("440103")) {
                            map.put("areaName", "广州市荔湾区");
                        }else if (regorg.equals("440104")) {
                            map.put("areaName", "广州市越秀区");
                        }else if (regorg.equals("440105")) {
                            map.put("areaName", "广州市海珠区");
                        }else if (regorg.equals("440106")) {
                            map.put("areaName", "广州市天河区");
                        }else if (regorg.equals("440111")) {
                            map.put("areaName", "广州市白云区");
                        }else if (regorg.equals("440112")) {
                            map.put("areaName", "广州市黄埔区");
                        }else if (regorg.equals("440113") || regorg.equals("440126")) {
                            map.put("areaName", "广州市番禺区");
                        }else if (regorg.equals("440114") || regorg.equals("440121")) {
                            map.put("areaName", "广州市花都区");
                        }else if (regorg.equals("440117") || regorg.equals("440122")) {
                            map.put("areaName", "广州市从化区");
                        }else if (regorg.equals("440118") || regorg.equals("440125")) {
                            map.put("areaName", "广州市增城区");
                        }

                        String fileName = baseinfo.getEntname() + "-处罚决定书";
                        String path = "";
                        if (!regorg.equals("440115") && !regorg.equals("440110")) {
                            path = "static" + File.separator + "template" + File.separator + "punishDecision.docx";
                        } else {
                            path = "static" + File.separator + "template" + File.separator + "punishDecisionNS.docx";
                        }

                        // 标题
                        String title = path.substring(path.lastIndexOf(File.separator) + 1,path.lastIndexOf(Constant.DOT));
                        String ext = ".pdf";
                        String urlFileName = UUID.randomUUID().toString() + ext;

                        try {
                            ByteArrayOutputStream wordOs = new ByteArrayOutputStream(); // word输出流
                            String resource = CreateFileServiceImpl.class.getClassLoader().getResource(path).getPath();

                            //配置
                            // html内容处理
                            String htmlContent = map.get("htmlContent").toString();
                            Document htmldoc = Jsoup.parse(htmlContent);
                            Elements links = htmldoc.getElementsByTag("p");
                            ArrayList<Object> list = new ArrayList<>();
                            for (Element link : links) {
                                    HashMap<String, Object> map1 = new HashMap<>();
                                    map1.put("pragraph", link.text().trim());
                                    list.add(map1);
                            }
                            map.put("htmlContent",list);
                            String pdfPath = CommonConfig.getUploadPath() + File.separator + "BatchRevocation" + File.separator + bizSeq + File.separator + title + File.separator + urlFileName;
                            XWPFTemplate.compile(resource).render(map).write(wordOs);
                            PdfUtil.convertDocx2Pdf(wordOs,pdfPath);

                        } catch (Exception e) {
                            e.printStackTrace();
                            throw new BusinessException("批吊附件文书pdf上传失败");
                        }

                        if (StringUtils.isBlank(fileName)) {
                            fileName = urlFileName;
                        }else if(fileName.lastIndexOf(Constant.DOT) > -1){
                            fileName = fileName.substring(0, fileName.lastIndexOf(Constant.DOT)) + ext;
                        }else {
                            fileName = fileName + ext;
                        }
                        String tempPath = CommonConfig.getUploadPath() + File.separator + "BatchRevocation" + File.separator + bizSeq + File.separator + title + File.separator + urlFileName;

                        tsWrit.setPath(tempPath);
                        tsWritService.updateById(tsWrit);
                    } catch (Exception e) {
                        e.printStackTrace();
                        // 记录错误日志，继续执行下一个循环
                        log.error("处理TSWrit时发生异常: {}", e.getMessage());
                    }
                }
            }

            List<BizRevEnt> bizRevEntList = bizRevEntService.lambdaQuery()
                    .eq(BizRevEnt::getBizseq,bizSeq).list();

            for (int i = 0; i < bizRevEntList.size(); i++) {
                try { // 为每个循环添加独立的异常处理
                    BizRevEnt bizRevEnt = bizRevEntList.get(i);
                    List<TSWrit> tsWritList1 = tsWritService.lambdaQuery()
                            .eq(TSWrit::getBizseq, bizRevEnt.getBizseq())
                            .eq(TSWrit::getPripid, bizRevEnt.getPripid())
                            .eq(TSWrit::getWritstype,"33")
                            .list();
                    if (tsWritList1.size() > 0) {
                        List<TSAttachment>  tsAttachmentList= attachmentService.lambdaQuery()
                                .eq(TSAttachment::getBizseq,tsWritList1.get(0).getBizseq())
                                .eq(TSAttachment::getPripid,tsWritList1.get(0).getPripid())
                                .eq(TSAttachment::getAttachtype,"14").list();
                        if (tsAttachmentList.size() > 0) {
                            TSAttachment tsAttachment = tsAttachmentList.get(0);
                            tsAttachment.setTemppath(tsWritList1.get(0).getPath());
                            attachmentService.updateById(tsAttachment);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    // 记录错误日志，继续执行下一个循环
                    log.error("处理BizRevEnt时发生异常: {}", e.getMessage());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return RestResult.ok();
    }

    /**
     * 获取浪潮用户数据
     * @author lwd
     * @since 2025年07月09日 15:46
     * @return
     */
    @GetMapping("hqlcusers")
    public RestResult<?> hqlcusers() {

//        itUserportalService.updateByUserName("肖茜敏");

        ForestResponse<LangChaoTokenDto> forestResponse = langChaoDoorApi.getClientCredentialsToken("end0eHlqZzo4ZGtqMXdzNw==","client_credentials");
        if (!forestResponse.isSuccess()) {
            log.error("浪潮获取token失败, status: {}", forestResponse.getStatusCode(), forestResponse.getException());
            throw new BusinessException(ResultCode.INTERFACE_OUTER_INVOKE_ERROR);
        }
        LangChaoTokenDto langChaoTokenDto = forestResponse.getResult();
        if (StringUtils.isBlank(langChaoTokenDto.getAccess_token())) {
            log.error("浪潮获取token为空, status: {}", forestResponse.getStatusCode(), forestResponse.getException());
            throw new BusinessException(ResultCode.INTERFACE_OUTER_INVOKE_ERROR);
        }

        // 2. 调用接口获取原始JSON响应
        ForestResponse<String> response = langChaoDoorApi.getAllUsers(
                langChaoTokenDto.getAccess_token(),
                "20000",
                "0"
        );

// 3. 检查接口调用是否成功（HTTP层面）
        if (!response.isSuccess()) {
            log.error("接口调用失败: {}", response.getContent());
            throw new BusinessException(ResultCode.INTERFACE_OUTER_INVOKE_ERROR);
        }

        // 4. 解析原始JSON字符串
        String jsonContent = response.getContent();
        if (jsonContent == null || jsonContent.isEmpty()) {
            log.error("接口返回空数据");
            throw new BusinessException(ResultCode.INTERFACE_OUTER_INVOKE_ERROR);
        }

        // 5. 提取data字段
        JSONObject jsonObject = JSONObject.parseObject(jsonContent);
        // 检查接口业务状态（success字段）
        if (!jsonObject.getBooleanValue("success")) {
            log.error("接口业务失败: {}", jsonObject.getString("msg"));
            throw new BusinessException(ResultCode.INTERFACE_OUTER_INVOKE_ERROR);
        }

        // 6. 将data字段转换为List<TUserportal>
        JSONArray dataArray = jsonObject.getJSONArray("data");
        if (dataArray == null || dataArray.isEmpty()) {
            log.info("没有获取到用户数据");
            return RestResult.ok();
        }
        List<TUserportal> userList = dataArray.toJavaList(TUserportal.class);

        // 7. 遍历处理用户数据
        for (TUserportal user : userList) {
            try {
                LambdaQueryWrapper<TUserportal> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(TUserportal::getId, user.getId());
                TUserportal existingUser = itUserportalService.getOne(wrapper);
                if (existingUser == null) {
                    itUserportalService.save(user);
                    itUserportalService.updateByUserName(user.getRealname());
                }
            } catch (Exception e) {
                log.error("处理用户[id={}]失败", user.getId(), e);
                // 跳过当前用户，继续处理下一个
                continue;
            }
        }


        return RestResult.ok();
    }

    /**
     * 泰富撤销吊销接口测试
     * @param uniscid 统一社会信用代码
     * @param entname 企业名称
     * @param handlerId 处理人ID
     * @param handlerName 处理人姓名
     * @return
     */
    @GetMapping("/revokeCancel")
    @ApiOperation("泰富撤销吊销接口测试")
    public RestResult<?> revokeCancel(
            @ApiParam("统一社会信用代码") @RequestParam(required = false) String uniscid,
            @ApiParam("企业名称") @RequestParam(required = false) String entname,
            @ApiParam("业务号") @RequestParam(required = false) String bizseq,
            @ApiParam("处理人ID") @RequestParam(required = false) String handlerId,
            @ApiParam("处理人姓名") @RequestParam(required = false) String handlerName) {

        try {
            // 创建CancelRevokelist对象
            CancelRevokelist cancelRevoke = new CancelRevokelist();
            Tsbizrevcancel tsbizrevcancelDB = tsbizrevcancelService.getOne(new LambdaQueryWrapper<Tsbizrevcancel>().eq(Tsbizrevcancel::getBizseq, bizseq));

            // 设置必要参数
            cancelRevoke.setPripid(tsbizrevcancelDB.getPripid());
            cancelRevoke.setUniscid(uniscid != null ? uniscid : "test_uniscid");
            cancelRevoke.setEntname(entname != null ? entname : "测试企业");
            cancelRevoke.setCancelapprdocno(tsbizrevcancelDB.getCancelwritsno());
            cancelRevoke.setCancelapprdept(tsbizrevcancelDB.getHandledecorg());
            cancelRevoke.setUsername("信用监管系统");
            cancelRevoke.setHandlerid(handlerId != null ? handlerId : "test_handler_id");
            cancelRevoke.setHandlername(handlerName != null ? handlerName : "测试处理人");
            cancelRevoke.setCancelapprdeptid(tsbizrevcancelDB.getRevcancelid());

            // 调用泰富撤销吊销接口
            String result = revokeAsyncTask.tfCancelRevocation(cancelRevoke);

            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("result", result);

            return RestResult.ok(resultMap);
        } catch (Exception e) {
            log.error("调用泰富撤销吊销接口失败", e);
            return RestResult.error(ResultCode.INTERFACE_OUTER_INVOKE_ERROR, "调用泰富撤销吊销接口失败: " + e.getMessage());
        }
    }

}
