package com.chinaweal.aiccs.aiccs.revoke.controller;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chinaweal.aiccs.aiccs.abnormal.entity.*;
import com.chinaweal.aiccs.aiccs.abnormal.entity.excel.EntExcel;
import com.chinaweal.aiccs.aiccs.abnormal.service.TSAttachmentService;
import com.chinaweal.aiccs.aiccs.abnormal.service.TSWritService;
import com.chinaweal.aiccs.aiccs.auditing.entity.TSOpinion;
import com.chinaweal.aiccs.aiccs.business.entity.BizCorrections;
import com.chinaweal.aiccs.aiccs.business.entity.TSTaskList;
import com.chinaweal.aiccs.aiccs.business.entity.TSTwfProcessNode;
import com.chinaweal.aiccs.aiccs.business.entity.dto.CorrectionsProcessDto;
import com.chinaweal.aiccs.aiccs.business.entity.dto.RevokeCorrectionsProcessDto;
import com.chinaweal.aiccs.aiccs.business.service.BizCorrectionsService;
import com.chinaweal.aiccs.aiccs.business.service.TSTaskListService;
import com.chinaweal.aiccs.aiccs.business.service.TSTwfProcessNodeService;
import com.chinaweal.aiccs.aiccs.business.service.WorkFlowService;
import com.chinaweal.aiccs.aiccs.punishment.util.ExcelIePortUtils;
import com.chinaweal.aiccs.aiccs.punishment.util.ExcelListener;
import com.chinaweal.aiccs.aiccs.revoke.entity.BizRevEnt;
import com.chinaweal.aiccs.aiccs.revoke.entity.Revokelist;
import com.chinaweal.aiccs.aiccs.revoke.entity.dto.RevBusDto;
import com.chinaweal.aiccs.aiccs.revoke.entity.dto.RevokeListDto;
import com.chinaweal.aiccs.aiccs.revoke.entity.excel.DisableListExcel;
import com.chinaweal.aiccs.aiccs.revoke.entity.excel.RevokeListExcel;
import com.chinaweal.aiccs.aiccs.revoke.service.*;
import com.chinaweal.aiccs.aiccs.system.entity.TRBaseCode;
import com.chinaweal.aiccs.aiccs.system.service.TRBaseCodeService;
import com.chinaweal.aiccs.common.base.controller.BaseController;
import com.chinaweal.aiccs.common.constant.BaseDataConstant;
import com.chinaweal.aiccs.common.constant.Constant;
import com.chinaweal.aiccs.common.util.*;
import com.chinaweal.aiccs.common.util.filestorage.FileStorageService;
import com.chinaweal.aiccs.config.CommonConfig;
import com.chinaweal.aiccs.org.entity.TUsers;
import com.chinaweal.aiccs.org.service.TUsersService;
import com.chinaweal.aiccs.redis.RedisService;
import com.chinaweal.aicorg.model.AICUser;
import com.chinaweal.youfool.framework.springboot.exception.custom.BusinessException;
import com.chinaweal.youfool.framework.springboot.mybatis.plus.page.PageRequestDto;
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.chinaweal.youfool.framework.sso.util.SSOUtil;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Lee
 * @since 2021-08-26
 */
@Slf4j
@RestController
@RequestMapping("/revokelist")
public class RevokelistController extends BaseController {

    @Autowired
    private RevokelistService revokelistService;
    @Autowired
    private TsbizrevlistService tsbizrevlistService;
    @Autowired
    private TswritscontentService tswritscontentService;
    @Autowired
    private TRBaseCodeService baseCodeService;
    @Resource
    private RevBusQueryService revBusQueryService;
    @Resource
    private BizRevEntService bizRevEntService;
    @Autowired
    private BizCorrectionsService bizCorrectionsService;
    @Resource
    private TSWritService writService;
    @Resource
    private TSTaskListService taskListService;
    @Resource
    private TSTwfProcessNodeService twfProcessNodeService;
    @Resource
    private WorkFlowService workFlowService;
    @Resource
    private TUsersService usersService;
    @Resource
    private FileStorageService fileStorageService;
    @Resource
    private TSAttachmentService attachmentService;
    @Autowired
    private RedisService redisService;

    private static final String REDIS_KEY_ENABLE_PREFIX = "revoke:corrections:enable:";
    private static final String REDIS_KEY_DISABLE_PREFIX = "revoke:corrections:disable:";
    /**
     * 批吊业务条件查询
     *
     * @return
     */
    @PostMapping(value = "/revBusQuery")
    public RestResult<?> revBusQueryByCondition(@RequestBody PageRequestDto pageRequestDto, HttpServletRequest request) {
        // 封装分页参数
        RevBusDto revBusListParam = new RevBusDto();
        Map<String, Object> customParamMap = pageRequestDto.getCustomParamMap();

        if (customParamMap != null && customParamMap.get("orgNumber") != null) {
            if (!StringUtils.isNotBlank(customParamMap.get("orgNumber").toString())) {
                AICUser user = SSOUtil.getUser();
                String userOrg = user.getRegionID();
                customParamMap.put("orgNumber", userOrg);
            }
        }

        switch (customParamMap.get("orgNumber").toString()) {
            case "440126" :
                customParamMap.put("otherNumber", "440113");
                break;
            default:
        }

        if (customParamMap != null && customParamMap.get("UNISCIDORREGNO") != null) {
            if (StringUtils.isNotBlank(customParamMap.get("UNISCIDORREGNO").toString())) {
                String uscc = customParamMap.get("UNISCIDORREGNO").toString();
                if (StringUtils.isUscc(uscc)) {
                    customParamMap.put("UNISCID", uscc);
                } else {
                    customParamMap.put("REGNO", uscc);
                }
            }
        }

        if (customParamMap != null && customParamMap.get("setTimeDate") != null) {
            Object datas = customParamMap.get("setTimeDate");
            if (datas instanceof List) {
                List<String> list = (List<String>) datas;
                customParamMap.put("setTimeOn", list.get(0));
                customParamMap.put("setTimeEnd", list.get(1));
            }
        }
        if (customParamMap != null && customParamMap.get("punishTime") != null) {
            Object datas = customParamMap.get("punishTime");
            if (datas instanceof List) {
                List<String> list = (List<String>) datas;
                customParamMap.put("punishTimeOn", list.get(0));
                customParamMap.put("punishTimeEnd", list.get(1));
            }
        }

        IPage<RevBusDto> page;
        page = revBusQueryService.searchByCondition(new Page<>(pageRequestDto.getCurPage(), pageRequestDto.getPageSize()), customParamMap);

        //汇总每个案件里主体业务状态的数量
        List<RevBusDto> list = page.getRecords();
        for (RevBusDto l : list) {
            // 查询已立案数
            LambdaQueryWrapper<BizRevEnt> registerWrapper = new LambdaQueryWrapper<>();
            registerWrapper.eq(BizRevEnt::getBizseq, l.getBIZSEQID());
            registerWrapper.and(i -> i.isNull(BizRevEnt::getRemovetime).or().gt(BizRevEnt::getRemovetime, l.getSetTime()));
            int isRegisterNum = bizRevEntService.count(registerWrapper);
            l.setIsRegisterNum(isRegisterNum);

            //已吊销数
            LambdaQueryWrapper<BizRevEnt> revokeWrapper = new LambdaQueryWrapper<>();
            revokeWrapper.eq(BizRevEnt::getBizseq, l.getBIZSEQID());
            revokeWrapper.eq(BizRevEnt::getIsdecisionpublish, '1');
            int isRevokeNum = bizRevEntService.count(revokeWrapper);
            l.setIsRevokeNum(isRevokeNum);

            //撤销吊销数
            int otherNum = revBusQueryService.countOther(l.getBIZSEQID());
            l.setOtherNum(otherNum);
        }

        /*增加合计行-start*/
        //分页总页数
        int pageCount = page.getTotal() != 0?(int)(page.getTotal() + pageRequestDto.getPageSize() - 1) / pageRequestDto.getPageSize() : 1;
        if(page.getTotal() != 0 && pageRequestDto.getCurPage() == pageCount){     //判断是否属于最后一页
            List<RevBusDto> revBusDtos = revBusQueryService.searchByConditionAll(customParamMap);
            RevBusDto dto = new RevBusDto();
            dto.setCurrentNodeOrBizStatus("合计");
            int isRegisterNum = 0;
            int isRevokeNum = 0;
            int otherNum = 0;
            for(RevBusDto revBusDto : revBusDtos){
                // 查询已立案数
                LambdaQueryWrapper<BizRevEnt> registerWrapper = new LambdaQueryWrapper<>();
                registerWrapper.eq(BizRevEnt::getBizseq, revBusDto.getBIZSEQID());
                registerWrapper.and(i -> i.isNull(BizRevEnt::getRemovetime).or().gt(BizRevEnt::getRemovetime, revBusDto.getSetTime()));
                isRegisterNum += bizRevEntService.count(registerWrapper);

                //已吊销数
                LambdaQueryWrapper<BizRevEnt> revokeWrapper = new LambdaQueryWrapper<>();
                revokeWrapper.eq(BizRevEnt::getBizseq, revBusDto.getBIZSEQID());
                revokeWrapper.eq(BizRevEnt::getIsdecisionpublish, '1');
                isRevokeNum += bizRevEntService.count(revokeWrapper);

                //撤销吊销数
                otherNum += revBusQueryService.countOther(revBusDto.getBIZSEQID());
            }
            dto.setIsRegisterNum(isRegisterNum);    // 查询已立案数
            dto.setIsRevokeNum(isRevokeNum);        //已吊销数
            dto.setOtherNum(otherNum);              //撤销吊销数
            page.getRecords().add(dto);
        }
        /*增加合计行-end*/

        return RestResult.ok(page);
    }

    /**
     * 已吊销主体分页
     *
     * @param pageRequestDto
     * @param request
     * @return
     */
    @PostMapping("revokeListPage")
    public RestResult<?> revokeListPage(@RequestBody PageRequestDto pageRequestDto, HttpServletRequest request) {
        AICUser curUser = getLoginUser(request);
        Map<String, Object> customParamMap = pageRequestDto.getCustomParamMap();

        if(MapUtils.isNotEmpty(customParamMap)){
            // 搜索统一码和注册号
            String searchCode = StringUtils.tranObject(customParamMap.get("searchCode"));
            //判断入参为统一码还是注册号
            if (StringUtils.isNotBlank(searchCode)) {
                if (StringUtils.isUscc(searchCode)) {
                    customParamMap.put("uniscid",searchCode);
                } else {
                    customParamMap.put("regno",searchCode);
                }
            }
        }

        IPage<RevokeListDto> page = revokelistService.selectRevokeListPage(new Page<>(pageRequestDto.getCurPage(), pageRequestDto.getPageSize()), customParamMap);

        if(CollectionUtils.isNotEmpty(page.getRecords())){
            // 封装吊销原因中文
            Map<String, TRBaseCode> causeMap = baseCodeService.getBaseCodeMapFormCache("DX01");
            for (RevokeListDto record : page.getRecords()) {
                TRBaseCode code = causeMap.get(record.getRevokeRea());
                if(code != null){
                    record.setRevokeReaCn(code.getName());
                }
            }
        }
        return RestResult.ok(page);

    }

    /**
     * 批吊勘误流程待办创建
     * @author ymc
     * @date 2023年6月26日 15:42
     * @param listId
     * @param request
     * @return
     */
    @ApiOperation("批吊勘误流程待办创建")
    @PostMapping("createTask")
    @Transactional(rollbackFor = Exception.class)
    public RestResult<?> createTask(@ApiParam("批吊id") String listId, HttpServletRequest request) {
        // 参数校验
        AssertUtils.isNotBlank(listId);

        Revokelist revokelist = revokelistService.getById(listId);
        if (revokelist == null) return RestResult.error(ResultCode.PARAM_IS_INVALID);

        BizRevEnt bizRevEnt = bizRevEntService.getById(listId);
        if (bizRevEnt == null) return RestResult.error(ResultCode.PARAM_IS_INVALID);

        // 在办业务验证
        int existsBus = bizCorrectionsService.count(new LambdaQueryWrapper<BizCorrections>()
                .eq(BizCorrections::getBusId, revokelist.getRevlistid())
                .eq(BizCorrections::getState, Constant.TRUE_1_STR));
        if (existsBus > 0) {
            return RestResult.error(ResultCode.DATA_ALREADY_EXISTED,"该信息已发起过勘误流程");
        }

        AICUser curUser = getLoginUser(request);

        String bizseq = UUID.randomUUID().toString();
        BizCorrections bizCorrections = new BizCorrections()
                .setBizseq(bizseq)
                .setBustype("2")
                .setBusId(listId)
                .setPripid(bizRevEnt.getPripid())
                .setRegno(bizRevEnt.getRegno())
                .setUniscid(bizRevEnt.getUniscid())
                .setEntType(bizRevEnt.getEnttype())
                .setState(Constant.TRUE_1_STR);

        boolean save = bizCorrectionsService.save(bizCorrections);
        if(!save){
            throw new BusinessException("发起勘误流程失败");
        }

        // 创建勘误
        TSTaskList taskListModel = new TSTaskList();
        taskListModel.setBizseqid(bizseq);
        taskListModel.setBustype(BaseDataConstant.CORRECTIONS_REVOKE_BIZ);// 勘误流程
        taskListModel.setBusname(revokelist.getEntname());
        bizCorrectionsService.createTask(curUser, taskListModel, bizCorrections);
        if (StringUtils.isNotBlank(taskListModel.getTasklistid())) {
            Map<String, Object> result = new HashMap<>();
            result.put("tasklistid", taskListModel.getTasklistid());
            result.put("bizseq", bizseq);
            result.put("workflowId", taskListModel.getWorkflowid());
            return RestResult.ok(result);
        }

        throw new BusinessException("发起勘误流程失败");
    }

    /**
     * 批量批吊勘误流程待办创建
     * @author ymc
     * @date 2023年6月26日 15:42
     * @param enableListId
     * @param request
     * @return
     */
    @ApiOperation("批吊勘误流程待办创建")
    @PostMapping("createBatchTask")
    @Transactional(rollbackFor = Exception.class)
    public RestResult<?> createBatchTask(@ApiParam("数据id") String enableListId, HttpServletRequest request) {
        // 参数校验
        AssertUtils.isNotBlank(enableListId);
        String json = redisService.get(REDIS_KEY_ENABLE_PREFIX + enableListId);
        if (StringUtils.isBlank(json)) return RestResult.error(ResultCode.PARAM_IS_INVALID);
        List<Revokelist> enableListArray = JSON.parseArray(json, Revokelist.class);
        HashSet<Revokelist> enableList = new HashSet<>(enableListArray);
        if (enableList.size() == 0) return RestResult.error(ResultCode.PARAM_IS_INVALID);
        String bizseq = UUID.randomUUID().toString();
        String name = "";
        List<BizCorrections> correctionsList = new ArrayList<>();
        for(Revokelist revokelist : enableList){
            if (revokelist == null) return RestResult.error(ResultCode.PARAM_IS_INVALID);

            BizRevEnt bizRevEnt = bizRevEntService.getById(revokelist.getRevlistid());
            if (bizRevEnt == null) return RestResult.error(ResultCode.PARAM_IS_INVALID);

            // 在办业务验证
            int existsBus = bizCorrectionsService.count(new LambdaQueryWrapper<BizCorrections>()
                    .eq(BizCorrections::getBusId, revokelist.getRevlistid())
                    .eq(BizCorrections::getState, Constant.TRUE_1_STR));
            if (existsBus > 0) {
                return RestResult.error(ResultCode.DATA_ALREADY_EXISTED,"列表中存在正在勘误中的流程");
            }
            BizCorrections bizCorrections = new BizCorrections()
                    .setBizseq(bizseq)
                    .setBustype("2")
                    .setBusId(revokelist.getRevlistid())
                    .setPripid(bizRevEnt.getPripid())
                    .setRegno(bizRevEnt.getRegno())
                    .setUniscid(bizRevEnt.getUniscid())
                    .setEntType(bizRevEnt.getEnttype())
                    .setState(Constant.TRUE_1_STR);

            boolean save = bizCorrectionsService.save(bizCorrections);
            correctionsList.add(bizCorrections);
            if(StringUtils.isEmpty(name)){
                name = revokelist.getEntname();
            }
            if(!save){
                throw new BusinessException("发起勘误流程失败");
            }
        }
        //业务名称 规则：关于+第一家公司名称+等+XX家+的批量批吊勘误
        String busname = "关于" + name + "等" +
                enableList.size() + "家的批量批吊勘误";
        // 创建勘误
        TSTaskList taskListModel = new TSTaskList();
        taskListModel.setBizseqid(bizseq);
        taskListModel.setBustype(BaseDataConstant.CORRECTIONS_REVOKE_BIZ);// 勘误流程
        taskListModel.setBusname(busname);
        AICUser curUser = getLoginUser(request);
        BizCorrections[] bizCorrections = correctionsList.toArray(new BizCorrections[correctionsList.size()]);
        bizCorrectionsService.createTask(curUser, taskListModel, bizCorrections);
        if (StringUtils.isNotBlank(taskListModel.getTasklistid())) {
            Map<String, Object> result = new HashMap<>();
            result.put("tasklistid", taskListModel.getTasklistid());
            result.put("bizseq", bizseq);
            result.put("workflowId", taskListModel.getWorkflowid());
            return RestResult.ok(result);
        }

        throw new BusinessException("发起勘误流程失败");
    }
    /**
     * 批量批吊勘误excel文件导入解析
     *
     * @param file 文件
     * @return 查询结果
     */
    @Transactional
    @ApiOperation("excel文件查询参数解析")
    @PostMapping("fileParamExplain")
    public RestResult<?> fileParamExplainByNB(HttpServletRequest request, @ApiParam("上传的excel文件") MultipartFile file) {
        AssertUtils.isNotNull(file);
        //保存文件至服务器
        // 获得上传目录
        AICUser curUser = getLoginUser(request);
        if (curUser == null) {
            throw new BusinessException("登录超时，请重新登录");
        }
        String bizseq = UUID.randomUUID().toString();
        String oldFileName = file.getOriginalFilename();
        String ext = StringUtils.isNotBlank(oldFileName) && oldFileName.lastIndexOf(Constant.DOT) > -1 ? oldFileName.substring(oldFileName.lastIndexOf(Constant.DOT)) : StringUtils.EMPTY;
        String filePath = curUser.getPrimaryKey() + File.separator + bizseq + File.separator + oldFileName;
        try (InputStream is = file.getInputStream()) {
            fileStorageService.writeFromStream(CommonConfig.getUploadPath() + File.separator + filePath, is);
        } catch (Exception e) {
            log.error("上传出错", e);
            throw new RuntimeException(e.getMessage());
        }
        TSAttachment tsAttachmentModel = new TSAttachment();
        tsAttachmentModel.setBizseq(bizseq);
        tsAttachmentModel.setFileext(ext);
        tsAttachmentModel.setFilename(oldFileName);
        tsAttachmentModel.setTemppath(filePath);
        tsAttachmentModel.setUploaddate(LocalDate.now());
        tsAttachmentModel.setUserid(curUser.getPrimaryKey());
        tsAttachmentModel.setUsername(curUser.getName());
        tsAttachmentModel.setAttachtype("1");  //1代表批量吊销勘误上传的主体信息
        attachmentService.save(tsAttachmentModel);
        // 读取excel数据
        List<EntExcel> entDtos;
        try {
            ExcelListener excelListener = ExcelIePortUtils.getExcelListener(file, new EntExcel(), 1, 1);
            if(excelListener == null)  throw new BusinessException("文件数据读取出错");
            Object objList = excelListener.getDatas();
            entDtos = (List<EntExcel>) objList;
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException("文件数据读取出错");
        }
        HashSet<Revokelist> enableList = new HashSet<>();
        ArrayList<DisableListExcel> disableList = new ArrayList<>();//不可导
        for (EntExcel entDto : entDtos) {
            LambdaQueryWrapper<Revokelist> wrapper = new LambdaQueryWrapper<>();
            Revokelist revokeListModel = new Revokelist();
            if (entDto.getUniscid() != null) {
                revokeListModel.setUniscid(entDto.getUniscid().trim());
            }
            if (entDto.getRegno() != null) {
                revokeListModel.setRegno(entDto.getRegno().trim());
            }
            if (entDto.getEntname() != null) {
                revokeListModel.setEntname(entDto.getEntname().trim());
            }

            wrapper.select(Revokelist::getRevlistid,Revokelist::getEntname,Revokelist::getUniscid,Revokelist::getRegno,Revokelist::getPunishOrgCn);
            if (StringUtils.isNotBlank(revokeListModel.getUniscid())) {
                wrapper.eq(Revokelist::getUniscid, revokeListModel.getUniscid());
            }
            if (StringUtils.isNotBlank(revokeListModel.getRegno())) {
                wrapper.eq(Revokelist::getRegno, revokeListModel.getRegno());
            }
            if (StringUtils.isNotBlank(revokeListModel.getEntname())) {
                wrapper.eq(Revokelist::getEntname, revokeListModel.getEntname());
                // 用名称查主体的时候，可能会出现同名的情况
                List<Revokelist> list = revokelistService.list(wrapper);
                if (list.size() > 1) {// 多家同名的时候，返回不可导原因“主体名称重名，请填写准确的统一码或注册号”
                    DisableListExcel disableListExcel = new DisableListExcel();
                    disableListExcel.setEntname(revokeListModel.getEntname());
                    disableListExcel.setReason("主体名称重名，请填写准确的统一码或注册号");
                    disableList.add(disableListExcel);
                    continue;
                }
            }

            // 避免wrapper没有筛选条件导致全表查询
            if (wrapper.getExpression().getNormal().size() == 0) {
                continue;
            }
            wrapper.orderByDesc(Revokelist::getLauptime);
            List<Revokelist> revokelistList = revokelistService.list(wrapper);  //避免表里有多条数据
            if (revokelistList != null && revokelistList.size() != 0) {
                Revokelist revokelist = revokelistList.get(0);
                if (StringUtils.isEmpty(revokelist.getPunishOrgCn()) || !curUser.getOrgName().equals(revokelist.getPunishOrgCn())) {
                    String reason = "只能勘误本单位的吊销处罚记录";
                    DisableListExcel disableListExcel = new DisableListExcel();
                    disableListExcel.setReason(reason);
                    disableListExcel.setEntname(revokelist.getEntname());
                    disableListExcel.setUniscid(revokelist.getUniscid());
                    disableListExcel.setRegno(revokelist.getRegno());
                    disableList.add(disableListExcel);
                }else {
                    // 在办业务验证
                    int existsBus = bizCorrectionsService.count(new LambdaQueryWrapper<BizCorrections>()
                            .eq(BizCorrections::getBusId, revokelist.getRevlistid())
                            .eq(BizCorrections::getState, Constant.TRUE_1_STR));
                    if (existsBus > 0) {
                        String reason = "该信息已经发起勘误流程";
                        DisableListExcel disableListExcel = new DisableListExcel();
                        disableListExcel.setReason(reason);
                        disableListExcel.setEntname(revokelist.getEntname());
                        disableListExcel.setUniscid(revokelist.getUniscid());
                        disableListExcel.setRegno(revokelist.getRegno());
                        disableList.add(disableListExcel);
                    }else {
                        enableList.add(revokelist);
                    }

                }

            } else {
                DisableListExcel disableListExcel = new DisableListExcel();
                disableListExcel.setEntname(revokeListModel.getEntname());
                disableListExcel.setUniscid(revokeListModel.getUniscid());
                disableListExcel.setRegno(revokeListModel.getRegno());
                disableListExcel.setReason("主体信息有误，未找到吊销处罚记录");
                disableList.add(disableListExcel);
            }
        }

        HashMap<String, Object> resultMap = new HashMap<>();
        String enableListId = UUID.randomUUID().toString();
        String disableListId = UUID.randomUUID().toString();
        resultMap.put("enableListId", enableListId);
        resultMap.put("disableListId", disableListId);
        redisService.set(REDIS_KEY_ENABLE_PREFIX + enableListId, JSON.toJSONString(enableList), 15 * 60);
        redisService.set(REDIS_KEY_DISABLE_PREFIX + disableListId, JSON.toJSONString(disableList), 15 * 60);

        resultMap.put("enableSize", enableList.size());
        resultMap.put("disableSize", disableList.size());
        resultMap.put("bizseq", bizseq);

        return RestResult.ok(resultMap);
    }

    /**
     * 批量吊销勘误错误清单导出
     * @param request
     * @param response
     * @param disableListId
     * @return
     */
    @GetMapping("failEntExport")
    public RestResult<?> failEntAddressExport(HttpServletRequest request, HttpServletResponse response, String disableListId){
        AssertUtils.isNotEmpty(disableListId);
        String json = redisService.get(REDIS_KEY_DISABLE_PREFIX + disableListId);
        if (StringUtils.isBlank(json)) return RestResult.error(ResultCode.PARAM_IS_INVALID);
        List<DisableListExcel> list = JSON.parseArray(json, DisableListExcel.class);

        String fileName = "批量吊销勘误错误清单.xlsx";
        attachmentService.exportExcel2(request, response, fileName, list, DisableListExcel.class);
        return OK;
    }

    /**
     * 批量批吊勘误主体名单导出Excel
     *
     * @return
     */
    @GetMapping("exportEntList")
    public RestResult<?> exportEntList(String bizseq,HttpServletRequest request, HttpServletResponse response) {
        AssertUtils.isNotBlank(bizseq);
        AssertUtils.isNotBlank(bizseq);

        // 查询列异勘误业务信息
        List<BizCorrections> bizCorrectionsPage = bizCorrectionsService.list(new LambdaQueryWrapper<BizCorrections>().eq(BizCorrections::getBizseq, bizseq));
        if(bizCorrectionsPage == null || bizCorrectionsPage.size() == 0) return RestResult.error(ResultCode.DATA_NONE,"未找到勘误业务信息");
        List<RevokeListExcel> revokeInfoList = new ArrayList<>();
        // 查询列异勘误业务信息
        for(BizCorrections bizCorrections : bizCorrectionsPage){
            Revokelist revokeInfo = revokelistService.getById(bizCorrections.getBusId());
            TSWrit tsWrit = writService.getById(revokeInfo.getWritsid());
            if(tsWrit != null){
                revokeInfo.setWritsno(tsWrit.getWritsno());
                revokeInfo.setContent(tsWrit.getContent().replace("<p>", "").replace("</p>", "。").replace("：。", "："));
            }
            RevokeListExcel revokeListExcel = new RevokeListExcel();
            BeanUtils.copyProperties(revokeInfo, revokeListExcel);
            String format = DateUtils.localDateFormat(revokeInfo.getRevokedate().toLocalDate(), "yyyy年MM月dd日");
            revokeListExcel.setRevokedate(format);
            String uscc = StringUtils.isBlank(revokeInfo.getUniscid())?revokeInfo.getRegno() : revokeInfo.getUniscid();
            revokeListExcel.setUscc(uscc);
            revokeInfoList.add(revokeListExcel);
        }
        String fileName = "批吊勘误主体名单清单.xlsx";
        attachmentService.exportExcel2(request, response, fileName, revokeInfoList, RevokeListExcel.class);
        return OK;
    }

    /**
     * 获取业务详情
     * @author ymc
     * @date 2023年6月27日 15:28
     * @param bizseq
     * @return
     */
    @ApiOperation("获取业务详情")
    @GetMapping("detail")
    public RestResult<?> getCorrectionsDetail(@ApiParam("业务号") String bizseq, int current, int size) {
        AssertUtils.isNotBlank(bizseq);
        // 构建分页对象，指定当前页码和每页显示的记录数
        Page<BizCorrections> page = new Page<>(current, size);
        // 查询列异勘误业务信息
        Page<BizCorrections> bizCorrectionsPage = bizCorrectionsService.page(page, new LambdaQueryWrapper<BizCorrections>().eq(BizCorrections::getBizseq, bizseq));
        if(bizCorrectionsPage == null || bizCorrectionsPage.getRecords().size() == 0) return RestResult.error(ResultCode.DATA_NONE,"未找到勘误业务信息");
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("detail", bizCorrectionsPage.getRecords().get(0));

        List<Revokelist> revokeInfoList = new ArrayList<>();
        // 查询列异勘误业务信息
        for(BizCorrections bizCorrections : bizCorrectionsPage.getRecords()){
            Revokelist revokeInfo = revokelistService.getById(bizCorrections.getBusId());
            TSWrit tsWrit = writService.getById(revokeInfo.getWritsid());
            if(tsWrit != null){
                revokeInfo.setWritsno(tsWrit.getWritsno());
                revokeInfo.setContent(tsWrit.getContent().replace("<p>", "").replace("</p>", "。").replace("：。", "："));
            }
            revokeInfoList.add(revokeInfo);
        }
        resultMap.put("revokeInfoList", revokeInfoList);
        resultMap.put("totals", bizCorrectionsPage.getTotal());

        // 查询待办信息
        TSTaskList taskList = taskListService.getOne(new LambdaQueryWrapper<TSTaskList>().eq(TSTaskList::getBizseqid, bizseq));
        resultMap.put("taskList", taskList);

        // 查询流程节点信息
        List<TSTwfProcessNode> node = twfProcessNodeService.list(new LambdaQueryWrapper<TSTwfProcessNode>()
                .eq(TSTwfProcessNode::getProcessid, taskList.getWorkflowid()).orderByDesc(TSTwfProcessNode::getLauptime));
        resultMap.put("nodes", node);
        return RestResult.ok(resultMap);
    }

    /**
     * 进入下一个勘误流程
     * @author ymc
     * @date 2023年6月27日 19:27
     * @param processDto
     * @param request
     * @return
     */
    @PostMapping("nextRevokeCorrectionsProcess")
    @ApiOperation("进入下一个勘误流程")
    @Transactional(rollbackFor = Exception.class)
    public RestResult<?> nextProcess(@ApiParam("流转信息") RevokeCorrectionsProcessDto processDto, HttpServletRequest request) {
        // 参数校验
        AssertUtils.isNotNull(processDto);
        AssertUtils.isNotBlank(processDto.getNextNodeId(), processDto.getBizseq(),
                processDto.getNextUserIds(), processDto.getNextUserNames(),
                processDto.getOpiniontype(), processDto.getCurNodeId(),
                processDto.getOpinioncontent(), processDto.getTasklistid(), processDto.getWorkflowId());

        AICUser curUser = getLoginUser(request);

        // 读取必须参数
        String link = String.format("%s_%s", processDto.getCurNodeId(), processDto.getNextNodeId());
        String[] ids = null;
        String[] names = null;
        if ("approvelist_handleFeedback".equals(link) || "handleFeedback_feedbackEnter".equals(link)) {
            String userId = workFlowService.findLastTwfprocessnodeByProcessidAndNodename(processDto.getWorkflowId(), processDto.getCurNodeId(), processDto.getNextNodeId());
            if (StringUtils.isEmpty(userId)) {
                return RestResult.error(ResultCode.DATA_NONE);
            }

            TUsers userInfo = usersService.selectTusersById(userId);
            ids = new String[]{userInfo.getUserid()};
            names = new String[]{userInfo.getRealname()};
        } else {
            ids = StringUtils.split(processDto.getNextUserIds(), ",");
            names = StringUtils.split(processDto.getNextUserNames(), ",");
        }
        TSTaskList taskListModel = taskListService.selectByTasklistID(processDto.getTasklistid());
        TSOpinion opinionModel = new TSOpinion()
                .setHandler(curUser.getName())
                .setHandlerid(curUser.getPrimaryKey())
                .setWorkflowid(taskListModel.getWorkflowid())
                .setOpiniontype(processDto.getOpiniontype())
                .setHandledate(LocalDateTime.now())
                .setOpinioncontent(processDto.getOpinioncontent());
        List<BizCorrections> correctionsList = bizCorrectionsService.list(new LambdaQueryWrapper<BizCorrections>().eq(BizCorrections::getBizseq, taskListModel.getBizseqid()));
        // 处理勘误数据 -- 经办环节
        if ("feedbackEnter".equals(processDto.getCurNodeId())) {
            for (BizCorrections corrections : correctionsList){
                // 勘误吊销决定日期
                if (processDto.getRevokeDecDate() != null) {
                    corrections.setRevokeDecDate(processDto.getRevokeDecDate().atStartOfDay());
                }
                // 勘误听证公告日期
                if (processDto.getRevokeHearDate() != null) {
                    corrections.setRevokeHearDate(processDto.getRevokeHearDate().atStartOfDay());
                }
            }
        }
        BizCorrections[] bizCorrections = correctionsList.toArray(new BizCorrections[correctionsList.size()]);
        // 处理流程
        bizCorrectionsService.nextProcess(curUser, taskListModel, opinionModel, processDto.getNextNodeId(), ids, names, bizCorrections);
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("bizseq", taskListModel.getBizseqid());
        resultMap.put("workflowid", taskListModel.getWorkflowid());
        resultMap.put("nextNodeID", processDto.getNextNodeId());
        resultMap.put("tasklistid", processDto.getTasklistid());

        return RestResult.ok(resultMap);
    }

}

