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


import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
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.EBaseinfo;
import com.chinaweal.aiccs.aiccs.abnormal.entity.TSAttachment;
import com.chinaweal.aiccs.aiccs.abnormal.entity.TSWrit;
import com.chinaweal.aiccs.aiccs.abnormal.entity.excel.EntExcel;
import com.chinaweal.aiccs.aiccs.abnormal.service.*;
import com.chinaweal.aiccs.aiccs.annual.service.NoannualreportService;
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.TSTwfProcessNode;
import com.chinaweal.aiccs.aiccs.business.entity.dto.TaskListUnionDto;
import com.chinaweal.aiccs.aiccs.business.service.WorkFlowService;
import com.chinaweal.aiccs.aiccs.dict.entity.CmsDictCode;
import com.chinaweal.aiccs.aiccs.dict.service.CmsDictCodeService;
import com.chinaweal.aiccs.aiccs.entbase.entity.TREntPriseType;
import com.chinaweal.aiccs.aiccs.entbase.service.TREntPriseTypeService;
import com.chinaweal.aiccs.aiccs.market.service.AreaSliceService;
import com.chinaweal.aiccs.aiccs.market.service.ITSUsualInspectService;
import com.chinaweal.aiccs.aiccs.punishment.util.BusTridMakeUtil;
import com.chinaweal.aiccs.aiccs.punishment.util.ExcelIePortUtils;
import com.chinaweal.aiccs.aiccs.punishment.util.ExcelListener;
import com.chinaweal.aiccs.aiccs.revoke.Vo.DisableListVo;
import com.chinaweal.aiccs.aiccs.revoke.Vo.EnableListAndCheckExcel;
import com.chinaweal.aiccs.aiccs.revoke.Vo.EnableListAndCheckVo;
import com.chinaweal.aiccs.aiccs.revoke.Vo.TsbizrevlistExcelVo;
import com.chinaweal.aiccs.aiccs.revoke.entity.*;
import com.chinaweal.aiccs.aiccs.revoke.entity.dto.*;
import com.chinaweal.aiccs.aiccs.revoke.service.*;
import com.chinaweal.aiccs.aiccs.security.dto.PenaltyCaseInfoQueryDTO;
import com.chinaweal.aiccs.aiccs.security.entity.PenaltyCaseInfo;
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.CommonConstants;
import com.chinaweal.aiccs.common.constant.Constant;
import com.chinaweal.aiccs.common.constant.IndustryConstant;
import com.chinaweal.aiccs.common.util.ConstantsUtil;
import com.chinaweal.aiccs.common.util.DateUtils;
import com.chinaweal.aiccs.common.util.StringUtils;
import com.chinaweal.aiccs.common.util.WorkNoUtil;
import com.chinaweal.aiccs.common.util.filestorage.FileStorageService;
import com.chinaweal.aiccs.config.CommonConfig;
import com.chinaweal.aiccs.org.service.AicorgService;
import com.chinaweal.aiccs.org.service.TUsersService;
import com.chinaweal.aiccs.redis.RedisService;
import com.chinaweal.aicorg.model.AICUser;
import com.chinaweal.aicorg.services.OrgUM;
import com.chinaweal.youfool.framework.springboot.base.query.BaseQuery;
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 com.google.common.collect.Lists;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
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 org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;


/**
 * <p>
 * 吊销业务 前端控制器
 * </p>
 *
 * @author Lee
 * @since 2021-03-26
 */
@Slf4j
@RestController
@RequestMapping("/tsbizrevlist")
public class TsbizrevlistController extends BaseController {

    @Autowired
    private EBaseinfoService eBaseinfoService;
    @Autowired
    private TsbizrevlistService tsbizrevlistService;
    @Autowired
    private ClueService clueService;
    @Autowired
    private TsrevtasklistService tsrevtasklistService;
    @Autowired
    private CaseService caseService;
    @Autowired
    private TSOpinionService tsOpinionService;
    @Autowired
    private IllegalactService illegalactService;
    @Autowired
    private TSOpinionService opinionService;
    @Autowired
    private TRBaseCodeService baseCodeService;
    @Autowired
    private AicorgService aicorgService;
    @Autowired
    private BusTridMakeUtil busTridMakeUtil;
    @Autowired
    private WorkFlowService workFlowService;
    @Autowired
    private TUsersService usersService;
    @Autowired
    private TREntPriseTypeService entPriseTypeService;
    @Autowired
    private TSAttachmentService attachmentService;
    @Resource
    private FileStorageService fileStorageService;
    @Resource
    private CmsDictCodeService cmsDictCodeService;
    @Resource
    private RevokeTempService revokeTempService;
    @Resource
    private IGzaiccodeService iGzaiccodeService;
    @Resource
    private TSAttachmentService tsAttachmentService;
    @Resource
    private BizRevEntService bizRevEntService;
    @Resource
    private IRevokeProcessService revokeProcessService;
    @Resource
    private RevokeAsyncTask revokeAsyncTask;
    @Resource
    private TSWritService tsWritService;
    @Resource
    private TSAbnListService tsAbnListService;
    @Resource
    private NoannualreportService noannualreportService;
    @Autowired
    private AreaSliceService areaSliceService;
    @Autowired
    private ITSUsualInspectService itsUsualInspectService;
    @Autowired
    private OrgUM orgUM;
    @Autowired
    private RedisService redisService;
    @Autowired
    private com.chinaweal.aiccs.aiccs.security.service.IPenaltyCaseInfoService penaltyCaseInfoService;

    private static final String REDIS_KEY_ENABLE_PREFIX = "revoke:batch:enable:";
    private static final String REDIS_KEY_DISABLE_PREFIX = "revoke:batch:disable:";


    /**
     * excel文件查询参数解析
     *
     * @param file       上传文件
     * @param model
     * @param bizEntType 企业类型；‘1’为公司 ‘2’为个人独资企业
     * @return
     */
    @ApiOperation("excel文件查询参数解析")
    @PostMapping("fileParamExplain")
    @Transactional
    public RestResult<?> fileParamExplain(@ApiParam("上传的excel文件") MultipartFile file, @ApiParam("参数模型名称") String model,
                                          @ApiParam("企业类型") String bizEntType, @ApiParam("名单类型") String illegalType) {
        AssertUtils.isNotNull(file);
        AssertUtils.isNotBlank(model);
        AssertUtils.isNotBlank(illegalType);

        AICUser user = SSOUtil.getUser();
        String userOrg = StringUtils.substring(user.getRegionID(), 0, 6);//user.getRegionID();

        // 读取excel数据
        List<EntExcel> entDtos;
        try {
            ExcelListener excelListener = ExcelIePortUtils.getExcelListener(file, new EntExcel(), 1, 1);
            Object objList = excelListener.getDatas();
            entDtos = (List<EntExcel>) objList;
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException("文件数据读取出错");
        }
        ArrayList<EBaseinfo> enableList = new ArrayList<>();
        HashSet<EBaseinfo> enableSet = new HashSet<>();
        ArrayList<DisableListVo> disableList = new ArrayList<>();//不可导
        Map<String, TRBaseCode> codeMap = baseCodeService.getBaseCodeMapFormCache("CA19");
        if (CollectionUtils.isEmpty(entDtos)) {
            return RestResult.error(ResultCode.PARAM_IS_BLANK, "不可上传空文件，请重新选择");
        }
        // 保存文件至服务器
        for (EntExcel entDto : entDtos) {
            LambdaQueryWrapper<EBaseinfo> wrapper = new LambdaQueryWrapper<>();
            EBaseinfo baseinfoModel = new EBaseinfo();
            baseinfoModel.setUniscid(entDto.getUniscid());
            baseinfoModel.setRegno(entDto.getRegno());
            baseinfoModel.setEntname(entDto.getEntname());

            wrapper.select(EBaseinfo::getRegorg, EBaseinfo::getPripid, EBaseinfo::getEntname, EBaseinfo::getRegno, EBaseinfo::getName, EBaseinfo::getRegstate, EBaseinfo::getRegstateCn, EBaseinfo::getEnttypeCn, EBaseinfo::getEnttype, EBaseinfo::getUniscid, EBaseinfo::getSuporg);
            if (StringUtils.isNotBlank(baseinfoModel.getUniscid())) {
                wrapper.eq(EBaseinfo::getUniscid, baseinfoModel.getUniscid());
            } else if (StringUtils.isNotBlank(baseinfoModel.getRegno())) {
                wrapper.eq(EBaseinfo::getRegno, baseinfoModel.getRegno());
            } else {
                wrapper.eq(EBaseinfo::getEntname, baseinfoModel.getEntname());
                // 用名称查主体的时候，可能会出现同名的情况
                List<EBaseinfo> list = eBaseinfoService.list(wrapper);
                if (list.size() > 1) {// 多家同名的时候，返回不可导原因“主体名称重名，请填写准确的统一码或注册号”
                    DisableListVo disableListVo = new DisableListVo();
                    disableListVo.setEntname(baseinfoModel.getEntname());
                    disableListVo.setReason("主体名称重名，请填写准确的统一码或注册号");
                    disableList.add(disableListVo);
                    continue;
                }
            }
            EBaseinfo eBaseinfo = eBaseinfoService.getOne(wrapper);
            if (eBaseinfo != null) {
                DisableListVo disableListVo = new DisableListVo();
                TRBaseCode baseCode = codeMap.get(eBaseinfo.getRegstate());
                if (baseCode != null) {
                    eBaseinfo.setRegstateCn(baseCode.getName());
                }

                //筛选过滤登记机关非本机关的市场主体到不可导入清单
                if (userOrg != null) {
                    String s = StringUtils.substring(eBaseinfo.getRegorg(), 0, 6);
                    if (!s.equals(userOrg)) {
                        disableListVo.setReason("登记机关非本机关的市场主体");
                        disableListVo.setEntname(eBaseinfo.getEntname());
                        disableListVo.setUniscid(eBaseinfo.getUniscid());
                        disableListVo.setRegno(eBaseinfo.getRegno());
                        disableListVo.setRegstateCn(eBaseinfo.getRegstateCn());
                        disableList.add(disableListVo);
                        continue;
                    }
                }

                // 判断与所选企业类型是否一致
                int i = 0;
                if ("1".equals(bizEntType)) {// 公司类型
                    i = Arrays.binarySearch(Constant.REVOKE_COMPANY_CODE, eBaseinfo.getEnttype());
                } else if ("2".equals(bizEntType)) { // 个人独资企业类型
                    i = Arrays.binarySearch(Constant.REVOKE_SOLE_CODE, eBaseinfo.getEnttype());
                }
                if (i < 0) {
                    disableListVo.setReason("主体类型与所选企业类型不符");//企业状态为不可导原因
                    disableListVo.setEntname(eBaseinfo.getEntname());
                    disableListVo.setUniscid(eBaseinfo.getUniscid());
                    disableListVo.setRegno(eBaseinfo.getRegno());
                    disableListVo.setRegstateCn(eBaseinfo.getRegstateCn());
                    disableList.add(disableListVo);
                    continue;
                }

                boolean isPartnership = false;
                for (String code : Constant.PARTNERSHIP_CODE) {
                    if (code.contains(eBaseinfo.getEnttype())) { // 为合伙企业 则加入不可导集合
                        disableListVo.setReason("主体类型为合伙企业");
                        isPartnership = true;
                        break;
                    }
                }

                if (!isPartnership) {// 不为合伙企业，判断企业状态
                    if ("1".equals(eBaseinfo.getRegstate())) {//为开业才可批吊
                        if (validInBiz(eBaseinfo.getPripid())) {// 检验是否在办理中了
                            disableListVo.setReason("该主体正在办理批吊中");//企业状态为不可导原因
                        } else {
                            if (enableSet.add(eBaseinfo)) {
                                enableList.add(eBaseinfo);
                            }
                            continue;
                        }
                    } else {
                        disableListVo.setReason("企业状态为" + eBaseinfo.getRegstateCn());//企业状态为不可导原因
                    }
                }
                disableListVo.setEntname(eBaseinfo.getEntname());
                disableListVo.setUniscid(eBaseinfo.getUniscid());
                disableListVo.setRegno(eBaseinfo.getRegno());
                disableListVo.setRegstateCn(eBaseinfo.getRegstateCn());
                disableList.add(disableListVo);

            } else {
                DisableListVo disableListVo = new DisableListVo();
                disableListVo.setEntname(baseinfoModel.getEntname());
                disableListVo.setUniscid(baseinfoModel.getUniscid());
                disableListVo.setRegno(baseinfoModel.getRegno());
                disableListVo.setReason("主体信息有误");
                disableList.add(disableListVo);
            }
        }
        String enableListId = UUID.randomUUID().toString();
        String disableListId = UUID.randomUUID().toString();
        HashMap<String, Object> groupMap = new HashMap<>();
        groupMap.put("enableListId", enableListId);
        groupMap.put("disableListId", disableListId);
        groupMap.put("disableList", disableList);
        redisService.set(REDIS_KEY_ENABLE_PREFIX + enableListId, JSON.toJSONString(enableList), 20 * 60);
        redisService.set(REDIS_KEY_DISABLE_PREFIX + disableListId, JSON.toJSONString(disableList), 20 * 60);
        groupMap.put("enableSize", enableList.size());
        groupMap.put("disableSize", disableList.size());

        return RestResult.ok(groupMap);
    }


    /**
     * 名单导入创建待办
     *
     * @param paramStr
     * @param request
     * @return
     */
    @Transactional
    @PostMapping(value = "/saveAccept.do")
    public RestResult<?> saveAccept(@RequestBody String paramStr, HttpServletRequest request) {
        AICUser aicUser = getLoginUser(request);
        if (aicUser == null) {
            return RestResult.error(ResultCode.USER_NOT_LOGGED_IN);
        }
        JSONObject jsonObject = JSONObject.parseObject(paramStr);
        String selectList = jsonObject.getString("selectList");
        String bizEntType = jsonObject.getString("bizEntType");
        String illegalType = jsonObject.getString("illegalType");
        AssertUtils.isNotEmpty(selectList, bizEntType, illegalType);
//        HashSet<EBaseinfo> eBaseinfoList = (HashSet<EBaseinfo>) expiryMap.get(enableListId);
//        ArrayList<EBaseinfo> eBaseinfos = new ArrayList<>(eBaseinfoList);
        List<String> pripids = JSONObject.parseArray(selectList, String.class);
        if (pripids.size() == 0) return RestResult.error(ResultCode.PARAM_IS_INVALID, "参数有误");
        //生成业务号
        String bizSeq = UUID.randomUUID().toString();
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime newDateTime = LocalDateTime.now();
        List<EBaseinfo> eBaseinfoList = new ArrayList<>();
        ArrayList<Tsbizrevlist> tsbizrevlists = new ArrayList<>();
        //ArrayList<BizRevEnt> bizRevEnts = new ArrayList<>();
        for (String pripid : pripids) {
            LambdaQueryWrapper<EBaseinfo> wrapper = new LambdaQueryWrapper<>();
            wrapper.select(EBaseinfo::getRegorg, EBaseinfo::getPripid, EBaseinfo::getEntname, EBaseinfo::getRegno, EBaseinfo::getName, EBaseinfo::getRegstate, EBaseinfo::getRegstateCn, EBaseinfo::getEnttypeCn, EBaseinfo::getEnttype, EBaseinfo::getUniscid);
            wrapper.eq(EBaseinfo::getPripid, pripid);
            EBaseinfo eBaseinfo = eBaseinfoService.getOne(wrapper);
            if (eBaseinfo == null) continue;
            eBaseinfoList.add(eBaseinfo);
            newDateTime = newDateTime.plus(1, ChronoUnit.SECONDS);
            BizRevEnt bizRevEnt = new BizRevEnt();
            bizRevEnt.setBizseq(bizSeq);
            bizRevEnt.setPripid(eBaseinfo.getPripid());
            bizRevEnt.setEntname(eBaseinfo.getEntname());    //企业名称
            bizRevEnt.setRegno(eBaseinfo.getRegno());//注册号
            bizRevEnt.setUniscid(eBaseinfo.getUniscid());//统一码
            bizRevEnt.setName(eBaseinfo.getName());//法定代表人
            if (StringUtils.isNotEmpty(eBaseinfo.getEnttypeCn())) {
                bizRevEnt.setEnttypeCn(eBaseinfo.getEnttypeCn());//企业类型
            } else {
                TREntPriseType entPriseType = entPriseTypeService.getEntPriseTypeFromCache(eBaseinfo.getEnttype());
                if (entPriseType != null) {
                    bizRevEnt.setEnttypeCn(entPriseType.getDisplayvalue());
                }
            }
            bizRevEnt.setEnttype(eBaseinfo.getEnttype());
            bizRevEnt.setIsremove("0");
            bizRevEnt.setInserttime(newDateTime);
            bizRevEnt.setLauptime(now);
            //bizRevEnts.add(bizRevEnt);
            bizRevEntService.save(bizRevEnt);
        }
        //bizRevEntService.saveBatch(bizRevEnts);
        Tsbizrevlist tsbizrevlistModel = new Tsbizrevlist();
        tsbizrevlistModel.setBizseq(bizSeq);//业务号
        tsbizrevlistModel.setSettime(LocalDate.now());//发现线索时间
//        String orgCode = usersService.findOrgCode(aicUser.getPrimaryKey());
        String orgCode = aicorgService.getRegionCodeByUser(aicUser);
        tsbizrevlistModel.setHandleOrg(orgCode);
        tsbizrevlistModel.setHandleOrgCn(iGzaiccodeService.getNameByCode(orgCode));
        tsbizrevlistModel.setLauptime(now);
        tsbizrevlists.add(tsbizrevlistModel);
        //初始化案件
        TsCase caseModel = new TsCase();
        caseModel.setBizseq(bizSeq);
        // 获取案件编号
        String caseNo = orgCode + busTridMakeUtil.getBatchRevokeCaseNo(orgCode);
        caseModel.setCaseNo(caseNo);
        caseModel.setBizEntType(bizEntType);
        caseModel.setIllegalType(illegalType);
        caseModel.setHandlerId(aicUser.getPrimaryKey());
        caseModel.setRegistTime(now);
        caseModel.setHandlerName(aicUser.getName());
        caseModel.setHandlerDate(now);
        //案件名称   规则： 关于+第一家公司名称+等+XX家+企业类型+的批量吊销
        String casename = "关于" + eBaseinfoList.get(0).getEntname() + "等" +
                eBaseinfoList.size() + "家" + ("2".equals(caseModel.getBizEntType()) ? "个人独资企业" : "公司") + "的批量吊销";
        caseModel.setCaseName(casename);
        //初始化立案理由  例：截止2017年9月，当事人未报送2015年和2016年年度报告，且未进行纳税申报，涉嫌构成《中华人民共和国公司法》第二百一十一条所指向的“公司成立后无正当理由超过6个月未开业的”行为，建议立案调查。
        LocalDate nowDate = LocalDate.now();
        int year = nowDate.getYear();
        int month = nowDate.getMonthValue();
        // '1'一年未年报实地查无、'2'连续两年年报、'3'因实地查无列入经营异常名录两年以上
        String reason = null;
        switch (illegalType) {
            case "2":
                reason = "截止" + year + "年" + month + "月，当事人未报送" + (year - 2) + "年和" + (year - 1) + "年年度报告，且未进行纳税申报，"
                        + BaseDataConstant.REVOKE_CASEREASON_MAP.get(caseModel.getBizEntType()) + "，建议立案调查。";
                break;
            case "3":
                reason = "截止" + year + "年" + month + "月，当事人通过登记住所（经营场所）无法取得联系被列入经营异常名录超过两年,"
                        + BaseDataConstant.REVOKE_CASEREASON_MAP.get(caseModel.getBizEntType()) + "，建议立案调查。";
                break;
        }
        if (StringUtils.isNotEmpty(reason)) {
            caseModel.setSituation(reason);
        }
        caseService.save(caseModel);

//         吊销待办
        Tsrevtasklist revtasklistModel = new Tsrevtasklist();
        revtasklistModel.setBizseqid(bizSeq);
        revtasklistModel.setCaseid(caseModel.getCaseId());
        revtasklistModel.setBustype(BaseDataConstant.REVOKE_TYPE_BATCHREVOKE);

        revtasklistModel.setBusname(casename);
        revtasklistModel.setAreaCode(orgCode);
        //开启流程--录入线索
        revtasklistModel = tsbizrevlistService.saveRevListAccept(aicUser, revtasklistModel, tsbizrevlists);
        if (StringUtils.isNotBlank(revtasklistModel.getTasklistid())) {
            Map<String, String> result = new HashMap<>();
            result.put("tasklistid", revtasklistModel.getTasklistid());
            result.put("bizseq", bizSeq);
            result.put("workflowid", revtasklistModel.getWorkflowid());
            return RestResult.ok(result);
        }
        return OK;
    }

    /**
     * 获取业务中第一个主体及基本信息
     *
     * @param bizseq
     * @return
     */
    @PostMapping("getFirstEntInBiz")
    public RestResult<?> getFirstEntInBiz(String bizseq) {
        AssertUtils.isNotBlank(bizseq);
        LambdaQueryWrapper<Tsbizrevlist> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(Tsbizrevlist::getPripid).eq(Tsbizrevlist::getBizseq, bizseq)
                .eq(Tsbizrevlist::getIsRemove, "0")
                .orderByDesc(Tsbizrevlist::getInsertTime).last("limit 1");
        List<Tsbizrevlist> list = tsbizrevlistService.list(wrapper);
        if (CollectionUtils.isNotEmpty(list)) {
            String pripid = list.get(0).getPripid();
            EBaseinfo eBaseinfo = eBaseinfoService.getOneByPripid(pripid);
            return RestResult.ok(eBaseinfo);
        }
        return RestResult.error(ResultCode.DATA_NONE);
    }

    @PostMapping("/next")
    public RestResult<?> processControl(@RequestBody @Validated RevokeProcessDto revokeProcessDto, BindingResult bindingResult, HttpServletRequest request) {
        AssertUtils.isBndingValidit(bindingResult);
        AICUser user = getLoginUser(request);
        if (user == null) throw new BusinessException("登录超时，请重新登录");

        Tsrevtasklist taskListModel = tsrevtasklistService.getById(revokeProcessDto.getTasklistid());
        Tsbizrevlist tsbizrevlist = tsbizrevlistService.getOneBybizseq(revokeProcessDto.getBizseq());
        AssertUtils.isTrue(taskListModel != null && tsbizrevlist != null, ResultCode.DATA_NONE);
        TSTwfProcessNode twfProcessNode = workFlowService.findCurrentNode(taskListModel.getWorkflowid());
        String currentnode = twfProcessNode.getCurrentnode();
        try {
            revokeProcessService.processControl(revokeProcessDto, taskListModel, tsbizrevlist, user);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("批吊业务号{}流程扭转出错" + e, revokeProcessDto.getBizseq());
            return RestResult.error(ResultCode.BUSINESS_LOGIC_ERROR, "流程扭转出错");
        }
        try {
            if ("decisionEnter".equals(revokeProcessDto.getNextNodeID())) {
                if ("approvalHearing".equals(currentnode)) {
                    LocalDateTime now = LocalDateTime.now();
                    LocalDate nowDate = LocalDate.now();
                    // 异步生成听证告知书
                    revokeAsyncTask.revHearingNoticeTask(revokeProcessDto.getBizseq(), tsbizrevlist.getHandleOrg(), now, nowDate);
                }
            } else if ("sendEnter".equals(revokeProcessDto.getNextNodeID())) {
                if ("approvalDecision".equals(currentnode)) {
                    // 异步生成决定书
                    revokeAsyncTask.revPunishDecTask(revokeProcessDto.getBizseq(), tsbizrevlist.getHandleOrg());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("批吊业务号{}异步附件任务执行异常" + e, revokeProcessDto.getBizseq());
        }

        return RestResult.ok();
    }

    /**
     * 违法行为列表更新或保存
     *
     * @param illegalactList 违法行为列表
     * @return
     */
    @Transactional
    @PostMapping("saveorUpdateIllegalactList")
    public RestResult<?> saveorUpdateIllegalactList(@RequestBody List<Illegalact> illegalactList) {
        if (illegalactList.size() == 0) {
            return RestResult.error(ResultCode.PARAM_IS_BLANK);
        }
        boolean flag = false;
        for (Illegalact illegalact : illegalactList) {
            flag = illegalactService.saveOrUpdate(illegalact);
        }
        return RestResult.ok(flag);
    }

    /**
     * 获取拟吊销主体列表 分页
     *
     * @param pageRequestDto 分页参数
     * @param request
     * @return
     */
    @PostMapping("/getBizRevListPage")
    public RestResult<?> getBizRevListPage(@RequestBody PageRequestDto pageRequestDto, HttpServletRequest request) {
        AssertUtils.isNotNull(pageRequestDto, pageRequestDto.getCustomParamMap());// 要改 bizseq必传
        pageRequestDto.checkDefault(1, 10, "insertTime");
        Map<String, Object> customParamMap = pageRequestDto.getCustomParamMap();
        String bizseq = StringUtils.tranObject(customParamMap.get("bizseq"));
        if (StringUtils.isBlank(bizseq)) return RestResult.error(ResultCode.PARAM_IS_BLANK);
        // 搜索统一码和注册号
        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<Tsbizrevlist> revEntPage = tsbizrevlistService.getRevEntPage(new Page<>(pageRequestDto.getCurPage(), pageRequestDto.getPageSize()), customParamMap);


//        IPage<Tsbizrevlist> defaultPaging = tsbizrevlistService.defaultPaging(pageRequestDto, w -> {
//            LambdaQueryWrapper<Tsbizrevlist> wrapper = w.lambda();
//            Map<String, Object> customParamMap = pageRequestDto.getCustomParamMap();
//
//            String bizseq = StringUtils.tranObject(customParamMap.get("bizseq"));
//            if (StringUtils.isNotBlank(bizseq)) {
//                wrapper.eq(Tsbizrevlist::getBizseq, bizseq);
//            }
//            String entName = StringUtils.tranObject(customParamMap.get("entname"));
//            if (StringUtils.isNotBlank(entName)) {
//                wrapper.eq(Tsbizrevlist::getEntname, entName);
//            }
//            // 搜索统一码和注册号
//            String searchCode = StringUtils.tranObject(customParamMap.get("searchCode"));
//            //判断入参为统一码还是注册号
//            if (StringUtils.isNotBlank(searchCode)) {
//                if (StringUtils.isUscc(searchCode)) {
//                    wrapper.like(Tsbizrevlist::getUniscid, searchCode);
//                } else {
//                    wrapper.like(Tsbizrevlist::getRegno, searchCode);
//                }
//            }
//            // 是否查出已剔除的
//            String type = StringUtils.tranObject(customParamMap.get("type"));
//            if (StringUtils.isNotBlank(type) && type.equals("all")){
//                wrapper.orderByDesc(Tsbizrevlist::getIsRemove);// 已剔除的排前
//            }else {
//                wrapper.eq(Tsbizrevlist::getIsRemove, "0");
//            }
//        }, null);
        if (CollectionUtils.isNotEmpty(revEntPage.getRecords())) { // 封装企业状态
            Map<String, TRBaseCode> codeMap = baseCodeService.getBaseCodeMapFormCache("CA19");
            for (Tsbizrevlist record : revEntPage.getRecords()) {
                EBaseinfo eBaseinfo = eBaseinfoService.getOne(new LambdaQueryWrapper<EBaseinfo>().eq(EBaseinfo::getPripid, record.getPripid()));
                record.setRegstate(eBaseinfo.getRegstate());
                TRBaseCode code = codeMap.get(eBaseinfo.getRegstate());
                if (code != null) {
                    record.setRegstateCn(code.getName());
                }
                if (record.getEnttypeCn() == null) {
                    TREntPriseType type = entPriseTypeService.getEntPriseTypeFromCache(record.getEnttype());
                    if (type != null) {
                        record.setEnttypeCn(type.getDisplayvalue());
                    }
                }

            }
        }
        return RestResult.ok(revEntPage);

    }

    /**
     * 验证业务中企业状态，不符合（开业、停业、其他)的自动剔除
     *
     * @param bizseq 业务号
     * @return
     */
    @PostMapping("validEntsRegstate")
    public RestResult<?> validEntsRegstate(String bizseq) {
        LambdaQueryWrapper<BizRevEnt> lqW = new LambdaQueryWrapper<>();
        lqW.eq(BizRevEnt::getBizseq, bizseq)
                .eq(BizRevEnt::getIsremove, "0");
        List<BizRevEnt> list = bizRevEntService.list(lqW);
        if (CollectionUtils.isEmpty(list)) {
            return RestResult.error(ResultCode.DATA_NONE, "该业务无主体信息");
        }
        ArrayList<String> enableCodeList = new ArrayList<>();// "1" 可批吊的情况
        enableCodeList.add(ConstantsUtil.QUALIFICATION_OPEN);
        for (BizRevEnt each : list) {
            LambdaQueryWrapper<EBaseinfo> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(EBaseinfo::getPripid, each.getPripid());
            EBaseinfo eBaseinfo = eBaseinfoService.getOne(queryWrapper);
            if (eBaseinfo != null) {
                String regState = eBaseinfo.getRegstate(); // 企业状态（国标）
                String entStatus = eBaseinfo.getEntStatus();  // 企业状态（市标）
                // 不可批吊状态 regState 不等于1 或者 entStatus为市标003006（清算中）、003001（待迁入）
                boolean isNotRev = !ConstantsUtil.QUALIFICATION_OPEN.equals(regState) || "003001".equals(entStatus) || "003006".equals(entStatus);
                if (isNotRev) {
                    bizRevEntService.update(new BizRevEnt().setNoopenstate("1"), new LambdaQueryWrapper<>(each).eq(BizRevEnt::getBizseq, bizseq).eq(BizRevEnt::getPripid, each.getPripid()));
                } else {
                    if ("1".equals(each.getNoopenstate())) {
                        bizRevEntService.update(new BizRevEnt().setNoopenstate("0"), new LambdaQueryWrapper<>(each).eq(BizRevEnt::getBizseq, bizseq).eq(BizRevEnt::getPripid, each.getPripid()));
                    }
                }
            }
        }
        return RestResult.ok();
    }

    /**
     * 验证企业是否已在在办业务中
     *
     * @param pripid 主体id
     * @return true: 在办中；false：未办
     */
    public boolean validInBiz(String pripid) {
        List<Tsbizrevlist> list = tsbizrevlistService.selectInBiz(pripid);
//        LambdaQueryWrapper<Tsbizrevlist> wrapper = new LambdaQueryWrapper<>();
//        wrapper.eq(Tsbizrevlist::getPripid,pripid).eq(Tsbizrevlist::getIsRemove,"0").notIn(Tsbizrevlist::getStatus,"20","21","22");
//        List<Tsbizrevlist> list = tsbizrevlistService.list(wrapper);
        return CollectionUtils.isNotEmpty(list);
    }

//    /**
//     * 新增拟吊销主体列表 分页
//     *
//     * @param pageRequestDto
//     * @param request
//     * @return
//     */
//    @PostMapping("enableAddList")
//    public RestResult<?> enableAddList(@RequestBody PageRequestDto pageRequestDto, HttpServletRequest request) {
//        AssertUtils.isNotNull(pageRequestDto);
//        pageRequestDto.checkDefault(1, 10, null);
//        return RestResult.ok(eBaseinfoService.defaultPaging(pageRequestDto, w -> {
//            LambdaQueryWrapper<EBaseinfo> wrapper = w.lambda();
//            Map<String, Object> customParamMap = pageRequestDto.getCustomParamMap();
//            if (customParamMap == null) return;
//
//            String bizseq = StringUtils.tranObject(customParamMap.get("bizseq"));
//            //排除已在拟吊銷列表的主体
//            if (StringUtils.isNotBlank(bizseq)) {
//                LambdaQueryWrapper<Tsbizrevlist> queryWrapper = new LambdaQueryWrapper<>();
//                queryWrapper.eq(Tsbizrevlist::getBizseq, bizseq)
//                        .select(Tsbizrevlist::getPripid);
//                List<Tsbizrevlist> list = tsbizrevlistService.list(queryWrapper);
//                List<String> pripids = list.stream().map(Tsbizrevlist::getPripid).collect(Collectors.toList());
//                wrapper.notIn(EBaseinfo::getPripid, pripids);
//            }
//            // 搜索统一码和注册号
//            String searchCode = StringUtils.tranObject(customParamMap.get("searchCode"));
//            //判断入参为统一码还是注册号
//            if (StringUtils.isNotBlank(searchCode)) {
//                if (StringUtils.isUscc(searchCode)) {
//                    wrapper.eq(EBaseinfo::getUniscid, searchCode);
//                } else {
//                    wrapper.eq(EBaseinfo::getRegno, searchCode);
//                }
//            }
//            wrapper.eq(EBaseinfo::getRegstate, '1');//企业在营 条件
//        }, null));
//    }

    /**
     * 新增拟吊销主体列表查询，优化
     *
     * @param pageRequestDto
     * @param request
     * @return
     */
    @PostMapping("enableAddList")
    public RestResult<?> enableAddList(@RequestBody PageRequestDto pageRequestDto, HttpServletRequest request) {
        AssertUtils.isNotNull(pageRequestDto, pageRequestDto.getCustomParamMap());
//        pageRequestDto.checkDefault(1, 10, null);
        Map<String, Object> customParamMap = pageRequestDto.getCustomParamMap();


        String searchCode = StringUtils.tranObject(customParamMap.get("searchCode"));
        String searchName = StringUtils.tranObject(customParamMap.get("searchName"));
        LambdaQueryWrapper<EBaseinfo> wrapper = new LambdaQueryWrapper<>();
        //判断入参为统一码还是注册号
        if (StringUtils.isNotBlank(searchCode)) {
            if (StringUtils.isUscc(searchCode)) {
                wrapper.eq(EBaseinfo::getUniscid, searchCode);
            } else {
                wrapper.eq(EBaseinfo::getRegno, searchCode);
            }
        }
        wrapper.eq(StringUtils.isNotBlank(searchName), EBaseinfo::getEntname, searchName);

        Page<EBaseinfo> page = eBaseinfoService.page(new Page<>(pageRequestDto.getCurPage(), pageRequestDto.getPageSize()), wrapper);
        if (page != null && CollectionUtils.isNotEmpty(page.getRecords())) {
            Map<String, TRBaseCode> codeMap = baseCodeService.getBaseCodeMapFormCache("CA19");
            //封装主体类型名称
            page.getRecords().forEach(each -> {
                TREntPriseType code = entPriseTypeService.getEntPriseTypeFromCache(each.getEnttype());
                if (code != null) {
                    each.setEnttypeCn(code.getDisplayvalue());
                }
                // 经营状态
                TRBaseCode baseCode = codeMap.get(each.getRegstate());
                if (baseCode != null) {
                    each.setRegstateCn(baseCode.getName());
                }
            });
        }

        // 去掉类型条件
/*
        String type = StringUtils.tranObject(customParamMap.get("type"));
        //实地查无列异两年
        if("abn".equals(type)) {
            LocalDate date = LocalDate.now().minusYears(2);
            customParamMap.put("abntime",DateUtils.localDateFormat(date,DateUtils.DATE_DEFAULT_FORMAT));
            IPage<AbnEntDto> page = eBaseinfoService.getSDCWandTwoYearsAbnlist(new Page<>(pageRequestDto.getCurPage(), pageRequestDto.getPageSize(),false), customParamMap);
            List<AbnEntDto> records = page.getRecords();
            for (AbnEntDto record : records) {
                if(StringUtils.isEmpty(record.getEnttypeCn())) {
                    TREntPriseType entPriseType = entPriseTypeService.getEntPriseTypeFromCache(record.getEnttype());
                    if (entPriseType != null) {
                        record.setEnttypeCn(entPriseType.getDisplayvalue());
                    }
                }
            }

            return RestResult.ok(page);
        }
        //未年报
        else if ("wnb".equals(type)){
            IPage<NoAnnualReportEntDto> page = eBaseinfoService.getNoReportTwoYearsPage(new Page<>(pageRequestDto.getCurPage(), pageRequestDto.getPageSize(),false), customParamMap);
            List<NoAnnualReportEntDto> records = page.getRecords();
            for (NoAnnualReportEntDto record : records) {
                if(StringUtils.isEmpty(record.getEnttypeCn())) {
                    TREntPriseType entPriseType = entPriseTypeService.getEntPriseTypeFromCache(record.getEnttype());
                    if (entPriseType != null) {
                        record.setEnttypeCn(entPriseType.getDisplayvalue());
                    }
                }
                if(StringUtils.isEmpty(record.getRegstateCn())) {
                    Map<String, TRBaseCode> codeMap = baseCodeService.getBaseCodeMapFormCache("CA19");
                    TRBaseCode trBaseCode = codeMap.get(record.getRegstate());
                    if (trBaseCode != null) {
                        record.setRegstateCn(trBaseCode.getName());
                    }
                }
            }
            return RestResult.ok(page);
        }
*/

        // 验证是否满足批吊条件
        return RestResult.ok(page);

//        return RestResult.ok(eBaseinfoService.defaultPaging(pageRequestDto, w -> {
//            LambdaQueryWrapper<EBaseinfo> wrapper = w.lambda();
//            Map<String, Object> customParamMap = pageRequestDto.getCustomParamMap();
//            if (customParamMap == null) return;
//
//            String bizseq = StringUtils.tranObject(customParamMap.get("bizseq"));
//            //排除已在拟吊銷列表的主体
//            if (StringUtils.isNotBlank(bizseq)) {
//                LambdaQueryWrapper<Tsbizrevlist> queryWrapper = new LambdaQueryWrapper<>();
//                queryWrapper.eq(Tsbizrevlist::getBizseq, bizseq)
//                        .select(Tsbizrevlist::getPripid);
//                List<Tsbizrevlist> list = tsbizrevlistService.list(queryWrapper);
//                List<String> pripids = list.stream().map(Tsbizrevlist::getPripid).collect(Collectors.toList());
//                wrapper.notIn(EBaseinfo::getPripid, pripids);
//            }
//            // 搜索统一码和注册号
//            String searchCode = StringUtils.tranObject(customParamMap.get("searchCode"));
//            //判断入参为统一码还是注册号
//            if (StringUtils.isNotBlank(searchCode)) {
//                if (StringUtils.isUscc(searchCode)) {
//                    wrapper.eq(EBaseinfo::getUniscid, searchCode);
//                } else {
//                    wrapper.eq(EBaseinfo::getRegno, searchCode);
//                }
//            }
//            wrapper.eq(EBaseinfo::getRegstate, '1');//企业在营 条件
//        }, null));
    }

    /**
     * 通过企业id从拟吊销企业列表移除主体
     *
     * @param pripids      企业id
     * @param bizseq       业务号id
     * @param removeReason 剔除原因
     * @param request
     * @return
     */
    @Transactional
    @PostMapping("removeRevListByPripid")
    public RestResult<?> removeRevListByPripid(String pripids, String bizseq, String removeReason, String remNo, HttpServletRequest request) {
        AICUser user = getLoginUser(request);
        if (user == null) return RestResult.error(ResultCode.USER_NOT_LOGGED_IN);
        AssertUtils.isNotBlank(bizseq, pripids);
        String[] pripidArray = pripids.split(Constant.SEMICOLON);
        BizRevEnt bizRevEntParam = new BizRevEnt();
        bizRevEntParam.setRemno(Integer.valueOf(remNo));//剔除批次
        bizRevEntParam.setRemhandler(user.getName());//剔除人
        bizRevEntParam.setRemovetime(LocalDateTime.now());//剔除时间
        bizRevEntParam.setRemovereason(removeReason);//剔除原因
        bizRevEntParam.setIsremove("1");//设为剔除
        boolean remove = bizRevEntService.update(bizRevEntParam, new LambdaQueryWrapper<BizRevEnt>().eq(BizRevEnt::getBizseq, bizseq).in(BizRevEnt::getPripid, pripidArray));
        if (!remove) {
            log.info("剔除更新{}失败", pripids);
            throw new BusinessException("剔除失败");
        }
        // 剔除时，检查有没有生成过听证告知书，有的话要更新文书表的更新时间，视图时间才会更新
        TSWrit tsWritModel = new TSWrit();
        tsWritModel.setLauptime(LocalDateTime.now());
        tsWritService.update(tsWritModel, new LambdaQueryWrapper<TSWrit>().eq(TSWrit::getWritstype, WorkNoUtil.WORKNOTYPE_32).eq(TSWrit::getBizseq, bizseq)
                .in(TSWrit::getPripid, pripidArray));

        for (String pripid : pripidArray) {
            List<TSAttachment> attachments = attachmentService.getByPripidAndBizseq(pripid, bizseq);
            if (CollectionUtils.isNotEmpty(attachments)) {
                for (TSAttachment attachment : attachments) {
                    boolean removeById = attachmentService.removeById(attachment.getAttachmentid());
                    if (!removeById) {
                        log.info("批吊剔除主体时，删除文件信息失败,主体id{}业务号{}", pripid, bizseq);
                        throw new BusinessException("剔除失败");
                    } else {
                        log.info("批吊剔除主体时,成功删除文件信息：{}", attachment);
                    }
                }
            }
        }
        String caseName = caseService.updateCaseName(bizseq);
        if (caseName != null) {
            List<Tsrevtasklist> revtasklist = tsrevtasklistService.selectByBizSeqID(bizseq);
            Tsrevtasklist tsrevtasklist = revtasklist.get(0);
            tsrevtasklist.setBusname(caseName);
            boolean update = tsrevtasklistService.updateById(tsrevtasklist);
            if (update) {
                return RestResult.ok(caseName);
            } else {
                log.info("批吊剔除主体时,业务号{}更新待办名称失败：{}", bizseq, caseName);
                throw new BusinessException("更新待办名称失败");
            }
        } else {
            log.info("批吊剔除主体时,业务号{}更新案件名称失败：{}", bizseq, caseName);
            throw new BusinessException("更新案件名称失败");
        }
    }

    /**
     * 通过企业id添加主体至拟吊销企业列表
     *
     * @param pripid    企业id
     * @param bizseq    业务号id
     * @param bizStatus 业务状态
     * @param request
     * @return
     */
    @Transactional
    @PostMapping("insertRevListByPripid")
    public RestResult<?> insertRevListByPripid(String pripid, String bizseq, String bizStatus, String bizEntType, HttpServletRequest request) {
        AssertUtils.isNotBlank(bizseq, pripid, bizStatus, bizEntType);
        AICUser user = getLoginUser(request);
//        String[] pripidArray = pripids.split(Constant.SEMICOLON); // 批量改个案
        EBaseinfo eBaseinfo = eBaseinfoService.getOneByPripid(pripid);
        // 验证该企业类型是否与业务的公司类型一致（公司与个人独资）
        int i = 0;
        if ("1".equals(bizEntType)) {// 公司类型
            i = Arrays.binarySearch(Constant.REVOKE_COMPANY_CODE, eBaseinfo.getEnttype());
        } else if ("2".equals(bizEntType)) { // 个人独资企业类型
            i = Arrays.binarySearch(Constant.REVOKE_SOLE_CODE, eBaseinfo.getEnttype());
        }
        if (i < 0) {
            return RestResult.error(ResultCode.BUSINESS_LOGIC_ERROR, "主体类型不符，无法新增！");
        }
        // 验证企业状态
        if (!"1".equals(eBaseinfo.getRegstate())) {
            return RestResult.error(ResultCode.BUSINESS_LOGIC_ERROR, "该主体状态非开业状态，无法新增！");
        }
        // 验证是否合伙企业
        for (String code : Constant.PARTNERSHIP_CODE) {
            if (code.contains(eBaseinfo.getEnttype())) {
                return RestResult.error(ResultCode.BUSINESS_LOGIC_ERROR, "该主体类型为合伙企业，无法新增！");
            }
        }
        // 验证是否在办
        List<Tsbizrevlist> bizRevEntDB = tsbizrevlistService.selectInBiz(pripid);
//        BizRevEnt bizRevEntDB = tsbizrevlistService.getByPripidandBizseq(eBaseinfo.getPripid(), bizseq);
        if (CollectionUtils.isNotEmpty(bizRevEntDB)) {
            return RestResult.error(ResultCode.BUSINESS_LOGIC_ERROR, "主体已在办理批吊业务中，无法新增！");
        }

        BizRevEnt bizRevEntModel = new BizRevEnt();
        bizRevEntModel.setPripid(eBaseinfo.getPripid());
        bizRevEntModel.setBizseq(bizseq);//业务号
        bizRevEntModel.setEntname(eBaseinfo.getEntname());    //企业名称
        bizRevEntModel.setRegno(eBaseinfo.getRegno());//注册号
        bizRevEntModel.setUniscid(eBaseinfo.getUniscid());//统一码
        bizRevEntModel.setName(eBaseinfo.getName());//法定代表人
        bizRevEntModel.setEnttype(eBaseinfo.getEnttype());
        if (StringUtils.isNotEmpty(eBaseinfo.getEnttypeCn())) {
            bizRevEntModel.setEnttypeCn(eBaseinfo.getEnttypeCn());//企业类型
        } else {
            TREntPriseType entPriseType = entPriseTypeService.getEntPriseTypeFromCache(eBaseinfo.getEnttype());
            if (entPriseType != null) {
                bizRevEntModel.setEnttypeCn(entPriseType.getDisplayvalue());
            }
        }
        bizRevEntModel.setInserttime(LocalDateTime.now());
        boolean insert = bizRevEntService.save(bizRevEntModel);
        if (insert) {
            String caseName = caseService.updateCaseName(bizseq);
            if (caseName != null) {
                List<Tsrevtasklist> revtasklist = tsrevtasklistService.selectByBizSeqID(bizseq);
                Tsrevtasklist tsrevtasklist = revtasklist.get(0);
                tsrevtasklist.setBusname(caseName);
                boolean update = tsrevtasklistService.updateById(tsrevtasklist);
                if (update) {
                    return RestResult.ok(caseName);
                } else {
                    throw new BusinessException("更新待办名称失败");
                }

            } else {
                throw new BusinessException("更新案件名称失败");
            }
        }
        throw new BusinessException("新增失败");
    }

    /**
     * 批量吊销流程跟踪
     *
     * @param tasklistid 待办id
     * @param stepNo     步骤标识
     * @return
     */
    @GetMapping("getStepTableList")
    public RestResult<?> getStepTableList(String tasklistid, String stepNo) {
        AssertUtils.isNotBlank(stepNo);
        ArrayList<StepTableDto> stepTableLists = new ArrayList<>();
        Tsrevtasklist tsrevtask = tsrevtasklistService.getOne(new LambdaQueryWrapper<Tsrevtasklist>().eq(Tsrevtasklist::getTasklistid, tasklistid));
        String workflowid = tsrevtask.getWorkflowid();
//        String caseId = tsrevtask.getCaseid();
//        Clue clue = clueService.getById(clueid);
//        StepTableDto stepTableDto = new StepTableDto();
//        stepTableDto.setHandlerName(clue.getAcceptName());//处理人
//        stepTableDto.setStartTime(clue.getAcceptTime());// 开始时间
//        stepTableDto.setEndTime(clue.getAcceptTime());// 结束时间
//        stepTableDto.setHandleDate(clue.getAcceptTime());// 处理日期
//        stepTableDto.setOpinionContent(clue.getSituation());// 意见内容
//        stepTableDto.setOpiniontype("0");
//        stepTableLists.add(stepTableDto);
//        //线索录入
//        if (stepNo.equals("0")) {
//            return RestResult.ok(stepTableLists);
//        }
        //其他环节从意见列表获取
        LambdaQueryWrapper<TSOpinion> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TSOpinion::getWorkflowid, workflowid)
                .orderByAsc(TSOpinion::getLauptime);
        List<TSOpinion> list = tsOpinionService.list(wrapper);
        for (int i = 0; i < list.size(); i++) {
            StepTableDto stepTable = new StepTableDto();
            TSOpinion tsOpinion = list.get(i);
            //封装开始时间
            if (i == 0) {
                stepTable.setStartTime(tsrevtask.getSendertime().toLocalDate());
            } else {
                stepTable.setStartTime(stepTableLists.get(i - 1).getEndTime());
            }
            stepTable.setHandlerName(tsOpinion.getHandler());//处理人
            stepTable.setEndTime(tsOpinion.getHandledate().toLocalDate());// 结束时间
            stepTable.setHandleDate(tsOpinion.getHandledate().toLocalDate());// 处理日期
            stepTable.setOpinionContent(tsOpinion.getOpinioncontent());// 意见内容
            stepTable.setOpiniontype(tsOpinion.getOpiniontype());
            stepTableLists.add(stepTable);
        }
        System.out.println("====================" + stepTableLists);
        List<StepTableDto> stepTableDtoList = new ArrayList<>();
        //立案 意见类型opiniontype为"1","2","3"
        if (stepNo.equals("1")) {
            stepTableDtoList = stepTableLists.stream().filter((StepTableDto st) -> Integer.valueOf(st.getOpiniontype()) >= 1 && Integer.valueOf(st.getOpiniontype()) <= 3).collect(Collectors.toList());
        } else if (stepNo.equals("2")) {//调查 意见类型opiniontype为"4","5","6"
            stepTableDtoList = stepTableLists.stream().filter((StepTableDto st) -> Integer.valueOf(st.getOpiniontype()) >= 4 && Integer.valueOf(st.getOpiniontype()) <= 6).collect(Collectors.toList());
        } else if (stepNo.equals("3")) {//听证告知 意见类型opiniontype为"7","8","9","24","25","26"
            stepTableDtoList = stepTableLists.stream().filter((StepTableDto st) -> Integer.valueOf(st.getOpiniontype()) == 4 || (Integer.valueOf(st.getOpiniontype()) >= 8 && Integer.valueOf(st.getOpiniontype()) <= 9) || (Integer.valueOf(st.getOpiniontype()) >= 24 && Integer.valueOf(st.getOpiniontype()) <= 26)).collect(Collectors.toList());

        } else if (stepNo.equals("4")) {//决定  意见类型opiniontype为"10","11","12","13","27","28","29"
            stepTableDtoList = stepTableLists.stream().filter((StepTableDto st) -> (Integer.valueOf(st.getOpiniontype()) >= 10 && Integer.valueOf(st.getOpiniontype()) <= 13) || (Integer.valueOf(st.getOpiniontype()) >= 27 && Integer.valueOf(st.getOpiniontype()) <= 29)).collect(Collectors.toList());

        } else if (stepNo.equals("5")) {//送达与结束 意见类型opiniontype为"14","15","16"
            stepTableDtoList = stepTableLists.stream().filter((StepTableDto st) -> Integer.valueOf(st.getOpiniontype()) >= 14 && Integer.valueOf(st.getOpiniontype()) <= 16).collect(Collectors.toList());

        } else if (stepNo.equals("31")) {//注销公告
            stepTableDtoList = stepTableLists.stream().filter((StepTableDto st) -> Integer.valueOf(st.getOpiniontype()) >= 31 && Integer.valueOf(st.getOpiniontype()) <= 33).collect(Collectors.toList());
        }
        return RestResult.ok(stepTableDtoList);
    }

    /**
     * 拟吊销主体列表剔除记录 分页
     *
     * @param pageRequestDto 分页参数
     * @param request
     * @return
     */
    @PostMapping("getRemoveRecord")
    public RestResult<?> getRemoveRecord(@RequestBody PageRequestDto pageRequestDto, HttpServletRequest request) {
        AssertUtils.isNotNull(pageRequestDto);
        pageRequestDto.checkDefault(1, 10, "removeTime");
        return RestResult.ok(bizRevEntService.defaultPaging(pageRequestDto, w -> {
            LambdaQueryWrapper<BizRevEnt> wrapper = w.lambda();
            Map<String, Object> customParamMap = pageRequestDto.getCustomParamMap();
            if (customParamMap == null) return;

            String bizseq = StringUtils.tranObject(customParamMap.get("bizseq"));
            //已移除拟吊銷列表的主体
            if (StringUtils.isNotBlank(bizseq)) {
                wrapper.eq(BizRevEnt::getBizseq, bizseq)
                        .eq(BizRevEnt::getIsremove, '1');
            }
            // 搜索统一码和注册号
            String searchCode = StringUtils.tranObject(customParamMap.get("searchCode"));
            //判断入参为统一码还是注册号
            if (StringUtils.isNotBlank(searchCode)) {
                if (StringUtils.isUscc(searchCode)) {
                    wrapper.eq(BizRevEnt::getUniscid, searchCode);
                } else {
                    wrapper.eq(BizRevEnt::getRegno, searchCode);
                }
            }
            //主体名称
            String searchEntName = StringUtils.tranObject(customParamMap.get("searchEntName"));
            wrapper.like(StringUtils.isNotBlank(searchEntName), BizRevEnt::getEntname, searchEntName);
            //剔除原因
            String searchReason = StringUtils.tranObject(customParamMap.get("searchReason"));
            wrapper.like(StringUtils.isNotBlank(searchReason), BizRevEnt::getRemovereason, searchReason);
            //处理人
            String searchHandler = StringUtils.tranObject(customParamMap.get("searchHandler"));
            wrapper.like(StringUtils.isNotBlank(searchHandler), BizRevEnt::getRemhandler, searchHandler);
            //手动/自动剔除
            String searchRemType = StringUtils.tranObject(customParamMap.get("searchRemType"));
            if (StringUtils.isNotBlank(searchRemType)) {
                if (searchRemType.equals("0")) {//表自动
                    wrapper.eq(BizRevEnt::getRemno, 0);//对应0批次
                } else if (searchRemType.equals("1")) {//表手动
                    wrapper.ne(BizRevEnt::getRemno, 0);//对应除0外其他批次
                }
            }
            //剔除时间
            String remStartDate = StringUtils.tranObject(customParamMap.get("remStartDate"));
            String remEndDate = StringUtils.tranObject(customParamMap.get("remEndDate"));
            if (StringUtils.isNotBlank(remStartDate) && StringUtils.isNotBlank(remStartDate)) {
                remStartDate = DateUtils.dateTimeFormat(remStartDate);
                remEndDate = DateUtils.dateTimeFormat(remEndDate);
                wrapper.between(BizRevEnt::getRemovetime, remStartDate, remEndDate);
            }
            wrapper.orderByDesc(BizRevEnt::getRemovetime);
        }, null));
    }

    /**
     * 批量吊销导入主体名单错误信息清单Excel导出
     *
     * @return
     */
    @GetMapping("exportDisableEntList")
    public RestResult<?> exportDisableEntList(HttpServletRequest request, HttpServletResponse response, String disableListId) {
        AssertUtils.isNotEmpty(disableListId);
        String json = redisService.get(REDIS_KEY_DISABLE_PREFIX + disableListId);
        List<DisableListVo> list = JSON.parseArray(json, DisableListVo.class);
        String fileName = "批吊-不可导入企业名单.xlsx";
        tsAttachmentService.exportExcel(request, response, fileName, list);
        return OK;
    }

    /**
     * 批量吊销现场核查导出主体名单
     *
     * @return
     */
    @PostMapping("exportCheckListExcel")
    public RestResult<?> exportCheckListExcel(HttpServletRequest request, HttpServletResponse response, @RequestBody String paramStr) {
        JSONObject jsonObject = JSONObject.parseObject(paramStr);
        String selectList = jsonObject.getString("pripids");
        String enableAndCheckListId = jsonObject.getString("enableAndCheckListId");
        AssertUtils.isNotEmpty(enableAndCheckListId, selectList);
        List<String> pripids = JSONObject.parseArray(selectList, String.class);
        if (pripids.size() == 0) return RestResult.error(ResultCode.PARAM_IS_INVALID, "参数有误");
        String json = redisService.get(REDIS_KEY_ENABLE_PREFIX + enableAndCheckListId);
        List<EnableListAndCheckVo> list = JSON.parseArray(json, EnableListAndCheckVo.class);
        List<EnableListAndCheckExcel> exportList = new ArrayList<>();
        for (EnableListAndCheckVo checkVo : list) {
            for (String pripid : pripids) {
                if (checkVo.getPripid().equals(pripid)) {
                    EnableListAndCheckExcel enableListAndCheckExcel = new EnableListAndCheckExcel();
                    BeanUtils.copyProperties(checkVo, enableListAndCheckExcel);
                    exportList.add(enableListAndCheckExcel);
                }
            }
        }
        String fileName = "批吊-现场核查企业名单.xlsx";
        tsAttachmentService.exportExcel2(request, response, fileName, exportList, EnableListAndCheckExcel.class);
        return OK;
    }

    //生成获取批吊现场核查列表，只生成一次，查询用searchEnableList方法
    @PostMapping("getEnableList")
    public RestResult<?> getEnableList(String enableListId) {
        String json = redisService.get(REDIS_KEY_ENABLE_PREFIX + enableListId);
        List<EBaseinfo> enableList = JSON.parseArray(json, EBaseinfo.class);
        List<EnableListAndCheckVo> enableListAndCheckVos = new ArrayList<>();
        for (EBaseinfo eBaseinfo : enableList) {
            EnableListAndCheckVo checkAndRevResult = itsUsualInspectService.getCheckAndRevResult(eBaseinfo.getPripid());
            if (checkAndRevResult != null) {
                checkAndRevResult.setUscc(eBaseinfo.getUniscid());
                checkAndRevResult.setEntname(eBaseinfo.getEntname());
                checkAndRevResult.setRegOrgCN(StringUtils.isBlank(eBaseinfo.getRegorg()) ? "" : baseCodeService.getRegorgName(eBaseinfo.getRegorg()));
                checkAndRevResult.setSupOrgCn(StringUtils.isBlank(eBaseinfo.getSuporg()) ? "" : baseCodeService.getSuporg(eBaseinfo.getSuporg()));
                enableListAndCheckVos.add(checkAndRevResult);
            }
        }
        String enableListAndCheckId = UUID.randomUUID().toString();
        HashMap<String, Object> groupMap = new HashMap<>();
        groupMap.put("enableAndCheckList", enableListAndCheckVos);
        groupMap.put("enableAndCheckListId", enableListAndCheckId);
        redisService.set(REDIS_KEY_ENABLE_PREFIX + enableListAndCheckId, JSON.toJSONString(enableListAndCheckVos), 20 * 60);
        return RestResult.ok(groupMap);
    }

    //根据查询条件获取批吊现场核查列表
    @PostMapping("searchEnableList")
    public RestResult<?> searchEnableList(String enableAndCheckListId, String status, String result) {
        String json = redisService.get(REDIS_KEY_ENABLE_PREFIX + enableAndCheckListId);
        List<EnableListAndCheckVo> enableAndCheckList = JSON.parseArray(json, EnableListAndCheckVo.class);
        List<EnableListAndCheckVo> enableListAndCheckVos = new ArrayList<>();
        if (enableAndCheckList != null) {
            enableListAndCheckVos = enableAndCheckList.stream()
                    .filter(item ->
                            (StringUtils.isBlank(status) || item.getCheckStatus().equals(status))
                                    && (StringUtils.isBlank(result) || item.getCheckResult().equals(result)))
                    .collect(Collectors.toList());
        }
        HashMap<String, Object> groupMap = new HashMap<>();
        groupMap.put("enableAndCheckList", enableListAndCheckVos);
        return RestResult.ok(groupMap);
    }

    /**
     * 批量吊销业务主体名单按类型导出Excel
     *
     */
    @GetMapping("exportEntListbyType")
    public RestResult<?> exportEntListbyType(String bizseq, String exportType, HttpServletRequest request, HttpServletResponse response) {
        AssertUtils.isNotBlank(bizseq, exportType);
        ExcelWriter writer = null;
        LambdaQueryWrapper<BizRevEnt> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BizRevEnt::getBizseq, bizseq);
        TsCase caseDB = caseService.getByBizseq(bizseq);
        String caseName = caseDB.getCaseName();
        // 查询导出数据
        String fileName = "";
        List<BizRevEnt> listbyType = new ArrayList<>();
        if (exportType.equals("All")) {
            fileName = caseName + "-全部主体名单.xlsx";
            listbyType = bizRevEntService.list(wrapper);
        } else if (exportType.equals("process")) {
            fileName = caseName + "-业务在办主体名单.xlsx";
            wrapper.eq(BizRevEnt::getIsremove, "0");
            listbyType = bizRevEntService.list(wrapper);

        } else if (exportType.equals("removed")) {
            fileName = caseName + "-已剔除主体名单.xlsx";
            wrapper.eq(BizRevEnt::getIsremove, "1");
            listbyType = bizRevEntService.list(wrapper);
        } else {
            return RestResult.error(ResultCode.PARAM_IS_INVALID);
        }

        try {
            List<String> includeColumnFiledNames = new ArrayList<>();
            includeColumnFiledNames.add("uniscid");
            includeColumnFiledNames.add("regno");
            includeColumnFiledNames.add("entname");
            includeColumnFiledNames.add("name");
            includeColumnFiledNames.add("enttypeCn");
            OutputStream outputStream = response.getOutputStream();
            //添加响应头信息
            response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
            response.setContentType("application/msexcel;charset=UTF-8");//设置类型
            response.setHeader("Pragma", "No-cache");//设置头
            response.setHeader("Cache-Control", "no-cache");//设置头
            response.setDateHeader("Expires", 0);//设置日期头
            //实例化 ExcelWriter，传入输出流，excel格式，表头true
//            writer = new ExcelWriter(outputStream, ExcelTypeEnum.XLSX, true);

            ArrayList<TsbizrevlistExcelVo> list = new ArrayList<>();
            for (BizRevEnt each : listbyType) {
                TsbizrevlistExcelVo excelVo = new TsbizrevlistExcelVo();
                BeanUtils.copyProperties(each, excelVo);
//                excelVo.setSettime(DateUtils.localDateFormat(tsbizrevlist.getSettime(),DateUtils.DATE_DEFAULT_FORMAT));
                list.add(excelVo);
            }
            writer = EasyExcel.write(outputStream, TsbizrevlistExcelVo.class).includeColumnFiledNames(includeColumnFiledNames).build();
            //使用Lists.partition 将list集合按指定长度进行切分，避免导出数据量大于excel的上限
            List<List<TsbizrevlistExcelVo>> partition = Lists.partition(list, 10000);
            for (int i = 1; i <= partition.size(); i++) {
                com.alibaba.excel.metadata.Sheet sheet = new com.alibaba.excel.metadata.Sheet(i, 0, TsbizrevlistExcelVo.class);
                sheet.setSheetName("清单" + i);
                //输出
                writer.write(partition.get(i - 1), sheet);
            }
            writer.finish();
            outputStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.getOutputStream().close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return OK;
    }

    /**
     * 名单导出Excel前数据非空校验
     *
     * @param bizseq     业务号
     * @param exportType 导出类型
     * @return
     */
    @GetMapping("exportValid")
    public RestResult<?> exportValid(String bizseq, String exportType) {
        AssertUtils.isNotBlank(bizseq, exportType);
        LambdaQueryWrapper<BizRevEnt> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BizRevEnt::getBizseq, bizseq);
        if (exportType.equals("process")) {
            wrapper.eq(BizRevEnt::getIsremove, "0");
            int count = bizRevEntService.count(wrapper);
            if (count == 0) {
                return RestResult.error(ResultCode.DATA_NONE, "业务中无在办主体");
            }
        } else if (exportType.equals("removed")) {
            wrapper.eq(BizRevEnt::getIsremove, "1");
            int count = bizRevEntService.count(wrapper);
            if (count == 0) {
                return RestResult.error(ResultCode.DATA_NONE, "业务中无已剔除主体");
            }
        } else if (exportType.equals("all")) {
            int count = bizRevEntService.count(wrapper);
            if (count == 0) {
                return RestResult.error(ResultCode.DATA_NONE, "查询不到该业务相关主体");
            }
        } else {
            return RestResult.error(ResultCode.PARAM_IS_INVALID);
        }
        return OK;
    }

    /**
     * 根据工作流id及意见类型获取最新意见
     *
     * @param workflowId  工作流id
     * @param opinionType 意见类型
     * @param status      状态是否暂存
     * @return
     */
    @PostMapping("getNewestOpinion")
    public RestResult<?> getNewestOpinion(String workflowId, String opinionType, String status, String bizStatus) {
        AssertUtils.isNotBlank(workflowId, opinionType);
        if ("1".equals(status) && opinionType.equals(bizStatus)) {// 暂存，取暂存表信息
            LambdaQueryWrapper<RevokeTemp> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(RevokeTemp::getWorkflowid, workflowId)
                    .eq(RevokeTemp::getOpiniontype, opinionType)
                    .orderByDesc(RevokeTemp::getLauptime);
            List<RevokeTemp> list = revokeTempService.list(wrapper);
            if (CollectionUtils.isNotEmpty(list)) {
                return RestResult.ok(list.get(0));
            }
            return RestResult.ok();
        }
        return RestResult.ok(opinionService.getNewestOpinion(workflowId, opinionType));
    }

    /**
     * 获取业务中非开业主体列表
     *
     * @param pageRequestDto
     * @return
     */
    @PostMapping("getNoOpenRevListPage")
    public RestResult<?> getNoOpenRevListPage(@RequestBody PageRequestDto pageRequestDto) {
        AssertUtils.isNotNull(pageRequestDto, pageRequestDto.getCustomParamMap());
        Map<String, Object> paramMap = pageRequestDto.getCustomParamMap();
        String bizseq = StringUtils.tranObject(paramMap.get("bizseq"));
        AssertUtils.isNotEmpty(bizseq);
        // 查询时再验证
        validEntsRegstate(bizseq);

        IPage<Tsbizrevlist> page = tsbizrevlistService.getNoOpenRevListPage(new Page<>(pageRequestDto.getCurPage(), pageRequestDto.getPageSize()), paramMap);
        if (CollectionUtils.isNotEmpty(page.getRecords())) { // 封装企业状态
            Map<String, TRBaseCode> codeMap = baseCodeService.getBaseCodeMapFormCache("CA19");
            for (Tsbizrevlist record : page.getRecords()) {
                EBaseinfo eBaseinfo = eBaseinfoService.getOne(new LambdaQueryWrapper<EBaseinfo>().eq(EBaseinfo::getPripid, record.getPripid()));
                record.setRegstate(eBaseinfo.getRegstate());
                TRBaseCode code = codeMap.get(eBaseinfo.getRegstate());
                if (code != null) {
                    record.setRegstateCn(code.getName());
                }
                if (record.getEnttypeCn() == null) {
                    TREntPriseType type = entPriseTypeService.getEntPriseTypeFromCache(record.getEnttype());
                    if (type != null) {
                        record.setEnttypeCn(type.getDisplayvalue());
                    }
                }

            }
        }
        return RestResult.ok(page);
    }

    /**
     * 批吊信息暂存
     *
     * @param request
     * @param tsCaseModel
     * @param bizseq
     * @param opinionModel
     * @param tasklistid
     * @param nextPerformerids
     * @return
     */
    @Transactional
    @PostMapping("tempSave")
    public RestResult<?> tempSave(HttpServletRequest request, TsCase tsCaseModel, String bizseq, TSOpinion opinionModel,
                                  String tasklistid, String bizStatus, String nextPerformerids) {
        AssertUtils.isNotEmpty(bizseq, tasklistid, opinionModel.getWorkflowid());
        AICUser user = getLoginUser(request);
        if (user == null) throw new BusinessException("登录超时，请重新登录");

        if ("1".equals(bizStatus)) {
            if (StringUtils.isNotEmpty(tsCaseModel.getIllegalAct())) {// 违法行为中文
                String[] split = tsCaseModel.getIllegalAct().split(Constant.COMMA);
                String s = split[split.length - 1];
                CmsDictCode dictCode = cmsDictCodeService.getList("illegalAct", s);
                tsCaseModel.setIllegalActCn(dictCode.getLabel());
            }
        }
        // 案件信息项直接保存，加多暂存状态标识，为暂存状态
        tsCaseModel.setStatus("1");// 标记暂存
        boolean update = caseService.updateById(tsCaseModel);
        if (!update) {
            return RestResult.error(ResultCode.BUSINESS_LOGIC_ERROR, "暂存失败");
        }
        LocalDateTime now = LocalDateTime.now();
        // 意见等存临时表
        if (opinionModel != null) {//判断是否有意见
            RevokeTemp revokeTemp = new RevokeTemp();
            revokeTemp.setWorkflowid(opinionModel.getWorkflowid());
            revokeTemp.setOpiniontype(opinionModel.getOpiniontype());
            revokeTemp.setHandler(user.getName());
            revokeTemp.setHandlerid(user.getPrimaryKey());
//            revokeTemp.setIsagree(opinionModel.getIsagree());
            revokeTemp.setLauptime(now);
            revokeTemp.setNexthandlerid(nextPerformerids);
            revokeTemp.setOpinioncontent(opinionModel.getOpinioncontent());
            if (opinionModel.getHandledate() != null) {
                revokeTemp.setHandledate(opinionModel.getHandledate());
            }
            boolean save = revokeTempService.save(revokeTemp);
            if (!save) {
                throw new BusinessException("暂存失败!");
            }
        }
        return RestResult.ok();
    }

    /**
     * 批吊相关条件类型企业清单导出
     *
     * @param response
     * @return
     */
    @PostMapping("revokeEntListExport")
    public RestResult<?> revokeEntListExport(@RequestBody PageRequestDto pageRequestDto, HttpServletRequest request, HttpServletResponse response) {
        AICUser loginUser = getLoginUser(request);
        if (loginUser == null) {
            return RestResult.error(ResultCode.USER_NOT_LOGGED_IN);
        }
        Map<String, Object> customParamMap = pageRequestDto.getCustomParamMap();
        String searchUscc = StringUtils.tranObject(customParamMap.get("searchUscc"));
        if (StringUtils.isNotBlank(searchUscc)) {
            if (StringUtils.isUscc(searchUscc)) {
                customParamMap.put("uniscid", searchUscc);
            } else {
                customParamMap.put("regno", searchUscc);
            }
        }
        String type = StringUtils.tranObject(customParamMap.get("type"));
        String isGRDZ = StringUtils.tranObject(customParamMap.get("isGRDZ"));
        String yearReport = StringUtils.tranObject(customParamMap.get("yearReport"));
        AssertUtils.isNotEmpty(type, isGRDZ);
        if (StringUtils.isNotEmpty(isGRDZ)) {
            if ("GRDZ".equals(isGRDZ)) {
                customParamMap.put("sole", Constant.REVOKE_SOLE_CODE);
            } else if ("NOGRDZ".equals(isGRDZ)) {
                customParamMap.put("company", Constant.REVOKE_COMPANY_CODE);
            }
        }

        //片区查询属地监管机关
        if (StringUtils.isNotBlank(StringUtils.tranObject(customParamMap.get("regulatory")))) {
            List<String> regulatory = (List<String>) customParamMap.get("regulatory");
            if (regulatory.size() > 0) {
                String suporg = regulatory.get(regulatory.size() - 1);
                List<String> idsByParentId = areaSliceService.getIdsByParentId(suporg);     //获取所有子片区id
                idsByParentId.add(suporg);      //加上父id
                customParamMap.put("regulatoryList", idsByParentId);
            }
        }
        //登记机关
        if (StringUtils.isNotBlank(StringUtils.tranObject(customParamMap.get("regorg")))) {
            List<String> regorg = (List<String>) customParamMap.get("regorg");
            if (regorg.size() > 0) {
                customParamMap.put("regorgFinal", regorg.get(regorg.size() - 1));   //找出机关列表中的最后一个
            }
        }
        //成立日期
        Object searchDate = customParamMap.get("establishDate");
        if (searchDate instanceof List) {
            List<String> list = (List<String>) searchDate;
            customParamMap.put("eststartDate", list.get(0));
            customParamMap.put("estendDate", list.get(1));
        }
        //核准日期
        Object apprDate = customParamMap.get("apprDate");
        if (apprDate instanceof List) {
            List<String> list = (List<String>) apprDate;
            customParamMap.put("apprDatestart", list.get(0));
            customParamMap.put("apprDateend", list.get(1));
        }

        IPage<EBaseinfo> page = null;
        String filename = "名单清单.xlsx";
        if ("abn".equals(type)) {// 实地查无列异两年以上
            LocalDate date = LocalDate.now().minusYears(2);
            customParamMap.put("abntime", DateUtils.localDateFormat(date, DateUtils.DATE_DEFAULT_FORMAT));
            page = eBaseinfoService.getSDCWandTwoYearsPage(new Page<>(1, -1, false), customParamMap);
            filename = "因实地查无列入经营异常名录两年以上-" + filename;
        } else if ("wnb2".equals(type)) {// 连续两年未年报
            // 获取当前日期
            LocalDate currentDate = LocalDate.now();
            int year = currentDate.getYear();
            // 构造6月30日的日期,6月30号为年报提交日期
            LocalDate endDate = LocalDate.of(year, 6, 30);
            String[] reportYear;
            if (currentDate.isBefore(endDate)) {
                reportYear = new String[]{String.valueOf(year - 2), String.valueOf(year - 3)};
            } else {
                reportYear = new String[]{String.valueOf(year - 1), String.valueOf(year - 2)};
            }
            List<String> listyear = Arrays.asList(reportYear);
            customParamMap.put("reportYear", listyear);
            customParamMap.put("yearSize", 2);
            page = eBaseinfoService.getNoReportPage(new Page<>(1, -1, false), customParamMap);
            filename = "连续两年未年报-" + filename;
        }
/*
        else if("wnb5".equals(type)) {// 连续五年未年报
            int year = LocalDate.now().getYear();
            String[] reportYear = new String[]{String.valueOf(year-1),String.valueOf(year-2),String.valueOf(year-3),String.valueOf(year-4),String.valueOf(year-5)};
            customParamMap.put("reportYear",reportYear);
            customParamMap.put("yearSize",5);
            page = eBaseinfoService.getNoReportPage(new Page<>(1,-1), customParamMap);
            filename = "连续五年未年报-" + filename;
        }
*/
        else if ("wnbSdcw".equals(type)) {// 两年未年报实地查无
            // 获取当前日期
            LocalDate currentDate = LocalDate.now();
            int year = currentDate.getYear();
            // 构造6月30日的日期,6月30号为年报提交日期
            LocalDate endDate = LocalDate.of(year, 6, 30);
            String[] reportYear;
            if (currentDate.isBefore(endDate)) {
                reportYear = new String[]{String.valueOf(year - 2), String.valueOf(year - 3)};
            } else {
                reportYear = new String[]{String.valueOf(year - 1), String.valueOf(year - 2)};
            }
            List<String> listyear = Arrays.asList(reportYear);
            customParamMap.put("reportYear", listyear);
            page = eBaseinfoService.getWnbAndSdcwPage(new Page<>(1, -1, false), customParamMap);
            filename = "两年未年报实地查无-" + filename;
        }
        if (page == null || CollectionUtils.isEmpty(page.getRecords())) {
            return RestResult.error(ResultCode.DATA_NONE);
        }
        List<EBaseinfo> records = page.getRecords();
        ExcelWriter writer = null;
        try {
            List<String> includeColumnFiledNames = new ArrayList<>();
            Lists.newArrayList("uniscid");
            includeColumnFiledNames.add("uniscid");
            includeColumnFiledNames.add("regno");
            includeColumnFiledNames.add("entname");
            includeColumnFiledNames.add("name");
            includeColumnFiledNames.add("enttypeCn");
            includeColumnFiledNames.add("dom");
            includeColumnFiledNames.add("suporgCn");
            includeColumnFiledNames.add("phone");
            includeColumnFiledNames.add("regorgCn");
            includeColumnFiledNames.add("regstateCn");
            includeColumnFiledNames.add("opscotypeCn");
            OutputStream outputStream = response.getOutputStream();
            //添加响应头信息
            response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode(filename, "UTF-8"));
            response.setContentType("application/msexcel;charset=UTF-8");//设置类型
            response.setHeader("Pragma", "No-cache");//设置头
            response.setHeader("Cache-Control", "no-cache");//设置头
            response.setDateHeader("Expires", 0);//设置日期头
            //实例化 ExcelWriter，传入输出流，excel格式，表头true
//            writer = new ExcelWriter(outputStream, ExcelTypeEnum.XLSX, true);

            ArrayList<TsbizrevlistExcelVo> list = new ArrayList<>();
            Map<String, TRBaseCode> codeMap = baseCodeService.getBaseCodeMapFormCache("CA19");
            for (EBaseinfo each : records) {
                TsbizrevlistExcelVo excelVo = new TsbizrevlistExcelVo();
                BeanUtils.copyProperties(each, excelVo);
                // 主体类型
                if (StringUtils.isEmpty(excelVo.getEnttypeCn())) {
                    TREntPriseType code = entPriseTypeService.getEntPriseTypeFromCache(each.getEnttype());
                    if (code != null) {
                        excelVo.setEnttypeCn(code.getDisplayvalue());
                    }
                }
                // 经营状态
                if (each.getRegstate() != null) {
                    TRBaseCode code = codeMap.get(each.getRegstate());
                    if (code != null) {
                        excelVo.setRegstateCn(code.getName());
                    }
                }
                // 登记机关
                if (each.getRegorg() != null) {
                    String regorgName = baseCodeService.getRegorgName(each.getRegorg());
                    if (regorgName != null) {
                        excelVo.setRegorgCn(regorgName);
                    }

                }
                // 主营项目类别
                if (StringUtils.isNotBlank(each.getIndustryco()) && each.getIndustryco().length() > 1) {
                    excelVo.setOpscotypeCn(IndustryConstant.getIndustryCN(each.getIndustryco().substring(0, 2)));
                }
                //属地监管机关
                excelVo.setSuporgCn(iGzaiccodeService.getNameByCode(each.getSuporg()));
                list.add(excelVo);
            }
            writer = EasyExcel.write(outputStream, TsbizrevlistExcelVo.class).includeColumnFiledNames(includeColumnFiledNames).build();
            //使用Lists.partition 将list集合按指定长度进行切分，避免导出数据量大于excel的上限
            List<List<TsbizrevlistExcelVo>> partition = Lists.partition(list, 10000);
            for (int i = 1; i <= partition.size(); i++) {
                com.alibaba.excel.metadata.Sheet sheet = new com.alibaba.excel.metadata.Sheet(i, 0);
//                sheet.setHead(head1);
                sheet.setSheetName("清单" + i);
                writer.write(partition.get(i - 1), sheet);
            }
            writer.finish();
            outputStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.getOutputStream().close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return OK;
    }


    /**
     * 获取非开业未剔除的名单总数
     *
     * @param bizseq 业务号
     * @return
     */
    @GetMapping("getNoOpenAndNoRemoveNum")
    public RestResult<?> getNoOpenAndNoRemoveNum(String bizseq) {
        AssertUtils.isNotNull(bizseq);
        LambdaQueryWrapper<BizRevEnt> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BizRevEnt::getBizseq, bizseq)
                .eq(BizRevEnt::getIsremove, "0")
                .eq(BizRevEnt::getNoopenstate, "1");
        List<BizRevEnt> list = bizRevEntService.list(wrapper);
        return RestResult.ok(list.size());
    }

    @ApiOperation(value = "第一份处罚决定书下载")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "bizseq", value = "业务号", required = true),
    })
    @GetMapping("/downFirstPunishDec")
    public RestResult<?> downFile(@RequestParam("bizseq") String bizseq, HttpServletResponse response) {
//        String url = filePath + File.separator + fileName;
        AssertUtils.isNotEmpty(bizseq);
        TSAttachment tsAttachment = new TSAttachment();
        tsAttachment.setBizseq(bizseq).setAttachtype("20");
        List<TSAttachment> tsAttachments = tsAttachmentService.selectwritByPage(tsAttachment);
        if (CollectionUtils.isEmpty(tsAttachments)) {
            return RestResult.error(ResultCode.DATA_NONE, "找不到附件");
        }
        String filePath = tsAttachments.get(0).getTemppath();
        String fileName = tsAttachments.get(0).getFilename();
        String ext = filePath.substring(filePath.lastIndexOf(Constant.DOT));
        try {
            response.setContentType("application/octet-stream");
            response.addHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8"));

//            response.setHeader("Content-Disposition", "attachment;  filename=\"" + fileName + "\"");
            ServletOutputStream os = response.getOutputStream();
            fileStorageService.writeToStream(CommonConfig.getUploadPath() + File.separator + filePath, os);
            return OK;
        } catch (IOException e) {
            log.error("下载文件发生错误，" + e.getMessage());
            return RestResult.error(ResultCode.DATA_NONE, "下载文件错误");
        }

    }

    /**
     * 批量吊销任务转办列表
     *
     * @param pageRequestDto
     * @return
     * @author ymc
     * @since 2024年8月16日 10:45
     */
    @PostMapping("batchRevokeForwardTask")
    public RestResult<?> batchRevokeForwardTask(@RequestBody PageRequestDto pageRequestDto) {
        IPage<TaskListUnionDto> page = tsrevtasklistService.batchRevokeForwardTask(pageRequestDto);
        return RestResult.ok(page);
    }

    /**
     * 批量吊销任务转办
     *
     * @param tasklistid 待办id
     * @param userId     转办用户userId
     * @return
     * @author ymc
     * @since 2024年8月16日 11:13
     */
    @GetMapping("batchRevokeForward")
    public RestResult<?> batchRevokeForward(@RequestParam String tasklistid, @RequestParam String userId) {
        tsrevtasklistService.batchRevokeForward(tasklistid, userId);
        return RestResult.ok();
    }

    /**
     * 转办用户列表
     *
     * @param orgId
     * @return
     * @author ymc
     * @since 2024年8月16日 16:45
     */
    @GetMapping("getBatchRevokeForwardUsers")
    public RestResult<?> getBatchRevokeForwardUsers(@RequestParam String orgId) {
        return RestResult.ok(orgUM.findUsersByOrgPK(orgId, false));
    }

    /**
     * 批量直接吊销市场主体（无需审批）
     * 接口直接吊销市场主体，无需经过审核审批流程
     *
     * @param dto     批量直接吊销请求参数
     * @param request
     * @return 吊销结果（成功数量、失败数量、失败列表）
     */
    @ApiOperation(value = "批量直接吊销市场主体（执法系统）", notes = "直接吊销市场主体，无需审核审批流程（执法系统）")
    @PostMapping("directRevoke")
    public RestResult<DirectRevokeResultDto> directRevoke(@RequestBody @Validated DirectRevokeDto dto, HttpServletRequest request) {
        AICUser user = getLoginUser(request);
        if (user == null) {
            return RestResult.error(ResultCode.USER_NOT_LOGGED_IN);
        }

        if (CollectionUtils.isEmpty(dto.getPripids())) {
            return RestResult.error(ResultCode.PARAM_IS_BLANK, "主体列表不能为空");
        }

        try {
            DirectRevokeResultDto result = tsbizrevlistService.directRevoke(dto, user);
            return RestResult.ok(result);
        } catch (Exception e) {
            log.error("批量直接吊销失败", e);
            return RestResult.error(ResultCode.BUSINESS_LOGIC_ERROR, "批量直接吊销失败：" + e.getMessage());
        }
    }

    /**
     * 查询未吊销的市场主体分页列表
     * 查询开业状态且未被吊销的市场主体
     *
     * @param query   分页查询参数（BaseQuery包含分页信息和UnrevokedEntQueryDto查询条件）
     * @param request
     * @return 分页列表
     */
    @ApiOperation(value = "查询未吊销的市场主体分页列表（执法系统）", notes = "查询开业状态且未被吊销的市场主体（执法系统）")
    @PostMapping("unrevokedList")
    public RestResult<?> unrevokedList(@RequestBody BaseQuery<UnrevokedEntQueryDto> query, HttpServletRequest request) {

        AICUser user = getLoginUser(request);
        if (user == null) {
            return RestResult.error(ResultCode.USER_NOT_LOGGED_IN);
        }

        try {
            // 获取查询条件实体
            UnrevokedEntQueryDto queryDto = query.getEntity(UnrevokedEntQueryDto.class);
            if (queryDto == null) {
                queryDto = new UnrevokedEntQueryDto();
            }
            AssertUtils.isNotBlank(queryDto.getCaseid());

            // 构建分页对象
            Page<EBaseinfo> page = new Page<>(query.getCurrent(), query.getSize());
            LambdaQueryWrapper<EBaseinfo> wrapper = new LambdaQueryWrapper<>();

            // 只查询开业状态的市场主体
            wrapper.eq(EBaseinfo::getRegstate, "1");

            if (StringUtils.equals(queryDto.getIsDeal(), CommonConstants.TRUE_1)) {
                wrapper.exists("SELECT 1 FROM revokelist r WHERE r.PRIPID = e_baseinfo.PRIPID");
            } else if (StringUtils.equals(queryDto.getIsDeal(), CommonConstants.FALSE_0)) {
                wrapper.notExists("SELECT 1 FROM revokelist r WHERE r.PRIPID = e_baseinfo.PRIPID");
            }

            // 排除已吊销的市场主体（通过子查询排除）
            wrapper.exists(String.format("SELECT 1 FROM PENALTY_ENT_INFO p WHERE p.PRIPID = e_baseinfo.PRIPID" +
                    " AND p.FLG_DELETED != '1' and p.CASEID = '%s'", queryDto.getCaseid()));

            // 条件查询
            if (StringUtils.isNotBlank(queryDto.getEntname())) {
                wrapper.like(EBaseinfo::getEntname, queryDto.getEntname());
            }
            if (StringUtils.isNotBlank(queryDto.getUniscid())) {
                wrapper.eq(EBaseinfo::getUniscid, queryDto.getUniscid());
            }
            if (StringUtils.isNotBlank(queryDto.getRegno())) {
                wrapper.eq(EBaseinfo::getRegno, queryDto.getRegno());
            }
            if (StringUtils.isNotBlank(queryDto.getEnttype())) {
                wrapper.eq(EBaseinfo::getEnttype, queryDto.getEnttype());
            }
            if (StringUtils.isNotBlank(queryDto.getRegorg())) {
                wrapper.eq(EBaseinfo::getRegorg, queryDto.getRegorg());
            }

            // 根据用户机关过滤
            String userOrg = StringUtils.substring(user.getRegionID(), 0, 6);
            if (StringUtils.isNotBlank(userOrg)) {
                wrapper.apply("SUBSTR(REGORG, 1, 6) = {0}", userOrg);
            }

            wrapper.orderByDesc(EBaseinfo::getPripid);

            IPage<EBaseinfo> result = eBaseinfoService.page(page, wrapper);
            return RestResult.ok(result);
        } catch (Exception e) {
            log.error("查询未吊销市场主体列表失败", e);
            return RestResult.error(ResultCode.BUSINESS_LOGIC_ERROR, "查询失败：" + e.getMessage());
        }
    }

    /**
     * 案件信息分页查询
     *
     * @param baseQuery 分页和筛选参数
     * @return
     */
    @ApiOperation("案件信息分页查询")
    @PostMapping("/getPenaltyCaseInfoPage")
    public RestResult<IPage<PenaltyCaseInfo>> getPenaltyCaseInfoPage(@RequestBody BaseQuery<PenaltyCaseInfoQueryDTO> baseQuery) {
        try {
            AssertUtils.isNotNull(baseQuery);

            PenaltyCaseInfoQueryDTO queryDTO = baseQuery.getEntity(PenaltyCaseInfoQueryDTO.class);

            LambdaQueryWrapper<PenaltyCaseInfo> wrapper = new LambdaQueryWrapper<>();

            if (queryDTO != null) {
                // 案件编号
                wrapper.eq(StringUtils.isNotBlank(queryDTO.getCaseid()), PenaltyCaseInfo::getCaseid, queryDTO.getCaseid());
                wrapper.like(StringUtils.isNotBlank(queryDTO.getCaseidlike()), PenaltyCaseInfo::getCaseid, queryDTO.getCaseidlike());

                // 案件名称
                if (StringUtils.isNotBlank(queryDTO.getCasename())) {
                    wrapper.like(PenaltyCaseInfo::getCasename, queryDTO.getCasename());
                }

                // 案由
                if (StringUtils.isNotBlank(queryDTO.getCaseintroduction())) {
                    wrapper.like(PenaltyCaseInfo::getCaseintroduction, queryDTO.getCaseintroduction());
                }

                // 违法行为
                if (StringUtils.isNotBlank(queryDTO.getIllegality())) {
                    wrapper.like(PenaltyCaseInfo::getIllegality, queryDTO.getIllegality());
                }

                // 处罚决定机关
                if (StringUtils.isNotBlank(queryDTO.getPenaltyorg())) {
                    wrapper.like(PenaltyCaseInfo::getPenaltyorg, queryDTO.getPenaltyorg());
                }

                // 是否已办
                if (StringUtils.equals(queryDTO.getIsDeal(), CommonConstants.TRUE_1)) {
                    wrapper.exists("select 1 from PENALTY_ENT_INFO pei where pei.CASEID = PENALTY_CASE_INFO.CASEID and pei.FLG_DELETED != '1' " +
                            " and exists(select 1 from REVOKELIST e where e.PRIPID = pei.PRIPID)");
                } else if (StringUtils.equals(queryDTO.getIsDeal(), CommonConstants.FALSE_0)) {
                    wrapper.notExists("select 1 from PENALTY_ENT_INFO pei where pei.CASEID = PENALTY_CASE_INFO.CASEID and pei.FLG_DELETED != '1' " +
                            " and exists(select 1 from REVOKELIST e where e.PRIPID = pei.PRIPID)");
                }

                // 处罚决定日期范围
                if (queryDTO.getPenaltydateStart() != null) {
                    wrapper.ge(PenaltyCaseInfo::getPenaltydate, queryDTO.getPenaltydateStart());
                }
                if (queryDTO.getPenaltydateEnd() != null) {
                    wrapper.le(PenaltyCaseInfo::getPenaltydate, queryDTO.getPenaltydateEnd());
                }
            }

            // 默认查询未删除的记录
            wrapper.eq(PenaltyCaseInfo::getFlgDeleted, "0");

            // 按创建时间倒序
            wrapper.orderByDesc(PenaltyCaseInfo::getCreateTime);

            return RestResult.ok(penaltyCaseInfoService.page(new Page<>(baseQuery.getCurrent(), baseQuery.getSize()), wrapper));
        } catch (Exception e) {
            log.error("查询案件信息列表失败", e);
            return RestResult.error(ResultCode.BUSINESS_LOGIC_ERROR, "查询失败：" + e.getMessage());
        }
    }
}

