package com.chinaweal.aiccs.aiccs.force.service.impl;

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.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chinaweal.aiccs.aiccs.abnormal.entity.EBaseinfo;
import com.chinaweal.aiccs.aiccs.abnormal.entity.TSWrit;
import com.chinaweal.aiccs.aiccs.abnormal.service.EBaseinfoService;
import com.chinaweal.aiccs.aiccs.abnormal.service.IGzaiccodeService;
import com.chinaweal.aiccs.aiccs.abnormal.service.TSWritService;
import com.chinaweal.aiccs.aiccs.business.entity.XrTaskList;
import com.chinaweal.aiccs.aiccs.business.entity.vo.XrTaskListVo;
import com.chinaweal.aiccs.aiccs.business.rules.init.FlowUtil;
import com.chinaweal.aiccs.aiccs.business.service.IXrTaskListService;
import com.chinaweal.aiccs.aiccs.force.entity.XrForceDeregister;
import com.chinaweal.aiccs.aiccs.force.entity.XrForceDeregisterRes;
import com.chinaweal.aiccs.aiccs.force.entity.XrForceDeregisterSpe;
import com.chinaweal.aiccs.aiccs.force.entity.XrForceNotice;
import com.chinaweal.aiccs.aiccs.force.entity.querydto.ForceDeregisterSpeQueryDto;
import com.chinaweal.aiccs.aiccs.force.entity.querydto.ForceDeregisterSpeSaveDto;
import com.chinaweal.aiccs.aiccs.force.entity.vo.XrForceDeregisterSpeVo;
import com.chinaweal.aiccs.aiccs.force.mapper.XrForceDeregisterSpeMapper;
import com.chinaweal.aiccs.aiccs.force.service.IXrForceDeregisterResService;
import com.chinaweal.aiccs.aiccs.force.service.IXrForceDeregisterService;
import com.chinaweal.aiccs.aiccs.force.service.IXrForceDeregisterSpeService;
import com.chinaweal.aiccs.aiccs.force.service.IXrForceNoticeService;
import com.chinaweal.aiccs.aiccs.inspect.service.TSWorkNoService;
import com.chinaweal.aiccs.aiccs.revoke.entity.BatchRevokePushRecord;
import com.chinaweal.aiccs.aiccs.revoke.service.BatchRevokePushRecordService;
import com.chinaweal.aiccs.aiccs.revoke.service.CreateFileService;
import com.chinaweal.aiccs.aiccs.seriousillegalPerson.common.emnu.AuthEnum;
import com.chinaweal.aiccs.aiccs.system.entity.TRBaseCode;
import com.chinaweal.aiccs.aiccs.system.service.TRBaseCodeService;
import com.chinaweal.aiccs.aiccs.writs.entity.Tswrittemplate;
import com.chinaweal.aiccs.aiccs.writs.service.TswrittemplateService;
import com.chinaweal.aiccs.common.constant.BaseDataConstant;
import com.chinaweal.aiccs.common.constant.FlowConstant;
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.org.service.AicorgService;
import com.chinaweal.aicorg.model.AICUser;
import com.chinaweal.aicorg.pojo.AICPermission;
import com.chinaweal.youfool.framework.springboot.base.query.BaseQuery;
import com.chinaweal.youfool.framework.springboot.exception.custom.BusinessException;
import com.chinaweal.youfool.framework.springboot.util.ExpiryMap;
import com.google.common.collect.Lists;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 拟强制注销/强制注销业务表 服务实现类
 *
 * @author zhouxy
 * @since 2025/9/26
 */
@Service
public class XrForceDeregisterSpeServiceImpl extends ServiceImpl<XrForceDeregisterSpeMapper, XrForceDeregisterSpe> implements IXrForceDeregisterSpeService {

    @Resource
    private EBaseinfoService iEBaseinfoService;
    @Resource
    private IXrTaskListService iXrTaskListService;
    @Resource
    private IXrForceDeregisterService iXrForceDeregisterService;
    @Resource
    private IXrForceDeregisterResService iXrForceDeregisterResService;
    @Resource
    private IXrForceNoticeService iXrForceNoticeService;
    @Resource
    private AicorgService aicorgService;
    @Resource
    private TswrittemplateService tswrittemplateService;
    @Resource
    private TRBaseCodeService trBaseCodeService;
    @Resource
    private TSWritService tsWritService;
    @Resource
    private TSWorkNoService tsWorkNoService;
    @Autowired
    private CreateFileService createFileService;
    @Autowired
    private IGzaiccodeService gzaiccodeService;
    @Resource
    private BatchRevokePushRecordService batchRevokePushRecordService;

    private static final ExpiryMap<String, Collection<?>> EXPIRY_MAP = new ExpiryMap<>(15 * 60);

    @Override
    public IPage<XrForceDeregisterSpeVo> listXrForceDeregisterSpe(BaseQuery<ForceDeregisterSpeQueryDto> query, AICUser user) {
        Map<String, AICPermission> aicPermissions = user.getAicPermissions();
        // 权限
        List<String> authList = new ArrayList<>();
        authList.add(user.getPrimaryKey());
        if (aicPermissions.containsKey(AuthEnum.XR_HANDLE.getTsPermissionCode())) {
            authList.add(user.getRegionID() + ":" + AuthEnum.XR_HANDLE.getCode());
        }
        ForceDeregisterSpeQueryDto entity = query.getEntity(ForceDeregisterSpeQueryDto.class);
        entity.setAuthList(authList);
        IPage<XrForceDeregisterSpeVo> xrForceDeregisterSpeIPage;
        Page<XrForceDeregisterSpe> page = new Page<>(query.getCurrent(), query.getSize());
        if (Objects.equals(entity.getBusType(), "todo")) {  //待办
            entity.setBusStatus("0");
            xrForceDeregisterSpeIPage = baseMapper.selectXrForceDeregisterSpeTodo(page, entity);
        } else if (Objects.equals(entity.getBusType(), "history")) {    //记录
            String regOrg = aicorgService.getOrgnumberByUserLevel(user, false);
            entity.setRegOrg(regOrg);
            xrForceDeregisterSpeIPage = baseMapper.selectXrForceDeregisterSpeHistory(page, entity);
        } else {
            throw new BusinessException("查询列表类型错误，请联系管理员处理");
        }
        return xrForceDeregisterSpeIPage;
    }

    @Override
    public IPage<EBaseinfo> baseinfoListByRegOrg(BaseQuery<ForceDeregisterSpeQueryDto> query, AICUser user) {
        ForceDeregisterSpeQueryDto entity = query.getEntity(ForceDeregisterSpeQueryDto.class);

        // 获取用户地区ID并设置为9位
        String regionID = user.getRegionID();
//        if (regionID.length() == 6) {
//            regionID = regionID + "000";
//        }
//        entity.setRegOrg(regionID);
        //改为用映射后的登记机关
        entity.setAcceptRegorg(regionID);

        Page<EBaseinfo> page = new Page<>(query.getCurrent(), query.getSize());

        // 调用手写 SQL 查询
        IPage<EBaseinfo> eBaseinfoIPage = baseMapper.baseinfoListByRegOrg(page, entity);

        // 处理 EnterType 赋值逻辑
//        for (EBaseinfo eBaseinfo : eBaseinfoIPage.getRecords()) {
//            String entType = eBaseinfo.getEnttype();
//            if (StringUtils.equalsAny(entType,"9910","9500")) {
//                eBaseinfo.setEnterType("individual");
//            } else if (StringUtils.equalsAny(entType,"9100","9200")) {
//                eBaseinfo.setEnterType("farmer");
//            } else {
//                eBaseinfo.setEnterType("company");
//            }
//
//            // 吊销时间已通过 SQL 关联 E_REVOKE 表的 REVDATE 字段查询并设置
//            if (StringUtils.equals(eBaseinfo.getRegstate(),"2") && eBaseinfo.getRevDate() == null){
//                eBaseinfo.setRevDate(eBaseinfo.getApprdate() != null ? eBaseinfo.getApprdate().toString() : null);
//            }
//        }
        return eBaseinfoIPage;
    }

    @Override
    public XrTaskListVo saveSpeAcceptList(ForceDeregisterSpeQueryDto queryDto, AICUser user) {
        String bizSeqNo = queryDto.getBizSeqNo();
        String taskLikeId = queryDto.getTaskLikeId();
        boolean isNew = false;
        if (queryDto.getPripIdList().isEmpty()) {
            throw new BusinessException("主体主键不能为空");
        }
        //判断是新增的业务还是在原来的业务上继续添加拟强制注销主体
        if (StringUtils.isEmpty(bizSeqNo)) {
            bizSeqNo = UUID.randomUUID().toString();
            isNew = true;
        }

        List<String> pripIdList = queryDto.getPripIdList();
        StringBuilder entName = new StringBuilder();

        List<List<String>> newPripIdList = Lists.partition(pripIdList, 400);
        List<EBaseinfo> eBaseinfos = new ArrayList<>();
        for (List<String> list : newPripIdList) {
            eBaseinfos.addAll(iEBaseinfoService.listByIds(list));
        }

        List<XrForceDeregisterSpe> xrForceDeregisterSpeList = new ArrayList<>();
        String forceId = UUID.randomUUID().toString();
        String noticeTitle = user.getOrgName() + "拟强制注销公司登记公告";
        for (EBaseinfo eBaseinfo : eBaseinfos) {
            entName.append(eBaseinfo.getEntname()).append("、");
            // 开启业务，先生成拟强制注销业务表，在受理后（即下一环节）再生成拟强制注销公告数据
            XrForceDeregisterSpe xrForceSpe = new XrForceDeregisterSpe();
            String forceSpeId = UUID.randomUUID().toString();
            xrForceSpe.setForceSpeId(forceSpeId)
                    .setForceResId(forceSpeId)
                    .setForceId(forceId)
                    .setBizSeqNo(bizSeqNo)
                    .setPripId(eBaseinfo.getPripid())
                    .setUniscId(eBaseinfo.getUniscid())
                    .setRegno(eBaseinfo.getRegno())
                    .setEntName(eBaseinfo.getEntname())
                    .setRegOrg(eBaseinfo.getAcceptRegorg())
                    .setRegOrgCn(eBaseinfo.getRegorgCn())
                    .setStatus(FlowConstant.LINK_STATUS_ZERO)
                    .setNoticeTitle(noticeTitle)
                    .setApplyTime(LocalDateTime.now())
                    .setForceType("1") //拟强制注销
                    .setAcceptOrg(user.getRegionID());
            // 保存业务信息
            xrForceDeregisterSpeList.add(xrForceSpe);
        }
        this.saveBatch(xrForceDeregisterSpeList);

        if (isNew) {  //若是新增的业务，需要开启新的待办
            // 开启待办
            XrTaskList xrTaskList = new XrTaskList();
            taskLikeId = UUID.randomUUID().toString();
            xrTaskList.setTaskLikeId(taskLikeId);
            xrTaskList.setBizSeqNo(bizSeqNo);
            xrTaskList.setBusType(BaseDataConstant.BUSINESS_TYPE_FORCE_DEREGISTER);
            xrTaskList.setAreaCode(user.getRegionID().substring(0, 6));
            if (eBaseinfos.size() > 2) {
                xrTaskList.setBusName(eBaseinfos.get(0).getEntname() + "、" + eBaseinfos.get(1).getEntname() + "等" + eBaseinfos.size() + "家主体");
            } else {
                xrTaskList.setBusName(entName.substring(0, entName.length() - 1));
            }
            xrTaskList.setApplyOrgId(user.getOrgID());
            xrTaskList.setWorkFlowId(FlowUtil.FORCE_DEREGISTER_WORK_FLOW);
            // 保存待办信息
            iXrTaskListService.startWorkFlow(xrTaskList, new String[]{user.getPrimaryKey()}, null, pripIdList, user);
        }

        return new XrTaskListVo(taskLikeId, bizSeqNo, "");
    }


    @Override
    public String getForceDeregisterContent(AICUser user, ForceDeregisterSpeSaveDto forceSaveDto) {
        //查找对应的模板
        Tswrittemplate templateDB = tswrittemplateService.getOne(new LambdaQueryWrapper<Tswrittemplate>()
                .eq(Tswrittemplate::getWritsType, WorkNoUtil.WORKNOTYPE_71)
                .eq(Tswrittemplate::getIsTemplate, "1"));

        //查出拟强制注销业务数据
        List<XrForceDeregisterSpe> speList = this.list(new LambdaQueryWrapper<XrForceDeregisterSpe>()
                .eq(XrForceDeregisterSpe::getBizSeqNo, forceSaveDto.getBizSeqNo()));
        //处理公司名称字段
        //取第一家公司的名称
        String entName = speList.get(0).getEntName();
        if (speList.size() > 1) {
            //取公司共计数量
            entName = entName + "等" + speList.size() + "户公司（另附附件）";
        }
        //查对应的拟强制注销登记法定事由
        String forceRraCn = "";
        if (StringUtils.isNotEmpty(forceSaveDto.getForceRra())) {
            TRBaseCode xrbasecode = trBaseCodeService.getOne(new LambdaQueryWrapper<TRBaseCode>()
                    .eq(TRBaseCode::getCodeid, "C13042")
                    .eq(TRBaseCode::getCode, forceSaveDto.getForceRra()));
            forceRraCn = xrbasecode.getName();
        }

        //处理时间参数
        String noticeFrom = "";
        if (forceSaveDto.getNoticeFrom() != null) {
            noticeFrom = DateUtils.localDateFormat(forceSaveDto.getNoticeFrom(), "yyyy年MM月dd日");
        }
        String noticeTo = "";
        if (forceSaveDto.getNoticeTo() != null) {
            noticeTo = DateUtils.localDateFormat(forceSaveDto.getNoticeTo(), "yyyy年MM月dd日");
        }

        String content = templateDB.getContent();
        return content
                .replace("{{forceResDate}}", noticeFrom)
                .replace("{{entName}}", entName)
                .replace("{{forceRra}}", forceRraCn)
                .replace("本公告自{{noticeFrom}}", "\n        本公告自 " + noticeFrom)
                .replace("{{noticeTo}}", noticeTo)
                .replace("{{regOrg}}", user.getOrgName());
    }

    @Override
    public void processControlSpe(ForceDeregisterSpeSaveDto forceSaveDto, AICUser user) {
        XrTaskList xrTaskList = iXrTaskListService.getOne(new LambdaQueryWrapper<XrTaskList>()
                .eq(XrTaskList::getBizSeqNo, forceSaveDto.getBizSeqNo()));
        LambdaQueryWrapper<XrForceDeregisterSpe> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(XrForceDeregisterSpe::getBizSeqNo, forceSaveDto.getBizSeqNo())
                .eq(XrForceDeregisterSpe::getForceType, forceSaveDto.getForceType());
        List<XrForceDeregisterSpe> xrForceDeregisterSpeList = list(queryWrapper);
        if (xrForceDeregisterSpeList.isEmpty()) {
            throw new BusinessException("暂无数据");
        }

//        LocalDateTime localDateTime = LocalDateTime.now();
//        // 转发业务
//        if (StringUtils.equals(FlowConstant.LINK_TYPE_REASSIGNMENT,forceQueryDto.getNextNodeID())) {
//            //查出转办单位的单位编号
//            TOrgunits nextOrg = iTOrgunitsService.getTOrgunitsById(forceQueryDto.getNextOrgID());
//            xrTaskList.setNextOrgId(nextOrg.getOrgNumber());
//            iXrTaskForwardService.saveByBizSeqNo(forceQueryDto, user,true);
//            iXrTaskListService.updateWorkFlow(forceQueryDto.getOpinion(), xrTaskList,
//                    forceQueryDto.getNextNodeID(), forceQueryDto.getNextPerformerIds(), AuthEnum.XR_HANDLE.getCode());
//            return;
//        }

        XrForceDeregister xrForceDeregister = null;
        for (XrForceDeregisterSpe xrForceDeregisterSpe : xrForceDeregisterSpeList) {
            switch (forceSaveDto.getNextNodeID()) {
                case FlowConstant.LINK_TYPE_EXAMINE:
                    // 保存值
                    xrForceDeregisterSpe.setForceRra(forceSaveDto.getForceRra());
                    TRBaseCode xrbasecode = trBaseCodeService.getOne(new LambdaQueryWrapper<TRBaseCode>()
                            .eq(TRBaseCode::getCodeid, "C13042")
                            .eq(TRBaseCode::getCode, xrForceDeregisterSpe.getForceRra()));
                    xrForceDeregisterSpe.setNoticeFrom(forceSaveDto.getNoticeFrom())
                            .setNoticeTo(forceSaveDto.getNoticeTo())
                            .setForceResDate(forceSaveDto.getForceResDate())
                            .setNoticeTitle(forceSaveDto.getNoticeTitle())
                            .setNoticeContent(forceSaveDto.getNoticeContent())
                            .setForceRes("1")  //正在进行拟强制注销公告
                            .setForceRraDate(LocalDate.now())
                            .setForceRegopi("拟强制注销")
                            .setForceRraCn(xrbasecode.getName());
                    xrForceDeregisterSpe.setStatus(FlowConstant.LINK_STATUS_ONE); // 审批流程中把状态设置成 "审核中"
                    break;
                case FlowConstant.LINK_TYPE_APPROVE:
                    xrForceDeregisterSpe.setStatus(FlowConstant.LINK_STATUS_TWO); // 审批流程中把状态设置成 "审批"
                    break;
                case FlowConstant.LINK_TYPE_END:
                    xrForceDeregisterSpe.setStatus(FlowConstant.LINK_STATUS_THREE) // 审批流程中把状态设置成 "通过"
                            .setJudauth(xrForceDeregisterSpe.getRegOrg())
                            .setJudauthCn(xrForceDeregisterSpe.getRegOrgCn());

                    //创建拟强制注销公告对象用于下面保存拟强制注销公告数据
                    xrForceDeregister = new XrForceDeregister();
                    //将拟强制注销业务表的数据传到拟强制注销公告详细表
                    xrForceDeregisterSpe = generateXrForceDeregisterRes(xrForceDeregisterSpe);
                    // 生成通知书
                    generateSpeWrit(xrForceDeregisterSpe, user);
                    break;
                case FlowConstant.LINK_TYPE_NULLIFY:
                    xrForceDeregisterSpe.setStatus(FlowConstant.LINK_STATUS_FIVE); // 审批流程中把状态设置成 "不通过"
                    break;
                case FlowConstant.LINK_TYPE_EXAMINE_FINISH:
                case FlowConstant.LINK_TYPE_APPROVE_FINISH:
                case FlowConstant.LINK_TYPE_LAW_FINISH:
                case FlowConstant.LINK_TYPE_UP_EXAMINE_FINISH:
                case FlowConstant.LINK_TYPE_UP_APPROVE_FINISH:
                    xrForceDeregisterSpe.setStatus(FlowConstant.LINK_STATUS_FOUR); // 审批流程中把状态设置成 "作废"
                    break;
                case FlowConstant.LINK_TYPE_EXAMINE_RETURN:
                    xrForceDeregisterSpe.setStatus(FlowConstant.LINK_STATUS_ONE);
                    break;
                case FlowConstant.LINK_TYPE_HANDLE_RETURN:
                    xrForceDeregisterSpe.setStatus(FlowConstant.LINK_STATUS_ZERO);
                    break;
                case FlowConstant.LINK_TYPE_LAW_RETURN:
                    xrForceDeregisterSpe.setStatus(FlowConstant.LINK_STATUS_SEVEN);
                    break;
                default:
                    break;
            }
            saveOrUpdate(xrForceDeregisterSpe);
        }

        //最后生成或修改拟强制注销公告数据
        if (xrForceDeregister != null) {
            XrForceDeregisterSpe xrForceDeregisterSpe = xrForceDeregisterSpeList.get(0);
            XrForceDeregister forceDeregister = iXrForceDeregisterService.getById(xrForceDeregisterSpe.getForceId());
            //校验是否已有公告数据
            if (forceDeregister == null) {
                BeanUtils.copyProperties(xrForceDeregisterSpe, xrForceDeregister);
                iXrForceDeregisterService.saveOrUpdate(xrForceDeregister);
            }
        }
        iXrTaskListService.updateWorkFlow(forceSaveDto.getOpinion(), xrTaskList,
                forceSaveDto.getNextNodeID(), forceSaveDto.getNextPerformerIds(), null);

    }

    /**
     * 将拟强制注销业务表的数据分别传到 拟强制注销公告表和拟强制注销公告详细表
     *
     * @param xrForceSpe
     */
    public XrForceDeregisterSpe generateXrForceDeregisterRes(XrForceDeregisterSpe xrForceSpe) {
        //生成详细表
        EBaseinfo eBaseinfo = iEBaseinfoService.getById(xrForceSpe.getPripId());
        XrForceDeregisterRes xrForceRes = new XrForceDeregisterRes();
        BeanUtils.copyProperties(xrForceSpe, xrForceRes);
        if (eBaseinfo != null) {
            xrForceRes.setLerep(eBaseinfo.getName())
                    .setDom(eBaseinfo.getDom());
        }

        iXrForceDeregisterResService.saveOrUpdate(xrForceRes);
        return xrForceSpe;
    }

    /**
     * 生成拟强注销公告文书
     *
     * @param xrForceSpe 公告文书
     * @param user       当前用户
     * @return 生成公告
     */
    public TSWrit generateSpeWrit(XrForceDeregisterSpe xrForceSpe, AICUser user) {
        TSWrit tsWritModel = new TSWrit();
        tsWritModel.setWritsid(UUID.randomUUID().toString());
        String workNoType = WorkNoUtil.WORKNOTYPE_71;
        //获取补全后的内容
        ForceDeregisterSpeSaveDto saveDto = new ForceDeregisterSpeSaveDto();
        saveDto.setBizSeqNo(xrForceSpe.getBizSeqNo());
        saveDto.setForceRra(xrForceSpe.getForceRra());
        String replaceContent = getForceDeregisterContent(user, saveDto);
        tsWritModel.setWritsno(tsWorkNoService.generateDocNo(workNoType, xrForceSpe.getRegOrg()))
                .setWritsname(WorkNoUtil.getWorkNoTypeName(workNoType))
                .setContent(replaceContent)
                .setBizseq(xrForceSpe.getBizSeqNo())
                .setPripid(xrForceSpe.getPripId())
                .setWritstype(workNoType)
                .setCreatetime(LocalDateTime.now())
                .setAreaCode(xrForceSpe.getRegOrg());

        tsWritService.save(tsWritModel);
        return tsWritModel;
    }

    @Override
    public XrTaskListVo saveForceAcceptList(ForceDeregisterSpeQueryDto queryDto, AICUser user) {
        XrForceDeregisterSpe forceSpe = queryDto.getXrForceDeregisterSpe();
        if (forceSpe == null) {
            throw new BusinessException("拟强制注销业务数据不能为空");
        }
        //拟强制注销公告id
        String forceId = forceSpe.getForceId();
        //查出该公告下的所有拟强制注销业务数据，需要排除掉已经终止拟强制注销的
        List<XrForceDeregisterSpe> speList = this.list(new LambdaQueryWrapper<XrForceDeregisterSpe>()
                .eq(XrForceDeregisterSpe::getForceId, forceId)
                .in(XrForceDeregisterSpe::getForceRes, "1","2") //查正在拟强制注销公告中的，和公告期满的数据
                .eq(XrForceDeregisterSpe::getForceType, "1")
                .ne(XrForceDeregisterSpe::getStatus, FlowConstant.LINK_STATUS_FIVE));
        String bizSeqNo = UUID.randomUUID().toString(); //业务编号用新的
        StringBuilder entName = new StringBuilder();
        List<String> pripIdList = new ArrayList<>();
        LocalDate now = LocalDate.now();
        List<XrForceDeregisterSpe> forceList = new ArrayList<>();
        for (XrForceDeregisterSpe spe : speList) {
            if (spe.getNoticeTo() != null && !now.isAfter(spe.getNoticeTo())) {
                throw new BusinessException(spe.getEntName() + "的拟强制注销公告期未结束");
            }
            entName.append(spe.getEntName()).append("、");
            XrForceDeregisterSpe xrForceDeregisterSpe = new XrForceDeregisterSpe();
            //直接使用原来的业务数据，类型由拟强制注销改为强制注销
            //2025.12.8 改为新增多一条业务数据
            BeanUtils.copyProperties(spe, xrForceDeregisterSpe);
            xrForceDeregisterSpe.setForceSpeId(UUID.randomUUID().toString())
                    .setForceType("0")  //强制注销
                    .setStatus(FlowConstant.LINK_STATUS_ZERO) // 待受理
                    .setApplyTime(LocalDateTime.now())
                    .setAcceptOrg(user.getRegionID())
                    .setBizSeqNo(bizSeqNo);
            forceList.add(xrForceDeregisterSpe);
            pripIdList.add(spe.getPripId());
        }
        this.saveBatch(forceList);

        // 开启待办
        XrTaskList xrTaskList = new XrTaskList();
        String taskLikeId = UUID.randomUUID().toString();
        xrTaskList.setTaskLikeId(taskLikeId);
        xrTaskList.setBizSeqNo(bizSeqNo);
        xrTaskList.setBusType(BaseDataConstant.BUSINESS_TYPE_FORCE_DEREGISTER);
        xrTaskList.setAreaCode(user.getRegionID().substring(0, 6));
        if (forceList.size() > 2) {
            xrTaskList.setBusName(forceList.get(0).getEntName() + "、" + forceList.get(1).getEntName() + "等" + forceList.size() + "家主体");
        } else {
            xrTaskList.setBusName(entName.substring(0, entName.length() - 1));
        }
        xrTaskList.setApplyOrgId(user.getOrgID());
        xrTaskList.setWorkFlowId(FlowUtil.FORCE_DEREGISTER_WORK_FLOW);
        // 保存待办信息
        iXrTaskListService.startWorkFlow(xrTaskList, new String[]{user.getPrimaryKey()}, null, pripIdList, user);

        return new XrTaskListVo(xrTaskList.getTaskLikeId(), bizSeqNo, "");
    }

    @Override
    public void processControlForce(ForceDeregisterSpeSaveDto forceSaveDto, AICUser user) {
        XrTaskList xrTaskList = iXrTaskListService.getOne(new LambdaQueryWrapper<XrTaskList>().eq(XrTaskList::getBizSeqNo, forceSaveDto.getBizSeqNo()));
        LambdaQueryWrapper<XrForceDeregisterSpe> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(XrForceDeregisterSpe::getBizSeqNo, forceSaveDto.getBizSeqNo());
        //若不是结束流程就只改强制注销业务数据，若是结束流程要把拟强制注销的也改了
        if (!FlowConstant.LINK_TYPE_END.equals(forceSaveDto.getNextNodeID())) {
            queryWrapper.eq(XrForceDeregisterSpe::getForceType, forceSaveDto.getForceType());
        } else {
            //要把终止拟强制注销的排除掉
            queryWrapper.ne(XrForceDeregisterSpe::getForceRes, "3");
        }
        List<XrForceDeregisterSpe> xrForceDeregisterSpeList = list(queryWrapper);
        if (xrForceDeregisterSpeList.isEmpty()) {
            throw new BusinessException("暂无数据");
        }
        LocalDateTime localDateTime = LocalDateTime.now();
//        // 转发业务
//        if (StringUtils.equals(FlowConstant.LINK_TYPE_REASSIGNMENT,forceQueryDto.getNextNodeID())) {
//            //查出转办单位的单位编号
//            TOrgunits nextOrg = iTOrgunitsService.getTOrgunitsById(forceQueryDto.getNextOrgID());
//            xrTaskList.setNextOrgId(nextOrg.getOrgNumber());
//            iXrTaskForwardService.saveByBizSeqNo(forceQueryDto, user,true);
//            iXrTaskListService.updateWorkFlow(forceQueryDto.getOpinion(), xrTaskList,
//                    forceQueryDto.getNextNodeID(), forceQueryDto.getNextPerformerIds(), AuthEnum.XR_HANDLE.getCode());
//            return;
//        }

        for (XrForceDeregisterSpe xrForceDeregisterSpe : xrForceDeregisterSpeList) {
            switch (forceSaveDto.getNextNodeID()) {
                case FlowConstant.LINK_TYPE_EXAMINE:
                    // 修改拟强制注销结果
                    xrForceDeregisterSpe.setForceRes("4")  //已强制注销
                            .setStatus(FlowConstant.LINK_STATUS_ONE); // 审批流程中把状态设置成 "审核中"
                    //强制注销决定送达公告内容
                    xrForceDeregisterSpe.setForceNoticeContent(forceSaveDto.getForceNoticeContent())
                            .setDecisionContent(forceSaveDto.getDecisionContent());
                    //根据各公司的信息调整决定书内容
//                    xrForceDeregisterSpe = updateContent(xrForceDeregisterSpe);
                    break;
                case FlowConstant.LINK_TYPE_APPROVE:
                    xrForceDeregisterSpe.setStatus(FlowConstant.LINK_STATUS_TWO); // 审批流程中把状态设置成 "审批"
                    break;
                case FlowConstant.LINK_TYPE_END:
                    xrForceDeregisterSpe.setStatus(FlowConstant.LINK_STATUS_THREE); // 审批流程中把状态设置成 "通过"
                    xrForceDeregisterSpe.setForceRes("4");  //这里再次改强制注销结果是为了让拟强制注销的结果也改成强制注销
                    xrForceDeregisterSpe = toEndXrForceDeregisterForce(xrForceDeregisterSpe, user);
                    break;
                case FlowConstant.LINK_TYPE_NULLIFY:
                    xrForceDeregisterSpe.setStatus(FlowConstant.LINK_STATUS_FIVE); // 审批流程中把状态设置成 "不通过"
                    break;
                case FlowConstant.LINK_TYPE_EXAMINE_FINISH:
                case FlowConstant.LINK_TYPE_APPROVE_FINISH:
                case FlowConstant.LINK_TYPE_LAW_FINISH:
                case FlowConstant.LINK_TYPE_UP_EXAMINE_FINISH:
                case FlowConstant.LINK_TYPE_UP_APPROVE_FINISH:
                    xrForceDeregisterSpe.setStatus(FlowConstant.LINK_STATUS_FOUR); // 审批流程中把状态设置成 "作废"
                    break;
                case FlowConstant.LINK_TYPE_EXAMINE_RETURN:
                    xrForceDeregisterSpe.setStatus(FlowConstant.LINK_STATUS_ONE);
                    break;
                case FlowConstant.LINK_TYPE_HANDLE_RETURN:
                    xrForceDeregisterSpe.setStatus(FlowConstant.LINK_STATUS_ZERO);
                    break;
                case FlowConstant.LINK_TYPE_LAW_RETURN:
                    xrForceDeregisterSpe.setStatus(FlowConstant.LINK_STATUS_SEVEN);
                    break;
                default:
                    break;
            }
            saveOrUpdate(xrForceDeregisterSpe);
        }
        iXrTaskListService.updateWorkFlow(forceSaveDto.getOpinion(), xrTaskList,
                forceSaveDto.getNextNodeID(), forceSaveDto.getNextPerformerIds(), null);
    }

    /**
     * 办结强制注销业务
     *
     * @param xrForceSpe
     * @param user
     */
    private XrForceDeregisterSpe toEndXrForceDeregisterForce(XrForceDeregisterSpe xrForceSpe, AICUser user) {
        //补全公告信息（不需要）
        //修改公告详细信息
        XrForceDeregisterRes xrForceDeregisterRes = iXrForceDeregisterResService.getById(xrForceSpe.getForceResId());
        xrForceDeregisterRes.setForceRes(xrForceSpe.getForceRes())
                .setForceResDate(LocalDate.now());
        //补全业务表的字段
        xrForceSpe.setJudauth(xrForceSpe.getRegOrg())
                .setJudauthCn(xrForceSpe.getRegOrgCn())
                .setForceResDate(LocalDate.now());
        //生成强制注销登记决定书送达公告
        XrForceNotice xrForceNotice = new XrForceNotice();
        BeanUtils.copyProperties(xrForceSpe, xrForceNotice);
        xrForceNotice.setNoticeId(UUID.randomUUID().toString())
                .setNoticeContent(xrForceSpe.getForceNoticeContent())
                .setAnnDate(LocalDate.now());

        //根据决定书送达公告生成文书表数据
        TSWrit tsWritModel = new TSWrit();
        tsWritModel.setWritsid(UUID.randomUUID().toString());
        String workNoType = WorkNoUtil.WORKNOTYPE_72;
        //获取补全后的内容
        String replaceContent = completeContent(xrForceSpe.getDecisionContent(), xrForceSpe);
        tsWritModel.setWritsno(tsWorkNoService.generateDocNo(workNoType, xrForceSpe.getRegOrg()))
                .setWritsname(WorkNoUtil.getWorkNoTypeName(workNoType))
                .setContent(replaceContent)
                .setBizseq(xrForceSpe.getBizSeqNo())
                .setPripid(xrForceSpe.getPripId())
                .setWritstype(workNoType)
                .setCreatetime(LocalDateTime.now())
                .setAreaCode(xrForceSpe.getRegOrg());

        tsWritService.save(tsWritModel);
        iXrForceDeregisterResService.saveOrUpdate(xrForceDeregisterRes);
        iXrForceNoticeService.saveOrUpdate(xrForceNotice);
        Map<String, Object> data = new HashMap<>();
        String orgNumber = StringUtils.fillZeroSuffix(StringUtils.clearRegionZero(xrForceSpe.getRegOrg()), 6);
        String nameByCode = gzaiccodeService.getNameByCode(orgNumber);
        data.put("areaName", StringUtils.trimToEmpty(nameByCode));
        data.put("writNo", StringUtils.trimToEmpty(tsWritModel.getWritsno()));
        data.put("htmlContent", StringUtils.trimToEmpty(replaceContent));
        LocalDate now = LocalDate.now();
        data.put("year", String.valueOf(now.getYear()));
        data.put("month", String.valueOf(now.getMonthValue() > 9 ? now.getMonthValue() : "0" + now.getMonthValue()));
        data.put("day", String.valueOf(now.getDayOfMonth() > 9 ? now.getDayOfMonth() : "0" + now.getDayOfMonth()));
        // 2026年2月4日 生成pdf文书
        createFileService.createPdfCommon(xrForceSpe.getBizSeqNo(), "决定书送达公告", "强制注销决定送达公告",
                "force", ".pdf", "/static/template/commonWritTemplate.docx", data);

        // 写入推送记录存储表，后续定时任务统一推送
        EBaseinfo eBaseinfo = iEBaseinfoService.getById(xrForceSpe.getPripId());
        LocalDateTime nowTime = LocalDateTime.now();
        BatchRevokePushRecord pushRecord = new BatchRevokePushRecord();
        pushRecord.setRevlistid(xrForceSpe.getForceSpeId());
        pushRecord.setPripid(xrForceSpe.getPripId());
        pushRecord.setUniscid(eBaseinfo != null ? eBaseinfo.getUniscid() : xrForceSpe.getUniscId());
        pushRecord.setEntname(eBaseinfo != null ? eBaseinfo.getEntname() : xrForceSpe.getEntName());
        pushRecord.setRevokeRea(xrForceSpe.getForceRra());
        pushRecord.setRevokedate(nowTime);
        pushRecord.setPunishOrg(xrForceSpe.getRegOrg());
        pushRecord.setPunishOrgCn(xrForceSpe.getRegOrgCn());
        pushRecord.setHandlerid(user.getPrimaryKey());
        pushRecord.setHandlername(user.getName());
        pushRecord.setPushStatus("0"); // 0-待推送
        pushRecord.setPushCount(0);
        pushRecord.setChangeregstate("A");
        pushRecord.setCreateTime(nowTime);
        pushRecord.setUpdateTime(nowTime);
        pushRecord.setBiztype("1"); // 强制注销类型
        batchRevokePushRecordService.save(pushRecord);

        return xrForceSpe;
    }

    /**
     * 补全决定书头部的公司基本信息
     *
     * @param xrForceSpe
     */
    public String completeContent(String content, XrForceDeregisterSpe xrForceSpe) {
        //查该企业的基本信息
        EBaseinfo eBaseinfo = iEBaseinfoService.getById(xrForceSpe.getPripId());
        String dom = StringUtils.isEmpty(eBaseinfo.getDom()) ? "" : eBaseinfo.getDom();
        String name = StringUtils.isEmpty(eBaseinfo.getName()) ? "" : eBaseinfo.getName();
        String info = "当事人/经营主体： " + eBaseinfo.getEntname() + "\n"
                + "统一信用代码/证件号码： " + eBaseinfo.getUniscid() + "\n"
                + "住所/经营场所（住址）： " + dom + "\n"
                + "法定代表人（负责人、经营者）姓名： " + name + "\n"
                + "证件号码： \n联系电话：            其他联系方式：     \n";
        content = info + content;
        return content;
    }

    //    @Override
//    public Map<String, Object> fileParamExplainLr(MultipartFile file, String type, String bizseq, AICUser aicUser){
//        // 读取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("文件数据读取出错");
//        }
//        HashSet<EBaseinfo> enableList = new HashSet<>();
//        ArrayList<DisableListVo> disableList = new ArrayList<>();//不可导
//        Map<String, Xrbasecode> codeMap = iXrbasecodeService.getBaseCodeMapFormCache("CA19");
//        LambdaQueryWrapper<XrForceDeregisterSpe> speWrapper = new LambdaQueryWrapper<>();
//
//        LambdaQueryWrapper<TOrgunits> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(TOrgunits::getOrgUnitID, aicUser.getOrgID());
//        String region = aicUser.getRegionID();
//        TOrgunits orgunits = iTOrgunitsService.getOne(queryWrapper);
//        Integer level = orgunits.getOrgLevel();
//        for (EntExcel entDto : entDtos) {
//            LambdaQueryWrapper<EBaseinfo> wrapper = new LambdaQueryWrapper<>();
//            EBaseinfo baseinfoModel = new EBaseinfo();
//            if (entDto.getUniscid() != null) {
//                baseinfoModel.setUniscId(entDto.getUniscid().trim());
//            }
//            if (entDto.getRegno() != null) {
//                baseinfoModel.setRegNo(entDto.getRegno().trim());
//            }
//            if (entDto.getEntname() != null) {
//                baseinfoModel.setEntName(entDto.getEntname().trim());
//            }
//
//            wrapper.select(EBaseinfo::getPripId, EBaseinfo::getEntName, EBaseinfo::getUniscId,EBaseinfo::getRegNo,
//                    EBaseinfo::getName,EBaseinfo::getRegstate, EBaseinfo::getRegstateCn,EBaseinfo::getEntType,
//                    EBaseinfo::getRegorg, EBaseinfo::getRegorgCn);
//            wrapper.eq(StringUtils.isNotBlank(baseinfoModel.getUniscId()),EBaseinfo::getUniscId, baseinfoModel.getUniscId())
//                    .eq(StringUtils.isNotBlank(baseinfoModel.getRegNo()),EBaseinfo::getRegNo, baseinfoModel.getRegNo())
//                    .eq(StringUtils.isNotBlank(baseinfoModel.getEntName()),EBaseinfo::getEntName, baseinfoModel.getEntName());
//
//            // 避免wrapper没有筛选条件导致全表查询
//            if (wrapper.getExpression().getNormal().size() == 0) {
//                continue;
//            }
//            Xrbasecode baseCode = null;
//            List<EBaseinfo> eBaseinfoList = iEBaseinfoService.list(wrapper);
//            if(!eBaseinfoList.isEmpty()){
//                EBaseinfo eBaseinfo = null;
//                //处理多个企业状态的主体
//                if(eBaseinfoList.size()>1){
//                    for(EBaseinfo base : eBaseinfoList){
//                        if(base.getRegstate().equals("1")){
//                            eBaseinfo = base;
//                            break;
//                        }
//                    }
//                } else {
//                    eBaseinfo = eBaseinfoList.get(0);
//                }
//
//                if (eBaseinfo != null) {
//                    String reason = "";
//                    String regorg = eBaseinfo.getRegorg();
//                    if (StringUtils.isNotEmpty(regorg)) {
//                        boolean isSame = region.substring(0,6).equals(regorg);
//                        baseCode = codeMap.get(eBaseinfo.getRegstate());
//                        //校验用户所在机关是否和主体的登记机关一致
//                        if (isSame) {
//                            //校验企业状态是否不为注销状态
//                            if (!Arrays.asList("3", "4").contains(eBaseinfo.getRegstate())) {   //不为注销状态才可导入
//                                // 校验是否已列异
//                                speWrapper.clear();
//                                speWrapper.eq(XrForceDeregisterSpe::getPripId, eBaseinfo.getPripId())
//                                        .notIn(XrForceDeregisterSpe::getStatus, "3","4","5");
//
//                                List<XrForceDeregisterSpe> speList = this.list(speWrapper);
//                                if (speList.isEmpty()) {     //未在办理拟强制注销业务
//                                    enableList.add(eBaseinfo);
//                                    continue;
//                                } else {
//                                    reason = "该主体尚在办理拟强制注销业务中";
//                                }
//                            } else {    // 不为开业或歇业
//                                if (baseCode != null) {
//                                    reason = "主体状态为" + baseCode.getName();
//                                } else {
//                                    reason = "主体状态为" + eBaseinfo.getRegstateCn();
//                                }
//                            }
//                        } else {
//                            reason = "该主体的登记机关为" + eBaseinfo.getRegorgCn();
//                        }
//                    } else {
//                        reason = "登记机关为空";
//                    }
//                    DisableListVo disableListVo = new DisableListVo();
//                    disableListVo.setReason(reason);
//                    disableListVo.setEntname(eBaseinfo.getEntName());
//                    disableListVo.setUniscid(eBaseinfo.getUniscId());
//                    disableListVo.setRegno(eBaseinfo.getRegNo());
//                    disableListVo.setRegstateCn(baseCode == null ? null : baseCode.getName());
//                    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);
//                }
//            } else {
//                DisableListVo disableListVo = new DisableListVo();
//                disableListVo.setEntname(baseinfoModel.getEntName());
//                disableListVo.setUniscid(baseinfoModel.getUniscId());
//                disableListVo.setRegno(baseinfoModel.getRegNo());
//                disableListVo.setReason("主体信息有误");
//                disableList.add(disableListVo);
//            }
//        }
//
//        HashMap<String, Object> resultMap = new HashMap<>();
//        String enableListId = UUID.randomUUID().toString();
//        String disableListId = UUID.randomUUID().toString();
//        resultMap.put("enableListId", enableListId);
//        resultMap.put("disableListId", disableListId);
//        resultMap.put("enableList", enableList);
//        resultMap.put("disableList", disableList);
//        EXPIRY_MAP.put(enableListId, enableList);
//        EXPIRY_MAP.put(disableListId, disableList);
//
//        resultMap.put("enableSize", enableList.size());
//        resultMap.put("disableSize", disableList.size());
//        resultMap.put("bizseq", bizseq);
//
//        return resultMap;
//    }
//
    @Override
    public IPage<XrForceDeregisterSpe> forceDeregisterPageByRegOrg(BaseQuery<ForceDeregisterSpeQueryDto> query, AICUser user) {
        ForceDeregisterSpeQueryDto entity = query.getEntity(ForceDeregisterSpeQueryDto.class);
        String userRegOrg = user.getRegionID();

        IPage<XrForceDeregisterSpe> xrForceDeregisterSpeIPage;
        Page<XrForceDeregisterSpe> page = new Page<>(query.getCurrent(), query.getSize());
        entity.setRegOrg(userRegOrg);
//        entity.setForceRes("2");    //只查正在拟强制注销公告中的数据
        List<String> forceresList = Arrays.asList("1", "2");    //查正在拟强制注销公告中的，和公告期满的数据
        entity.setForceResList(forceresList);
        entity.setForceType("1");   //只查正在拟强制注销公告
        entity.setStatus("3");  //查审批通过的

        if (StringUtils.equals("0", entity.getSoon())) {
            entity.setSoon(null);
        }
        xrForceDeregisterSpeIPage = baseMapper.xrForceDeregisterPageByRegOrg(page, entity);
        return xrForceDeregisterSpeIPage;
    }

    @Override
    public boolean addForceDeregisterSpe(String bizSeqNo, List<String> pripIdList, AICUser user) {
        if (StringUtils.isEmpty(bizSeqNo)) {
            throw new BusinessException("业务号不能为空");
        }
        if (pripIdList == null || pripIdList.isEmpty()) {
            throw new BusinessException("主体ID列表不能为空");
        }

        // 查询现有业务数据
        LambdaQueryWrapper<XrForceDeregisterSpe> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(XrForceDeregisterSpe::getBizSeqNo, bizSeqNo);
        List<XrForceDeregisterSpe> existingSpeList = this.list(queryWrapper);

        if (existingSpeList.isEmpty()) {
            throw new BusinessException("未找到对应的业务数据");
        }

        // 检查业务状态，只有在待受理状态才能添加
        XrForceDeregisterSpe firstSpe = existingSpeList.get(0);
        if (!FlowConstant.LINK_STATUS_ZERO.equals(firstSpe.getStatus())) {
            throw new BusinessException("只有在待受理状态下才能添加主体");
        }

        // 获取现有的 forceId 和 forceType
        String forceId = firstSpe.getForceId();
        String forceType = firstSpe.getForceType();
        String noticeTitle = firstSpe.getNoticeTitle();

        // 查询待办信息
        XrTaskList xrTaskList = iXrTaskListService.getOne(new LambdaQueryWrapper<XrTaskList>()
                .eq(XrTaskList::getBizSeqNo, bizSeqNo));

        // 获取现有的主体ID，避免重复添加
        Set<String> existingPripIds = existingSpeList.stream()
                .map(XrForceDeregisterSpe::getPripId)
                .collect(Collectors.toSet());

        // 过滤掉已存在的主体
        List<String> newPripIds = pripIdList.stream()
                .filter(pripId -> !existingPripIds.contains(pripId))
                .collect(Collectors.toList());

        if (newPripIds.isEmpty()) {
            throw new BusinessException("所有主体已存在，无需重复添加");
        }

        // 分批查询主体信息
        List<List<String>> partitionList = Lists.partition(newPripIds, 400);
        List<EBaseinfo> eBaseinfos = new ArrayList<>();
        for (List<String> list : partitionList) {
            eBaseinfos.addAll(iEBaseinfoService.listByIds(list));
        }

        // 创建新的业务数据
        List<XrForceDeregisterSpe> newSpeList = new ArrayList<>();
        for (EBaseinfo eBaseinfo : eBaseinfos) {
            XrForceDeregisterSpe xrForceSpe = new XrForceDeregisterSpe();
            String forceSpeId = UUID.randomUUID().toString();
            xrForceSpe.setForceSpeId(forceSpeId)
                    .setForceResId(forceSpeId)
                    .setForceId(forceId)
                    .setBizSeqNo(bizSeqNo)
                    .setPripId(eBaseinfo.getPripid())
                    .setUniscId(eBaseinfo.getUniscid())
                    .setRegno(eBaseinfo.getRegno())
                    .setEntName(eBaseinfo.getEntname())
                    .setRegOrg(eBaseinfo.getAcceptRegorg())
                    .setRegOrgCn(eBaseinfo.getRegorgCn())
                    .setStatus(FlowConstant.LINK_STATUS_ZERO)
                    .setNoticeTitle(noticeTitle)
                    .setApplyTime(LocalDateTime.now())
                    .setForceType(forceType)
                    .setAcceptOrg(user.getRegionID());
            newSpeList.add(xrForceSpe);
        }

        // 批量保存
        this.saveBatch(newSpeList);

        // 更新待办业务名称
        if (xrTaskList != null) {
            List<XrForceDeregisterSpe> allSpeList = new ArrayList<>(existingSpeList);
            allSpeList.addAll(newSpeList);
            StringBuilder entName = new StringBuilder();
            for (XrForceDeregisterSpe spe : allSpeList) {
                entName.append(spe.getEntName()).append("、");
            }
            if (allSpeList.size() > 2) {
                xrTaskList.setBusName(allSpeList.get(0).getEntName() + "、" + allSpeList.get(1).getEntName() + "等" + allSpeList.size() + "家主体");
            } else {
                xrTaskList.setBusName(entName.substring(0, entName.length() - 1));
            }
            iXrTaskListService.updateById(xrTaskList);
        }

        return true;
    }

    @Override
    public boolean deleteForceDeregisterSpe(String forceSpeId, AICUser user) {
        if (StringUtils.isEmpty(forceSpeId)) {
            throw new BusinessException("业务表主键不能为空");
        }

        // 查询要删除的业务数据
        XrForceDeregisterSpe deleteSpe = this.getById(forceSpeId);
        if (deleteSpe == null) {
            throw new BusinessException("未找到对应的业务数据");
        }

        // 检查业务状态，只有在待受理状态才能删除
        if (!FlowConstant.LINK_STATUS_ZERO.equals(deleteSpe.getStatus())) {
            throw new BusinessException("只有在待受理状态下才能删除主体");
        }

        String bizSeqNo = deleteSpe.getBizSeqNo();

        // 查询同业务号的所有数据
        LambdaQueryWrapper<XrForceDeregisterSpe> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(XrForceDeregisterSpe::getBizSeqNo, bizSeqNo);
        List<XrForceDeregisterSpe> speList = this.list(queryWrapper);

        if (speList.size() == 1) {
            throw new BusinessException("待办中只有一个主体，不能删除");
        }

        // 删除指定主体
        this.removeById(forceSpeId);

        // 更新待办业务名称
        XrTaskList xrTaskList = iXrTaskListService.getOne(new LambdaQueryWrapper<XrTaskList>()
                .eq(XrTaskList::getBizSeqNo, bizSeqNo));

        if (xrTaskList != null) {
            // 重新查询删除后的数据
            List<XrForceDeregisterSpe> remainingSpeList = this.list(queryWrapper);
            StringBuilder entName = new StringBuilder();
            for (XrForceDeregisterSpe spe : remainingSpeList) {
                entName.append(spe.getEntName()).append("、");
            }
            if (remainingSpeList.size() > 2) {
                xrTaskList.setBusName(remainingSpeList.get(0).getEntName() + "、" + remainingSpeList.get(1).getEntName() + "等" + remainingSpeList.size() + "家主体");
            } else {
                xrTaskList.setBusName(entName.substring(0, entName.length() - 1));
            }
            iXrTaskListService.updateById(xrTaskList);
        }

        return true;
    }
//
//    private XrForceDeregisterSpe updateContent(XrForceDeregisterSpe xrForceSpe) {
//        String decisionContent = xrForceSpe.getDecisionContent();
//
//        //查对应的拟强制注销登记法定事由
//        String forceRraCn =  "";
//        if(StringUtils.isNotEmpty(xrForceSpe.getForceRra())){
//            Xrbasecode xrbasecode = iXrbasecodeService.getOne(new LambdaQueryWrapper<Xrbasecode>()
//                    .eq(Xrbasecode::getCodeid, "C13042").eq(Xrbasecode::getCode, xrForceSpe.getForceRra()));
//            forceRraCn = xrbasecode.getName();
//        }
//        String part = "        你单位（公司名称） " + xrForceSpe.getEntName() + "（统一社会信用代码：" + xrForceSpe.getUniscId() + "）"+forceRraCn+"。";
//        xrForceSpe.setDecisionContent(part + decisionContent);
//        return xrForceSpe;
//    }

}
