package com.yeejoin.amos.boot.module.jg.biz.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Sequence;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.biz.common.bo.CompanyBo;
import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.amos.boot.biz.common.entity.BaseEntity;
import com.yeejoin.amos.boot.biz.common.utils.RedisKey;
import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;
import com.yeejoin.amos.boot.module.jg.api.dto.*;
import com.yeejoin.amos.boot.module.jg.api.entity.*;
import com.yeejoin.amos.boot.module.jg.api.enums.BusinessTypeEnum;
import com.yeejoin.amos.boot.module.jg.api.enums.EquipTypeEnum;
import com.yeejoin.amos.boot.module.jg.api.enums.WorkFlowStatusEnum;
import com.yeejoin.amos.boot.module.jg.api.mapper.*;
import com.yeejoin.amos.boot.module.jg.api.service.IJgChangeRegistrationUnitService;
import com.yeejoin.amos.boot.module.jg.api.vo.SortVo;
import com.yeejoin.amos.boot.module.jg.biz.feign.TzsServiceFeignClient;
import com.yeejoin.amos.boot.module.jg.biz.service.ICommonService;
import com.yeejoin.amos.boot.module.jg.flc.api.fegin.WorkFlowFeignService;
import com.yeejoin.amos.boot.module.ymt.api.entity.*;
import com.yeejoin.amos.boot.module.ymt.api.enums.ApplicationFormTypeEnum;
import com.yeejoin.amos.boot.module.ymt.api.enums.FlowStatusEnum;
import com.yeejoin.amos.boot.module.ymt.api.mapper.*;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.feign.systemctl.model.TaskV2Model;
import com.yeejoin.amos.feign.workflow.Workflow;
import com.yeejoin.amos.feign.workflow.model.*;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.lang3.ObjectUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.rdbms.service.BaseService;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.yeejoin.amos.boot.module.jg.biz.service.impl.JgUseRegistrationServiceImpl.getAuditPassedDate;

/**
 * 单位变更登记服务实现类
 *
 * @author system_generator
 * @date 2023-12-22
 */
@Service
public class JgChangeRegistrationUnitServiceImpl extends BaseService<JgChangeRegistrationUnitDto, JgChangeRegistrationUnit, JgChangeRegistrationUnitMapper> implements IJgChangeRegistrationUnitService {
    private static final String SUBMIT_TYPE_FLOW = "1";
    private static final String PROCESS_DEFINITION_KEY = "unitChange";
    private static final String TABLE_PAGE_ID = "1734141426742095873";


    @Autowired
    EquipmentCategoryMapper equipmentCategoryMapper;
    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    JgChangeRegistrationUnitEqMapper JgChangeRegistrationUnitEqMapper;

    @Autowired
    JgChangeRegistrationUnitEqServiceImpl registrationUnitEqService;

    @Autowired
    CmWorkflowServiceImpl cmWorkflowService;
    @Autowired
    private JgChangeRegistrationUnitMapper JgChangeRegistrationUnitMapper;

    @Autowired
    RegistrationInfoMapper tzsJgRegistrationInfoMapper;
    @Autowired
    OtherInfoMapper tzsJgOtherInfoMapper;
    @Autowired
    UseInfoMapper useInfoMapper;
    @Autowired
    TzsServiceFeignClient tzsServiceFeignClient;
    @Autowired
    SupervisoryCodeInfoMapper supervisoryCodeInfoMapper;
    @Autowired
    CommonServiceImpl commonServiceImpl;

    @Autowired
    WorkFlowFeignService workFlowFeginService;

    @Autowired
    private JgRegistrationHistoryMapper jgRegistrationHistoryMapper;

    @Autowired
    private IdxBizJgRegisterInfoMapper idxBizJgRegisterInfoMapper;

    //改造登记关系表mapper
    @Autowired
    private JgChangeRegistrationReformEqMapper jgChangeRegistrationReformEqMapper;
    //移装登记关系表
    @Autowired
    private JgChangeRegistrationTransferEqMapper jgChangeRegistrationTransferEqMapper;
    //使用登记关系表mapper
    @Autowired
    private JgUseRegistrationEqMapper jgUseRegistrationEqMapper;
    //单位变更登记关系表mapper
    @Autowired
    private JgChangeRegistrationUnitEqMapper jgChangeRegistrationUnitEqMapper;
    //更名变更登记关系表mapper
    @Autowired
    private JgChangeRegistrationNameEqMapper jgChangeRegistrationNameEqMapper;

    @Autowired
    private IdxBizJgUseInfoServiceImpl idxBizJgUseInfoService;
    @Autowired
    private IdxBizJgRegisterInfoServiceImpl idxBizJgRegisterInfoService;
    @Autowired
    private IdxBizJgFactoryInfoServiceImpl idxBizJgFactoryInfoService;

    @Autowired
    ICommonService commonService;

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    JgUseRegistrationManageServiceImpl registrationManageService;
    @Autowired
    JgRegistrationHistoryServiceImpl registrationHistoryService;

    @Autowired
    private Sequence sequence;

    @Autowired
    JgCertificateChangeRecordServiceImpl certificateChangeRecordService;

    @Autowired
    JgCertificateChangeRecordEqServiceImpl certificateChangeRecordEqService;

    @Autowired
    JgUseRegistrationManageServiceImpl useRegistrationManageService;

    @Autowired
    private TzBaseEnterpriseInfoMapper tzBaseEnterpriseInfoMapper;

    /**
     * 根据sequenceNbr查询：1、查询单位变更信息，2、查询使用登记证列表
     *
     * @param sequenceNbr 主键
     * @return 单位变更
     */
    @Override
    public Map<String, Map<String, Object>> queryBySequenceNbr(Long sequenceNbr) {
        // 单位变更信息
        JgChangeRegistrationUnit notice = JgChangeRegistrationUnitMapper.selectById(sequenceNbr);
        if (Objects.isNull(notice)) {
            return null;
        }
        Map<String, Object> changeInfo = BeanUtil.beanToMap(notice, false, true);

        //组装下拉数据
        if (!ValidationUtil.isEmpty(notice.getReceiveOrgCode()) && !ValidationUtil.isEmpty(notice.getReceiveOrgName())) {
            changeInfo.put("receiveOrgCode", notice.getReceiveOrgCode() + "_" + notice.getReceiveOrgName());
        }
        if (!ValidationUtil.isEmpty(notice.getUseUnitCreditCode()) && !ValidationUtil.isEmpty(notice.getUseUnitName())) {
            changeInfo.put("useUnitCreditCode", notice.getUseUnitCreditCode() + "_" + notice.getUseUnitName());
        }
        if (!ValidationUtil.isEmpty(notice.getNewUseUnitCreditCode()) && !ValidationUtil.isEmpty(notice.getNewUseUnitName())) {
            changeInfo.put("newUseUnitCreditCode", notice.getNewUseUnitCreditCode() + "_" + notice.getNewUseUnitName());
        }
        //附件格式处理
        changeInfo.put("changeCertificateList", JSON.parse(notice.getChangeCertificate()));
        changeInfo.put("otherAccessoriesList", JSON.parse(notice.getOtherAccessories()));
        //查询使用登记证列表
        JgRegistrationHistory historyServiceOne = registrationHistoryService.getOne(
                new LambdaQueryWrapper<JgRegistrationHistory>().eq(JgRegistrationHistory::getCurrentDocumentId, notice.getApplyNo()));
        changeInfo.put("registrationList", JSON.parse(historyServiceOne.getChangeData()));
        return new HashMap<String, Map<String, Object>>() {{
//            this.put("changeRegisInfo", fillEquipInfoWithRuntimeOrHistoryData(notice, changeInfo));
            this.put("changeRegisInfo", changeInfo);
        }};
    }

    private Map<String, Object> fillEquipInfoWithRuntimeOrHistoryData(JgChangeRegistrationUnit notice, Map<String, Object> changeInfo) {
        // 已完成时显示历史数据
        if (notice.getStatus().equals(FlowStatusEnum.TO_BE_FINISHED.getName())) {
            JSONObject his = commonService.queryHistoryData(notice.getSequenceNbr());
            // 兼容老数据
            if (his == null) {
                return getEquipInfo(notice.getSequenceNbr(), changeInfo);
            }
            CommonServiceImpl.formatTime2StrDateForEquip(his);
            his.putAll(changeInfo);
            return his;
        }
        // 非完成状态返回实时使用登记证数据
        return getEquipInfo(notice.getSequenceNbr(), changeInfo);
    }


    private Map<String, Object> getEquipInfo(Long sequenceNbr, Map<String, Object> changeInfo) {
        String[] fields = {"productPhoto", "designDoc", "designStandard", "factoryStandard",
                "productQualityYieldProve", "insUseMaintainExplain", "inspectReport", "otherAccessoriesList",
                "proxyStatementAttachment", "installContractAttachment", "changeCertificateList"};

        // 设备信息
        List<Map<String, Object>> equipmentInfos = JgChangeRegistrationUnitMapper.queryEquipInformation(sequenceNbr);
        String equipId = JgChangeRegistrationUnitMapper.queryEquipIdBySeq(sequenceNbr);
        Map<String, Object> detailFieldCamelCaseByRecord = idxBizJgRegisterInfoService.getDetailFieldCamelCaseByRecord(equipId);
        detailFieldCamelCaseByRecord.remove("useUnitCreditCode");


        for (String s : fields) {
            if (changeInfo.containsKey(s) && !ObjectUtils.isEmpty(changeInfo.get(s))) {
                changeInfo.put(s, JSON.parseArray(changeInfo.get(s).toString()));
            }
            if (equipmentInfos.get(0).containsKey(s) && !ObjectUtils.isEmpty(equipmentInfos.get(0).get(s))) {
                equipmentInfos.get(0).put(s, JSON.parseArray(equipmentInfos.get(0).get(s).toString()));
            }
        }

        Map<String, Object> newMap = new HashMap<>();
        newMap.putAll(detailFieldCamelCaseByRecord);
        newMap.putAll(changeInfo);
        newMap.putAll(equipmentInfos.get(0));
        return newMap;
    }

    /**
     * 更新单位变更
     *
     * @param noticeDto 单位变更
     */
    @GlobalTransactional(rollbackFor = Exception.class)
    public JgChangeRegistrationUnitDto updateInstallationNotice(String submitType, JgChangeRegistrationUnitDto noticeDto, String op) {
        if (Objects.isNull(noticeDto) || StringUtils.isEmpty(submitType)) {
            throw new IllegalArgumentException("参数不能为空");
        }
        // 字段转换
        this.convertField(noticeDto);
        // 获取单位变更使用登记证列表
        List<Map<String, Object>> registrationList = noticeDto.getRegistrationList();
        if (CollectionUtils.isEmpty(registrationList)) {
            throw new BadRequest("使用登记证不能为空");
        }
        //根据使用登记证查询设备
        List<Long> registrationIdList = registrationList.stream().filter(v -> v.containsKey("sequenceNbr") &&
                        ObjectUtils.isNotEmpty(v.get("sequenceNbr")) && canConvertToLong(v.get("sequenceNbr").toString()))
                .map(v -> Long.parseLong(v.get("sequenceNbr").toString())).collect(Collectors.toList());
        // 获取单位变更设备列表
        if (CollectionUtils.isEmpty(registrationIdList)) {
            throw new BadRequest("使用登记证不能为空");
        }
        List<JSONObject> deviceList = registrationManageService.queryEquByCertificateSeqList(registrationIdList);
        // 获取单位变更设备列表
        if (CollectionUtils.isEmpty(deviceList)) {
            throw new BadRequest("使用登记证下无设备");
        }
        ArrayList<String> roleListAll = new ArrayList<>();
        ArrayList<String> roleListNext = new ArrayList<>();
        if (SUBMIT_TYPE_FLOW.equals(submitType)) {
            AjaxResult ajaxResult;
            // 发起流程
            if (!StringUtils.hasText(noticeDto.getInstanceId())) {
                List<ProcessTaskDTO> processTasks = new ArrayList<>();
                ActWorkflowBatchDTO actWorkflowBatchDTO = new ActWorkflowBatchDTO();
                List<ActWorkflowStartDTO> list = new ArrayList<>();
                ActWorkflowStartDTO dto = new ActWorkflowStartDTO();
                dto.setProcessDefinitionKey(PROCESS_DEFINITION_KEY);
                dto.setBusinessKey(String.valueOf(new Date().getTime()));
                dto.setCompleteFirstTask(true);
                list.add(dto);
                actWorkflowBatchDTO.setProcess(list);
                dto.setNextExecuteUserCompanyCode(noticeDto.getReceiveCompanyCode());
                processTasks = cmWorkflowService.startBatch(actWorkflowBatchDTO);
                String instanceId = processTasks.get(0).getProcessInstance().getId();
                String nextTaskId = processTasks.get(0).getNextTask().get(0).getId();
                String taskname = processTasks.get(0).getNextTask().get(0).getName();
                this.buildRoleList(processTasks, roleListNext, roleListAll);
                List<WorkflowResultDto> workflowResultDtos = commonServiceImpl.buildWorkFlowInfo(processTasks);
                String nextUserIds = workflowResultDtos.get(0).getNextExecutorUserIds();

                JgChangeRegistrationUnit notice = new JgChangeRegistrationUnit();
                //    JgChangeRegistrationUnit noticeOld = JgChangeRegistrationUnitMapper.selectById(noticeDto.getSequenceNbr());
                BeanUtils.copyProperties(noticeDto, notice);
                //         boolean submit = submit(notice, op);
                notice.setChangeCertificate(noticeDto.getChangeCertificate());
                notice.setRemark(noticeDto.getRemark());
                //  notice.setStatus(taskName[0]);
                if (!ObjectUtils.isEmpty(notice.getInstanceStatus())) {
                    notice.setInstanceStatus(notice.getInstanceStatus() + "," + roleListAll);
                } else {
                    notice.setInstanceStatus(String.join(",", roleListAll));
                }
                notice.setInstanceId(instanceId);
                notice.setNextTaskId(nextTaskId);
                notice.setSupervisoryCode(noticeDto.getSupervisoryCode());
                notice.setPromoter(RequestContext.getExeUserId());
                notice.setNextExecutorIds(String.join(",", roleListNext));
                notice.setStatus(WorkFlowStatusEnum.UNITCHANGE_RECEIVE.getPass());
                notice.setNextExecuteUserIds(nextUserIds);
                JgChangeRegistrationUnitMapper.updateById(notice);
                commonServiceImpl.deleteTasksByRelationId(notice.getSequenceNbr() + "");
                createTaskModel(notice, taskname, "1", nextUserIds);
                commonServiceImpl.saveExecuteFlowData2Redis(notice.getInstanceId(), buildInstanceRuntimeData(notice));
            } else {
                ArrayList<String> roleList = new ArrayList<>();
                String taskId = noticeDto.getNextTaskId();
                //组装信息
                TaskResultDTO task = new TaskResultDTO();
                task.setResultCode("approvalStatus");
                task.setTaskId(taskId);
                task.setComment("");
                HashMap<String, Object> map = new HashMap<>();
                map.put("approvalStatus", op);
                if (!ObjectUtils.isEmpty(noticeDto.getInstanceStatus()) &&
                        (noticeDto.getStatus().equals(WorkFlowStatusEnum.UNIT_RENAME_SUBMIT.getReject()) ||
                                noticeDto.getStatus().equals(WorkFlowStatusEnum.UNIT_RENAME_SUBMIT.getRollBack()))) {
                    map.put("approvalStatus", "提交");
                }
                task.setVariable(map);
                //执行流程
                task.setNextExecuteUserCompanyCode(noticeDto.getReceiveCompanyCode());
                ProcessTaskDTO processTaskDTO = cmWorkflowService.completeOrReject(taskId, task, op);
                JgChangeRegistrationUnit bean = new JgChangeRegistrationUnit();
                BeanUtils.copyProperties(noticeDto, bean);
                String taskCode = FlowStatusEnum.TO_BE_FINISHED.getName();
                String taskName1 = "";
                String nextTaskId = "";
                this.buildRoleList(Collections.singletonList(processTaskDTO), roleList, roleListAll);
                List<WorkflowResultDto> workflowResultDtos = commonServiceImpl.buildWorkFlowInfo(Collections.singletonList(processTaskDTO));
                String nextUserIds = workflowResultDtos.get(0).getNextExecutorUserIds();
                if (processTaskDTO != null && processTaskDTO.getNextTask() != null && processTaskDTO.getNextTask().size() > 0) {
                    taskCode = processTaskDTO.getNextTask().get(0).getKey();
                    taskName1 = processTaskDTO.getNextTask().get(0).getName();
                    nextTaskId = processTaskDTO.getNextTask().get(0).getId();
                }
                bean.setNextExecutorIds(String.join(",", roleList));
                if (!ObjectUtils.isEmpty(bean.getInstanceStatus())) {
                    bean.setInstanceStatus(bean.getInstanceStatus() + "," + String.join(",", roleList));
                } else {
                    bean.setInstanceStatus(String.join(",", roleList));
                }
                bean.setNextTaskId(nextTaskId);
                bean.setPromoter(RequestContext.getExeUserId());
                bean.setStatus(WorkFlowStatusEnum.getMessage(taskCode).getPass());
                executeOneStep(bean, taskName1, nextUserIds, op);
                bean.setNextExecuteUserIds(nextUserIds);
                JgChangeRegistrationUnitMapper.updateById(bean);
                commonServiceImpl.saveExecuteFlowData2Redis(bean.getInstanceId(), buildInstanceRuntimeData(bean));
            }
        } else {
            JgChangeRegistrationUnit bean = new JgChangeRegistrationUnit();
            BeanUtils.copyProperties(noticeDto, bean);
            JgChangeRegistrationUnitMapper.updateById(bean);
        }
//        updateHistorySingle(noticeDto.getSequenceNbr());
        List<JgChangeRegistrationUnitEq> jgRelationEquipList = new ArrayList<>();
        deviceList.forEach(device -> {
            JgChangeRegistrationUnitEq unitEq = new JgChangeRegistrationUnitEq();
            if (device.containsKey("USE_ORG_CODE")) {
                unitEq.setRegistrationCertificate(device.getString("USE_ORG_CODE"));//使用登记证主键
            }
            if (device.containsKey("SEQUENCE_NBR")) {
                unitEq.setEquId(device.getString("SEQUENCE_NBR"));//设备主键
            }
            unitEq.setUnitChangeRegistrationId(noticeDto.getSequenceNbr().toString());//单位变更业务主键
            unitEq.setDeviceInfo(JSONObject.toJSONString(device));//设备信息json
            jgRelationEquipList.add(unitEq);
        });
        JgRegistrationHistory jgRegistrationHistory = new JgRegistrationHistory();
        //登记类别
        jgRegistrationHistory.setRegistrationClass("单位变更登记");
        jgRegistrationHistory.setCurrentDocumentId(noticeDto.getApplyNo());
        //使用登记证历史数据
        jgRegistrationHistory.setChangeData(JSONObject.toJSONString(registrationList));
        //先删除之前设备关系数据，在插入最新设备关系数据
        registrationUnitEqService.getBaseMapper().delete(new LambdaQueryWrapper<JgChangeRegistrationUnitEq>()
                .eq(JgChangeRegistrationUnitEq::getUnitChangeRegistrationId, noticeDto.getSequenceNbr()));
        registrationUnitEqService.saveBatch(jgRelationEquipList);
        //先删除之前未提交的历史使用登记证信息，在插入最新的使用登记证信息
        registrationHistoryService.getBaseMapper().delete(new LambdaQueryWrapper<JgRegistrationHistory>()
                .eq(JgRegistrationHistory::getCurrentDocumentId, noticeDto.getApplyNo()));
        registrationHistoryService.save(jgRegistrationHistory);
        return noticeDto;
    }

    private void updateHistorySingle(Long seq) {
        QueryWrapper<JgChangeRegistrationUnitEq> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(JgChangeRegistrationUnitEq::getUnitChangeRegistrationId, seq);
        List<JgChangeRegistrationUnitEq> eqs = jgChangeRegistrationUnitEqMapper.selectList(wrapper);
        this.updateHistoryAsync(eqs);
    }


    /**
     * 分页查询
     *
     * @param page  分页对象
     * @param model 查询参数
     * @param type  类型：enterprise-企业端、supervision-监管端
     * @return 单位变更列表
     */
    @Override
    public Page<JgChangeRegistrationUnitDto> queryForJgChangeRegistrationUnitPage(Page<JgChangeRegistrationUnit> page,
                                                                                  String sort,
                                                                                  JgChangeRegistrationUnitDto model,
                                                                                  String type,
                                                                                  ReginParams reginParams) {

        String orgCode;
        orgCode = reginParams.getCompany().getCompanyCode();
        String companyType = reginParams.getCompany().getCompanyType();
        String currentUserId = reginParams.getUserModel().getUserId();
        SortVo sortMap = commonServiceImpl.sortFieldConversion(sort);
        Page<JgChangeRegistrationUnit> noticePage = JgChangeRegistrationUnitMapper.queryForPage(page, sortMap, model, type, orgCode, model.getRoleIds(), currentUserId);

        Page<JgChangeRegistrationUnitDto> noticeDtoPage = new Page<>();
        BeanUtils.copyProperties(noticePage, noticeDtoPage, "records");
        List<JgChangeRegistrationUnitDto> records = noticePage.getRecords().stream().map(notice -> {
            JgChangeRegistrationUnitDto noticeDto = new JgChangeRegistrationUnitDto();
            BeanUtils.copyProperties(notice, noticeDto);
            noticeDto.setCompanyType(companyType);
            return noticeDto;
        }).collect(java.util.stream.Collectors.toList());
        noticeDtoPage.setRecords(records);

        return noticeDtoPage;
    }

    /**
     * 批量删除
     *
     * @param sequenceNbrs 主键
     * @return 是否删除成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteForBatch(Long[] sequenceNbrs) {
        if (Objects.isNull(sequenceNbrs) || sequenceNbrs.length == 0) {
            return false;
        }
        for (Long sequenceNbr : sequenceNbrs) {
            JgChangeRegistrationUnit changeRegistrationUnit = this.baseMapper.selectById(sequenceNbr);
            // 删除代办 + 中止流程
            commonServiceImpl.deleteTaskModel(String.valueOf(sequenceNbr), changeRegistrationUnit.getInstanceId());
            // 删除单子
            this.baseMapper.deleteById(sequenceNbr);
            // 删除单子对应eq
            jgChangeRegistrationUnitEqMapper.delete(new LambdaQueryWrapper<JgChangeRegistrationUnitEq>()
                    .eq(JgChangeRegistrationUnitEq::getUnitChangeRegistrationId, sequenceNbr));
            // 删除单子对应历史表数据
            jgRegistrationHistoryMapper.delete(new LambdaQueryWrapper<JgRegistrationHistory>()
                    .eq(JgRegistrationHistory::getCurrentDocumentId, changeRegistrationUnit.getApplyNo()));
        }
        return Boolean.TRUE;
    }

    public void saveRecord(JgChangeRegistrationUnit registrationUnit) {
        Long sequenceNbr = registrationUnit.getSequenceNbr();
        List<JgChangeRegistrationUnitEq> eqList = registrationUnitEqService.lambdaQuery().eq(JgChangeRegistrationUnitEq::getUnitChangeRegistrationId, sequenceNbr).list();
        List<JgRegistrationHistory> historyList = registrationHistoryService.lambdaQuery().eq(JgRegistrationHistory::getCurrentDocumentId, registrationUnit.getApplyNo()).list();
        if (historyList.size() != 1) {
            return;
        }
        List<JgCertificateChangeRecord> changeRecordList = new ArrayList<>();
        List<JgCertificateChangeRecordEq> changeRecordEqList = new ArrayList<>();
        JgCertificateChangeRecord changeRecord = new JgCertificateChangeRecord();
        JSONArray historyJson = JSON.parseArray(historyList.get(0).getChangeData());
        for (Object object : historyJson) {
            JSONObject jsonObject = JSON.parseObject(object.toString());
            String registrationCode = jsonObject.getString("useRegistrationCode");
            String certificateNo = jsonObject.getString("certificateNo");
            String equCategoryCode = jsonObject.getString("equCategoryCode");
            changeRecord.setApplyNo(registrationUnit.getApplyNo());//申请编号
            changeRecord.setReceiveOrgName(registrationUnit.getReceiveOrgName());//接收机构/登记机关
            changeRecord.setAuditPassDate(registrationUnit.getApplyDate());//办理日期
            changeRecord.setRegType("单位变更登记");//登记类别
            changeRecord.setRegDate(registrationUnit.getCreateDate());//申请日期
            changeRecord.setChangeContent(this.buildRecordContent(registrationUnit));//变更内容
            changeRecord.setUseRegistrationCode(registrationCode);//使用登记编号
            changeRecord.setReceiveCompanyCode(registrationUnit.getReceiveCompanyCode());//接收机构公司代码
            changeRecord.setCertificateNo(certificateNo);//登记证书唯一码
            changeRecord.setUseUnitCreditCode(registrationUnit.getNewUseUnitCreditCode());//使用单位统一信用代码
            changeRecord.setUseUnitName(registrationUnit.getNewUseUnitName());//使用单位名称
            changeRecord.setEquCategory(equCategoryCode);//设备类别编码
            changeRecord.setCreateDate(new Date());
            changeRecord.setSequenceNbr(sequence.nextId());
            changeRecordList.add(changeRecord);
            for (JgChangeRegistrationUnitEq unitEq : eqList) {
                if (!StringUtils.isEmpty(unitEq.getRegistrationCertificate()) && !StringUtils.isEmpty(registrationCode) &&
                        unitEq.getRegistrationCertificate().equals(registrationCode)) {
                    JSONObject deviceJson = JSON.parseObject(unitEq.getDeviceInfo());
                    JgCertificateChangeRecordEq changeRecordEq = new JgCertificateChangeRecordEq();
                    changeRecordEq.setChangeRecordId(changeRecord.getSequenceNbr().toString());//登记证记录主键
                    changeRecordEq.setEquId(deviceJson.getString("SEQUENCE_NBR"));//设备主键
                    changeRecordEqList.add(changeRecordEq);
                }
            }
        }
        if (!changeRecordList.isEmpty()) {
            certificateChangeRecordService.saveBatch(changeRecordList);
        }
        if (!changeRecordEqList.isEmpty()) {
            certificateChangeRecordEqService.saveBatch(changeRecordEqList);
        }
    }

    @Override
//    @Transactional(rollbackFor = Exception.class)
    @GlobalTransactional(rollbackFor = Exception.class)
    public List<JgChangeRegistrationUnitDto> saveNotice(String submitType, JSONObject map, ReginParams reginParams) {
        JgChangeRegistrationUnitDto model = BeanUtil.toBeanIgnoreError(map.get("changeRegisInfo"), JgChangeRegistrationUnitDto.class);
        String[] taskName = new String[]{"流程结束"};
        // 字段转换
        convertField(model);
        // 获取单位变更使用登记证列表
        List<Map<String, Object>> registrationList = model.getRegistrationList();
        if (CollectionUtils.isEmpty(registrationList)) {
            throw new BadRequest("使用登记证不能为空");
        }
        //根据使用登记证查询设备
        List<Long> registrationIdList = new ArrayList<>();//使用登记证id
        List<String> registrationNoList = new ArrayList<>();//使用登记证编号
        for (Map<String, Object> objectMap : registrationList) {
            if (objectMap.containsKey("sequenceNbr") && ObjectUtils.isNotEmpty(objectMap.get("sequenceNbr"))
                    && canConvertToLong(objectMap.get("sequenceNbr").toString())) {
                registrationIdList.add(Long.parseLong(objectMap.get("sequenceNbr").toString()));
            }
            if (objectMap.containsKey("useRegistrationCode") && ObjectUtils.isNotEmpty(objectMap.get("useRegistrationCode"))) {
                registrationNoList.add(objectMap.get("useRegistrationCode").toString());
            }
        }
        // 获取单位变更设备列表
        if (CollectionUtils.isEmpty(registrationIdList)) {
            throw new BadRequest("使用登记证不能为空");
        }
        List<JSONObject> deviceList = registrationManageService.queryEquByCertificateSeqList(registrationIdList);
        // 获取单位变更设备列表
        if (CollectionUtils.isEmpty(deviceList)) {
            throw new BadRequest("使用登记证下无设备");
        }
        // 获取单位变更单号
        ResponseModel<List<String>> listResponseModel = tzsServiceFeignClient.applicationFormCode(ApplicationFormTypeEnum.DWBG.getCode(), 1);
        List<String> applyNoList = listResponseModel.getResult();
        if (CollectionUtils.isEmpty(applyNoList)) {
            log.error("生成申请变更单位编码失败");
            return new ArrayList<>();
        }
        ArrayList<String> roleListFirst = new ArrayList<>();
//        ArrayList<String> roleListSecond = new ArrayList<>();
        List<String> instanceIdList = new ArrayList<>();
        List<String> nextExecutorUserIds = new ArrayList<>();
        List<String> taskIds = new ArrayList<>();
        List<WorkflowResultDto> workflowResultDtos = new ArrayList<>();
        String nextExecutorRoleIds = "";
        // 判断当前是否为提交
        if (SUBMIT_TYPE_FLOW.equals(submitType)) {
            //发起流程
            // ActWorkflowStartDTO dto = new ActWorkflowStartDTO();
            ActWorkflowBatchDTO actWorkflowBatchDTO = new ActWorkflowBatchDTO();
            List<ActWorkflowStartDTO> list = new ArrayList<>();
//            for (int i = 0; i < deviceList.size(); i++
//            ) {
            ActWorkflowStartDTO dto = new ActWorkflowStartDTO();
            dto.setProcessDefinitionKey(PROCESS_DEFINITION_KEY);
            dto.setBusinessKey(String.valueOf(new Date().getTime()));
            dto.setNextExecuteUserCompanyCode(model.getReceiveCompanyCode());
            dto.setCompleteFirstTask(true);
            list.add(dto);
//            }
            actWorkflowBatchDTO.setProcess(list);
            List<ProcessTaskDTO> processTaskDTOS = cmWorkflowService.startBatch(actWorkflowBatchDTO);
            workflowResultDtos = commonServiceImpl.buildWorkFlowInfo(processTaskDTOS);
            nextExecutorRoleIds = workflowResultDtos.get(0).getNextExecutorRoleIds();
            nextExecutorUserIds.add(workflowResultDtos.get(0).getNextExecutorUserIds());
            for (WorkflowResultDto processTaskDTO : workflowResultDtos) {
                instanceIdList.add(processTaskDTO.getInstanceId());
                taskIds.add(processTaskDTO.getNextTaskId());
            }
        }

//        List<JgChangeRegistrationUnit> list = new ArrayList<>();
//        List<JgChangeRegistrationUnitEq> equipList = new ArrayList<>();
        String finalNextExecutorRoleIds = nextExecutorRoleIds;
        CompanyBo companyBo = commonServiceImpl.getOneCompany(model.getReceiveCompanyCode());
//        deviceList.forEach(obj -> {
//            JgChangeRegistrationUnitEq jgRelationEquip = new JgChangeRegistrationUnitEq();
//            int i = deviceList.indexOf(obj);
//            String applyNo = applyNoList.get(i);
        model.setApplyNo(applyNoList.get(0));
        model.setReceiveCompanyOrgCode(companyBo.getOrgCode());
        model.setCreateUserId(RequestContext.getExeUserId());
        model.setApplyDate(new Date());
        if (SUBMIT_TYPE_FLOW.equals(submitType)) {
            model.setNextExecutorIds(finalNextExecutorRoleIds);
            model.setInstanceStatus(String.join(",", roleListFirst));
            model.setPromoter(reginParams.getUserModel().getUserId());
            model.setStatus(taskName[0]);
        }
        model.setNewUseUnitName(reginParams.getCompany().getCompanyName());
        model.setNewUseUnitCreditCode(reginParams.getCompany().getCompanyCode());
//            dto.setEquType((String.valueOf(obj.get("EQU_CATEGORY"))));
//            dto.setProductNameB((String.valueOf(obj.get("PRODUCT_NAME"))));
//            dto.setEquCodeB((String.valueOf(obj.get("EQU_CODE"))));
//            dto.setUseInnerCode(ValidationUtil.isEmpty(obj.get("USE_INNER_CODE")) ? "" : String.valueOf(obj.get("USE_INNER_CODE")));
//            dto.setEquAddress((String.valueOf(obj.get("ADDRESS"))));
//            dto.setSupervisoryCode(String.valueOf(obj.get("SUPERVISORY_CODE")));
//            dto.setEquList(String.valueOf(obj.get("EQU_LIST")));
//            jgRelationEquip.setEquId(String.valueOf(obj.get("SEQUENCE_NBR")));
//            jgRelationEquip.setUnitChangeRegistrationId(applyNo);
        if (!CollectionUtils.isEmpty(nextExecutorUserIds)) {
            model.setNextExecuteUserIds(nextExecutorUserIds.get(0));
        }
        if (!CollectionUtils.isEmpty(instanceIdList)) {
            model.setInstanceId(instanceIdList.get(0));
            model.setStatus(WorkFlowStatusEnum.UNITCHANGE_RECEIVE.getPass());
        } else {
            model.setStatus(WorkFlowStatusEnum.UNITCHANGE_SUBMIT.getPass());
        }
        if (!CollectionUtils.isEmpty(taskIds)) {
            model.setNextTaskId(taskIds.get(0));
        }
//            list.add(dto);
//            equipList.add(jgRelationEquip);
//        });

//        WorkflowResultDto workDto = new WorkflowResultDto();
        model.setSequenceNbr(sequence.nextId());
        model.setCreateDate(new Date());
        model.setCreateUserName(reginParams.getUserModel().getRealName());
        model.setUseRegistCode(String.join("，", registrationNoList));
        model.setEquList(registrationList.get(0).get("equList").toString());
        JgChangeRegistrationUnit registrationUnit = new JgChangeRegistrationUnit();
        BeanUtils.copyProperties(model, registrationUnit);
        JgChangeRegistrationUnitMapper.insert(registrationUnit);

        List<TaskModelDto> modelDtos = new ArrayList<>();
        if (SUBMIT_TYPE_FLOW.equals(submitType)) {
//            for (JgChangeRegistrationUnit obj : list) {
            TaskModelDto taskModelDto = new TaskModelDto();

            TaskMessageDto ta = new TaskMessageDto();
            ta.setInstanceId(registrationUnit.getInstanceId());
            ta.setStatus(registrationUnit.getStatus());
            ta.setPromoter(registrationUnit.getPromoter());
            ta.setNextExecuteUserIds(registrationUnit.getNextExecuteUserIds());
            ta.setSequenceNbr(registrationUnit.getSequenceNbr());
            ta.setNextTaskId(registrationUnit.getNextTaskId());
            taskModelDto.setModel(ta);
            // dto.setModel(obj);
            taskModelDto.setFlowCreateDate(new Date());
            taskModelDto.setTaskName(workflowResultDtos.get(0).getNextTaskName());
            taskModelDto.setFlowCode(registrationUnit.getNextTaskId());
            taskModelDto.setTaskContent(this.buildTaskContent(registrationUnit));
            taskModelDto.setTaskCode(registrationUnit.getApplyNo());
            taskModelDto.setTaskType(BusinessTypeEnum.JG_COMPANY_CHANGE_REGISTRATION.getCode());
            taskModelDto.setTaskTypeLabel(BusinessTypeEnum.JG_COMPANY_CHANGE_REGISTRATION.getName());
            taskModelDto.setRelationId(registrationUnit.getInstanceId());
            taskModelDto.setExecuteUserIds(workflowResultDtos.get(0).getNextExecutorUserIds());
            taskModelDto.setTaskStatusLabel("未处理");
            taskModelDto.setFlowStatus(commonServiceImpl.getDictionaryCodeByName(WorkFlowStatusEnum.UNITCHANGE_RECEIVE.getPass()));
            taskModelDto.setFlowStatusLabel(WorkFlowStatusEnum.UNITCHANGE_RECEIVE.getPass());
            taskModelDto.setStartUserId(RequestContext.getExeUserId());
            taskModelDto.setStartUser(workflowResultDtos.get(0).getStartUserName());
            taskModelDto.setStartUserCompanyName(reginParams.getCompany().getCompanyName());
            taskModelDto.setStartDate(new Date());
            taskModelDto.setNextExecuteUser(workflowResultDtos.get(0).getNextExecutorRoleIds());
            modelDtos.add(taskModelDto);
//            }
        } else {
//            for (JgChangeRegistrationUnit obj : list) {
            TaskModelDto taskModelDto = new TaskModelDto();
            //行数据
            taskModelDto.setModel(registrationUnit);
            //摘要 按原有规则组装
            taskModelDto.setTaskContent(this.buildTaskContent(registrationUnit));
            //申请单号
            taskModelDto.setTaskCode(registrationUnit.getApplyNo());
            //业务类型枚举code值
            taskModelDto.setTaskType(BusinessTypeEnum.JG_COMPANY_CHANGE_REGISTRATION.getCode());
            ////业务主键
            taskModelDto.setRelationId(registrationUnit.getSequenceNbr() + "");
            modelDtos.add(taskModelDto);
//            }
        }

//        for(JgChangeRegistrationUnit obj : list) {
        commonServiceImpl.saveExecuteFlowData2Redis(registrationUnit.getInstanceId(), buildInstanceRuntimeData(registrationUnit));
//        }

        commonServiceImpl.buildTaskModel(modelDtos);

        List<JgChangeRegistrationUnitEq> jgRelationEquipList = new ArrayList<>();
        deviceList.forEach(device -> {
            JgChangeRegistrationUnitEq unitEq = new JgChangeRegistrationUnitEq();
            if (device.containsKey("USE_ORG_CODE")) {
                unitEq.setRegistrationCertificate(device.getString("USE_ORG_CODE"));//使用登记证主键
            }
            if (device.containsKey("SEQUENCE_NBR")) {
                unitEq.setEquId(device.getString("SEQUENCE_NBR"));//设备主键
            }
            unitEq.setUnitChangeRegistrationId(registrationUnit.getSequenceNbr().toString());//单位变更业务主键
            unitEq.setDeviceInfo(JSONObject.toJSONString(device));//设备信息json
            jgRelationEquipList.add(unitEq);
        });
        JgRegistrationHistory jgRegistrationHistory = new JgRegistrationHistory();
        //登记类别
        jgRegistrationHistory.setRegistrationClass("单位变更登记");
        jgRegistrationHistory.setCurrentDocumentId(registrationUnit.getApplyNo());
        //使用登记证历史数据
        jgRegistrationHistory.setChangeData(JSONObject.toJSONString(registrationList));
//        List<JgChangeRegistrationUnitEq> jgRelationEquipList = equipList.stream().map(jgRelationEquip -> {
//            List<JgChangeRegistrationUnit> collect = list.stream().filter(jgChangeRegistrationUnit -> jgRelationEquip.getUnitChangeRegistrationId().equals(jgChangeRegistrationUnit.getApplyNo())).collect(Collectors.toList());
//            Long sequenceNbr = collect.get(0).getSequenceNbr();
//            insertOrUpdateHis(JSON.parseObject(JSONObject.toJSONString(collect.get(0))), jgRelationEquip.getEquId());
//            return jgRelationEquip.setUnitChangeRegistrationId(String.valueOf(sequenceNbr));
//        }).collect(Collectors.toList());
        //先删除之前设备关系数据，在插入最新设备关系数据
        registrationUnitEqService.getBaseMapper().delete(new LambdaQueryWrapper<JgChangeRegistrationUnitEq>()
                .eq(JgChangeRegistrationUnitEq::getUnitChangeRegistrationId, registrationUnit.getSequenceNbr()));
        registrationUnitEqService.saveBatch(jgRelationEquipList);
        //先删除之前未提交的历史使用登记证信息，在插入最新的使用登记证信息
        registrationHistoryService.getBaseMapper().delete(new LambdaQueryWrapper<JgRegistrationHistory>()
                .eq(JgRegistrationHistory::getCurrentDocumentId, registrationUnit.getApplyNo()));
        registrationHistoryService.save(jgRegistrationHistory);
        return Collections.singletonList(model);
    }

    public boolean canConvertToLong(String str) {
        try {
            Long.parseLong(str);
            return true;
        } catch (NumberFormatException e) {
            return false;
        }
    }

    private void updateHistoryAsync(List<JgChangeRegistrationUnitEq> jgRelationEquipList) {
        jgRelationEquipList.forEach(j -> {
            commonService.saveOrUpdateHistory(BusinessTypeEnum.JG_COMPANY_CHANGE_REGISTRATION.getName(),
                    getEquipInfoJson(j.getUnitChangeRegistrationId()), j.getEquId(), j.getUnitChangeRegistrationId());
        });
    }

    private JSONObject getEquipInfoJson(String id) {
        return new JSONObject(getEquipInfo(Long.parseLong(id), new HashMap<>()));
    }


    void getNext(ArrayList<String> roleListFirst, String instanceId, String[] taskName) {
        AjaxResult aj = Workflow.taskClient.getTaskNoAuth(instanceId);
        JSONObject taskNoAuth = JSON.parseObject(JSON.toJSONString(aj.get("data")));
        if (!ObjectUtils.isEmpty(taskNoAuth)) {
            String nextTaskId = taskNoAuth.getString("id");
            FeignClientResult<JSONObject> nodeInfo = workFlowFeginService.getNodeInfo(nextTaskId);
            JSONObject result = nodeInfo.getResult();
            Map<String, Object> taskInfo = (Map<String, Object>) result.get("taskInfo");
            taskName[0] = String.valueOf(taskInfo.get("taskDefinitionKey"));
            AjaxResult taskGroupName = Workflow.taskClient.getTaskGroupName(nextTaskId);
            JSONArray data = JSON.parseArray(JSON.toJSONString(taskGroupName.get("data")));
            for (Object datum : data) {
                if (((Map) datum).containsKey("groupId")) {
                    roleListFirst.add(((Map) datum).get("groupId").toString());
                }
            }
        }
    }

    private void convertField(JgChangeRegistrationUnitDto model) {
        // 处理图片
        if (!ValidationUtil.isEmpty(model.getChangeCertificateList())) {
            model.setChangeCertificate(JSON.toJSONString(model.getChangeCertificateList()));
        }
        // 处理其他附件
        if (!ValidationUtil.isEmpty(model.getOtherAccessoriesList())) {
            model.setOtherAccessories(JSON.toJSONString(model.getOtherAccessoriesList()));
        }
        // 分割单位
        String useUnitId = model.getUseUnitCreditCode();
        if (!ObjectUtils.isEmpty(useUnitId)) {
            String[] useUnitList = useUnitId.split("_");
            if (useUnitList.length > 1) {
                model.setUseUnitCreditCode(useUnitList[0]);
                model.setUseUnitName(useUnitList[1]);
            }
        }

        String newUseUnitId = model.getNewUseUnitCreditCode();
        if (!ObjectUtils.isEmpty(newUseUnitId)) {
            String[] newUseUnitList = newUseUnitId.split("_");
            if (newUseUnitList.length > 1) {
                model.setNewUseUnitCreditCode(newUseUnitList[0]);
                model.setNewUseUnitName(newUseUnitList[1]);
            }
        }

        String receiveOrgCode = model.getReceiveOrgCode();
        if (!ObjectUtils.isEmpty(receiveOrgCode)) {
            String[] receiveOrgCodeList = receiveOrgCode.split("_");
            if (receiveOrgCodeList.length > 1) {
                model.setReceiveOrgCode(receiveOrgCodeList[0]);
                model.setReceiveCompanyCode(receiveOrgCodeList[0]);
                model.setReceiveOrgName(receiveOrgCodeList[1]);
            }
        }
    }

//    private String convertImageUrl(List<Map<String, String>> urlList) {
//        String urls = "";
//        if (!CollectionUtils.isEmpty(urlList)) {
//            urls = urlList.stream().map(map -> map.get("url")).collect(Collectors.joining(","));
//        }
//        return urls;
//    }
//
//    public void insertOrUpdateHis(JSONObject map, String equipId) {
//        JgRegistrationHistory jgRegistrationHistory = new JgRegistrationHistory();
//        //使用登记编号
//        jgRegistrationHistory.setUseRegistrationCode(idxBizJgRegisterInfoMapper.getUseOrgCodeByEquip(equipId));
//        //登记类别
//        jgRegistrationHistory.setRegistrationClass("单位变更登记");
//        //设备id
//        jgRegistrationHistory.setEquId(equipId);
//        //修改数据
//        jgRegistrationHistory.setChangeData(JSONObject.toJSONString(map));
//        //设备监管码
//        LambdaQueryWrapper<OtherInfo> queryWrapper1 = new LambdaQueryWrapper<>();
//        queryWrapper1.eq(OtherInfo::getRecord, equipId);
//        OtherInfo tzsJgOtherInfo = tzsJgOtherInfoMapper.selectOne(queryWrapper1);
//        jgRegistrationHistory.setSupervisoryCode(tzsJgOtherInfo.getSupervisoryCode());
//        if (map.containsKey("type") && "edit".equals(String.valueOf(map.get("type")))) {
//            jgRegistrationHistory.setSequenceNbr(jgRegistrationHistoryMapper.getSequenceNbrByEquidAndDocumentId(equipId, String.valueOf(map.get("sequenceNbr"))));
//            jgRegistrationHistoryMapper.updateById(jgRegistrationHistory);
//        } else {
//            //当前单据id
//            jgRegistrationHistory.setCurrentDocumentId(map.get("applyNo").toString());
//            jgRegistrationHistoryMapper.insert(jgRegistrationHistory);
//        }
//    }

    @GlobalTransactional(rollbackFor = Exception.class)
    public boolean submit(JgChangeRegistrationUnit notice, String op) {

        AjaxResult ajaxResult = Workflow.taskClient.getTask(notice.getInstanceId());
        JSONObject dataObject = JSON.parseObject(JSON.toJSONString(ajaxResult.get("data")));
        String taskId = dataObject.getString("id");
        //组装信息
        TaskResultDTO dto = new TaskResultDTO();
        dto.setResultCode("approvalStatus");
        dto.setTaskId(taskId);
        if (!ValidationUtil.isEmpty(notice.getProcessAdvice())) {
            dto.setComment(notice.getProcessAdvice());
        }
        HashMap<String, Object> map = new HashMap<>();
        if (notice.getStatus().equals(WorkFlowStatusEnum.UNIT_RENAME_SUBMIT.getReject()) || notice.getStatus().equals(WorkFlowStatusEnum.UNIT_RENAME_SUBMIT.getRollBack())) {
            map.put("approvalStatus", "提交");
        } else {
            map.put("approvalStatus", op);
        }
        dto.setVariable(map);
        //执行流程
        AjaxResult ajaxResult1;
        try {
            ajaxResult1 = Workflow.taskClient.completeByTask(taskId, dto);
            if (ajaxResult1.get("code").equals(200)) {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            log.error("提交失败：{}", e);
            return false;
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void cancel(JgChangeRegistrationUnitDto noticeDto) {
        String lockKey = CommonServiceImpl.buildJgExecuteLockKey(noticeDto.getInstanceId());
        RLock lock = redissonClient.getLock(lockKey);
        try {
            boolean isLocked = lock.tryLock(0, 180, TimeUnit.SECONDS);
            // 解决并发问题：多个人同时操作一个流程（并发执行通过、驳回、撤回）
            if (!isLocked) {
                throw new BadRequest("当前流程已经被执行！请重新打开页面查看并执行！");
            }
            // 撤回校验
            commonServiceImpl.checkForRevocationFlow(noticeDto.getNextTaskId(), noticeDto.getInstanceId());

            String taskCode;
            List<String> roleListNext = new ArrayList<>();
            List<String> roleListAll = new ArrayList<>();
            ProcessTaskDTO processTaskDTO = cmWorkflowService.rollBack(noticeDto.getInstanceId());
            String nextTaskId = processTaskDTO.getNextTask().get(0).getId();
            this.buildRoleList(Collections.singletonList(processTaskDTO), roleListNext, roleListAll);
            List<WorkflowResultDto> workflowResultDtos = commonServiceImpl.buildWorkFlowInfo(Collections.singletonList(processTaskDTO));

            // 待调整
            taskCode = processTaskDTO.getNextTask().get(0).getKey();
            JgChangeRegistrationUnit jgChangeRegistrationUnit = this.baseMapper.selectById(noticeDto.getSequenceNbr());
            jgChangeRegistrationUnit.setStatus(WorkFlowStatusEnum.getMessage(taskCode).getRollBack());
            jgChangeRegistrationUnit.setPromoter("");
            jgChangeRegistrationUnit.setNextTaskId(nextTaskId);
            jgChangeRegistrationUnit.setNextExecuteUserIds(workflowResultDtos.get(0).getNextExecutorUserIds());
            jgChangeRegistrationUnit.setNextExecutorIds(String.join(",", roleListNext));
            JgChangeRegistrationUnitMapper.updateById(jgChangeRegistrationUnit);
            JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(jgChangeRegistrationUnit));
            jsonObject.put("nextTaskId", jgChangeRegistrationUnit.getNextTaskId());
            jsonObject.put("nextExecuteUser", jgChangeRegistrationUnit.getNextExecutorIds());
            jsonObject.put("taskType", BusinessTypeEnum.JG_COMPANY_CHANGE_REGISTRATION.getCode());
            jsonObject.put("flowStatus", this.getTaskCodeByName(jgChangeRegistrationUnit.getStatus()));
            jsonObject.put("flowStatusLabel", jgChangeRegistrationUnit.getStatus());

            commonServiceImpl.rollbackTask(noticeDto.getInstanceId(), jsonObject);

            // redis流程实时数据更新
            commonServiceImpl.saveExecuteFlowData2Redis(noticeDto.getInstanceId(), this.buildInstanceRuntimeData(jgChangeRegistrationUnit));
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            if (lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }
    }

    public InstanceRuntimeData buildInstanceRuntimeData(JgChangeRegistrationUnit jgChangeRegistrationUnit) {
        return InstanceRuntimeData.builder()
                .nextExecuteUserIds(jgChangeRegistrationUnit.getNextExecuteUserIds())
                .promoter(jgChangeRegistrationUnit.getPromoter())
                .nextTaskId(jgChangeRegistrationUnit.getNextTaskId())
                .build();
    }

    //    @Transactional(rollbackFor = Exception.class)
    @GlobalTransactional(rollbackFor = Exception.class)
    public void accept(JgChangeRegistrationUnitDto dto, String op) {
        String lockKey = CommonServiceImpl.buildJgExecuteLockKey(dto.getInstanceId());
        RLock lock = redissonClient.getLock(lockKey);
        try {
            boolean isLocked = lock.tryLock(0, 180, TimeUnit.SECONDS);
            // 解决并发问题：多个人同时操作一个流程（并发执行通过、驳回、撤回）
            if (!isLocked) {
                throw new BadRequest("当前流程已经被执行！请重新打开页面查看并执行！");
            }
            // 流程执行时，状态及权限校验
            commonServiceImpl.checkForExecuteFlow(dto.getNextTaskId(), dto.getInstanceId());

            String[] taskName = new String[]{"已完成"};
            String userId = RequestContext.getExeUserId();
            String taskId = dto.getNextTaskId();
            JgChangeRegistrationUnit registration = this.JgChangeRegistrationUnitMapper.selectById(dto.getSequenceNbr());
            registration.setProcessAdvice(dto.getProcessAdvice());
            List<String> roleListNext = new ArrayList<>();
            List<String> roleListAll = new ArrayList<>();
            ArrayList<String> roleList = new ArrayList<>();
//        boolean submit = submit(jgChangeRegistrationUnit, op);
//        if (submit) {
            // getNext(roleList, dto.getInstanceId(), taskName);

            //组装信息
            TaskResultDTO task = new TaskResultDTO();
            task.setResultCode("approvalStatus");
            task.setTaskId(taskId);
            task.setComment(StringUtils.isEmpty(dto.getProcessAdvice()) ? "" : dto.getProcessAdvice());
            task.setNextExecuteUserCompanyCode(this.getNextUserOrgCode(op, registration));

            HashMap<String, Object> map = new HashMap<>();
            map.put("approvalStatus", op);
            if (!ObjectUtils.isEmpty(registration.getInstanceStatus()) &&
                    (registration.getStatus().equals(WorkFlowStatusEnum.UNIT_RENAME_SUBMIT.getReject()) ||
                            registration.getStatus().equals(WorkFlowStatusEnum.UNIT_RENAME_SUBMIT.getRollBack()))) {
                map.put("approvalStatus", "提交");
            }
            task.setVariable(map);
            //执行流程
            ProcessTaskDTO processTaskDTO = cmWorkflowService.completeOrReject(taskId, task, op);
            String taskCode = FlowStatusEnum.TO_BE_FINISHED.getName();
            String taskName1 = "";
            String nextTaskId = "";
            this.buildRoleList(Collections.singletonList(processTaskDTO), roleList, roleListAll);
            List<WorkflowResultDto> workflowResultDtos = commonServiceImpl.buildWorkFlowInfo(Collections.singletonList(processTaskDTO));
            String nextUserIds = workflowResultDtos.get(0).getNextExecutorUserIds();
            if (processTaskDTO != null && processTaskDTO.getNextTask() != null && processTaskDTO.getNextTask().size() > 0) {
                taskCode = processTaskDTO.getNextTask().get(0).getKey();
                taskName1 = processTaskDTO.getNextTask().get(0).getName();
                nextTaskId = processTaskDTO.getNextTask().get(0).getId();
            }

            registration.setStatus(taskName[0]);
            if ("0".equals(op)) {
                if (roleList.isEmpty()) {
                    registration.setStatus(taskName[0]);
                    registration.setAuditPassDate(new Date());
                    // 生成新的使用登记编号，使用登记证  修改设备的使用登记信息表，使用单位名称，使用单位统一信用代码，使用登记证编号，更新ES
                    LambdaQueryWrapper<JgChangeRegistrationUnitEq> queryWrapper = new LambdaQueryWrapper<>();
                    queryWrapper.eq(JgChangeRegistrationUnitEq::getUnitChangeRegistrationId, dto.getSequenceNbr());
                    List<JgChangeRegistrationUnitEq> jgChangeRegistrationUnitEqs = JgChangeRegistrationUnitEqMapper.selectList(queryWrapper);
                    for (JgChangeRegistrationUnitEq jgChangeRegistrationUnitEq : jgChangeRegistrationUnitEqs) {
                        String equipId = jgChangeRegistrationUnitEq.getEquId();
                        LambdaQueryWrapper<OtherInfo> queryWrapper1 = new LambdaQueryWrapper<>();
                        queryWrapper1.eq(OtherInfo::getRecord, equipId);
                        OtherInfo tzsJgOtherInfo = tzsJgOtherInfoMapper.selectOne(queryWrapper1);
                        if (ObjectUtils.isNotEmpty(tzsJgOtherInfo)) {
                            LambdaQueryWrapper<UseInfo> queryWrapper2 = new LambdaQueryWrapper<>();
                            queryWrapper2.eq(UseInfo::getRecord, equipId);
                            UseInfo useInfo = useInfoMapper.selectOne(queryWrapper2);
//                            String code = commonServiceImpl.generateRegistrationCode(equipId, tzsJgOtherInfo.getSupervisoryCode(), dto.getReceiveCompanyCode());
                            if (ObjectUtils.isNotEmpty(useInfo)) {
                                useInfo.setUseUnitName(registration.getNewUseUnitName());
                                useInfo.setUseUnitCreditCode(registration.getNewUseUnitCreditCode());
//                                if (ValidationUtil.isEmpty(code)) {
//                                    log.error("生成新的使用登记证编号失败");
//                                    return;
//                                }
                                useInfoMapper.updateById(useInfo);
//                        jgChangeRegistrationUnit.setUseRegistCode(code);
                            }
                            //更新使用注册登记证编号
//                            idxBizJgRegisterInfoMapper.updateUseOrgCodeByEquip(equipId, code);
                            //es中的编号信息
                            Map<String, Map<String, Object>> resultMap = new HashMap<>();
                            Map<String, Object> map1 = new HashMap<>();
//                            map1.put("USE_ORG_CODE", code);
                            map1.put("USE_UNIT_CREDIT_CODE", registration.getNewUseUnitCreditCode());
                            map1.put("USE_UNIT_NAME", registration.getNewUseUnitName());
                            resultMap.put(equipId, map1);
                            tzsServiceFeignClient.commonUpdateEsDataByIds(resultMap);
                            //修改各类告知列表，置为废弃
                            this.updataInvalidStatusByHistory(equipId, registration.getApplyNo());
                        }
                    }
                    registration.setNextTaskId(nextTaskId);
                    updateTaskModel(registration, op);
                    //新增使用登记证和设备变更记录
                    this.saveRecord(registration);
                    JgRegistrationHistory history = registrationHistoryService.lambdaQuery().eq(JgRegistrationHistory::getCurrentDocumentId, registration.getApplyNo()).one();
                    JSONArray historyJson = JSON.parseArray(history.getChangeData());
                    List<String> ids = historyJson.stream().map(v -> JSON.parseObject(v.toString()).getString("sequenceNbr")).collect(Collectors.toList());
                    List<JgUseRegistrationManage> list = useRegistrationManageService.lambdaQuery().in(BaseEntity::getSequenceNbr, ids).list();
                    LambdaQueryWrapper<TzBaseEnterpriseInfo> wrapper = new LambdaQueryWrapper<>();
                    wrapper.eq(TzBaseEnterpriseInfo::getUseCode, registration.getNewUseUnitCreditCode())
                            .eq(TzBaseEnterpriseInfo::getIsDelete, false);
                    for (JgUseRegistrationManage registrationManage : list) {
                        registrationManage.setUseUnitName(registration.getNewUseUnitName());
                        registrationManage.setUseUnitCreditCode(registration.getNewUseUnitCreditCode());
                        registrationManage.setReceiveOrgName(registration.getReceiveOrgName());
                        registrationManage.setReceiveCompanyCode(registration.getReceiveOrgCode());
                        registrationManage.setAuditPassDate(registration.getAuditPassDate());
                        if (!ObjectUtils.isEmpty(registration.getNewUseUnitCreditCode())) {
                            TzBaseEnterpriseInfo useCodeResult = tzBaseEnterpriseInfoMapper.selectOne(new QueryWrapper<TzBaseEnterpriseInfo>().eq("use_unit_code", registration.getNewUseUnitCreditCode()));
                            if (useCodeResult != null) {
                                registrationManage.setUseUnitAddress(useCodeResult.getAddress());
                            }
                        }
                    }
                    useRegistrationManageService.updateBatchById(list);
                } else {
                    registration.setNextExecutorIds(String.join(",", roleList));
                    if (!ObjectUtils.isEmpty(registration.getInstanceStatus())) {
                        registration.setInstanceStatus(registration.getInstanceStatus() + "," + String.join(",", roleList));
                    } else {
                        registration.setInstanceStatus(String.join(",", roleList));
                    }
                    registration.setPromoter(userId);
                    registration.setNextExecuteUserIds(nextUserIds);
                    registration.setNextTaskId(nextTaskId);
                    registration.setStatus(WorkFlowStatusEnum.getMessage(taskCode).getPass());
                    executeOneStep(registration, taskName1, nextUserIds, op);
                }
            } else {
                registration.setPromoter("");
                registration.setNextExecutorIds(String.join(",", roleList));
                registration.setNextTaskId(nextTaskId);
                registration.setNextExecuteUserIds(nextUserIds);
                registration.setStatus(WorkFlowStatusEnum.getMessage(taskCode).getReject());
                executeOneStep(registration, taskName1, nextUserIds, op);
            }
            JgChangeRegistrationUnitMapper.updateById(registration);

            // redis流程实时数据更新
            commonServiceImpl.saveExecuteFlowData2Redis(dto.getInstanceId(), this.buildInstanceRuntimeData(registration));
        } catch (InterruptedException e) {
            e.printStackTrace();
            throw new BadRequest("数据异常，请联系管理员");
        } finally {
            if (lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }
    }

    private Integer getTaskCodeByName(String auditStatus) {
        return commonServiceImpl.getDictionaryCodeByName(auditStatus);
    }


    /**
     * 修改各类告知列表，置为废弃
     *
     * @param equId           设备id
     * @param equipTransferId 当前告知单Id
     */
    public void updataInvalidStatusByHistory(String equId, String equipTransferId) {
        //改造变更登记
        jgChangeRegistrationReformEqMapper.updateEquipIsVaildByEquipIdAndCurrentDocumentId(equId, equipTransferId);
        //移装变更登记
        jgChangeRegistrationTransferEqMapper.updateEquipIsVaildByEquipIdAndCurrentDocumentId(equId, equipTransferId);
        //使用登记
        jgUseRegistrationEqMapper.updateEquipIsVaildByEquipIdAndCurrentDocumentId(equId, equipTransferId);
        //单位变更登记
        jgChangeRegistrationUnitEqMapper.updateEquipIsVaildByEquipIdAndCurrentDocumentId(equId, equipTransferId);
        //更名变更登记
        jgChangeRegistrationNameEqMapper.updateEquipIsVaildByEquipIdAndCurrentDocumentId(equId, equipTransferId);
    }


    public String getCode(String supervisoryCode) {
        if (!ObjectUtils.isEmpty(supervisoryCode) && supervisoryCode.length() > 5) {
            String name = EquipTypeEnum.getMessage(supervisoryCode.substring(1, 2));
            String type = supervisoryCode.substring(2, 4);
            String city = supervisoryCode.substring(0, 1);
            ResponseModel<String> stringResponseModel = tzsServiceFeignClient.useRegistrationCode(name + type + "陕" + city);
            return stringResponseModel.getResult();
        }
        return null;
    }


    /**
     * 导出使用登记证
     *
     * @param sequenceNbr
     */
    public void exportUseRegistrationCertificate(String sequenceNbr, HttpServletResponse response, String printType) {
        Map<String, Object> exportParamsMap = new HashMap<>();
        //查询移装变更详情
        JgChangeRegistrationUnit transfer = this.getById(sequenceNbr);
        LambdaQueryWrapper<JgChangeRegistrationUnitEq> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(JgChangeRegistrationUnitEq::getUnitChangeRegistrationId, transfer.getSequenceNbr());
        JgChangeRegistrationUnitEq jgChangeRegistrationUnitEq = JgChangeRegistrationUnitEqMapper.selectOne(queryWrapper);
        if (ValidationUtil.isEmpty(transfer) || ValidationUtil.isEmpty(jgChangeRegistrationUnitEq)) {
            throw new BadRequest("使用登记证导出失败,请稍后重试!");
        }
        //是否废弃
        exportParamsMap.put("isInvalid", ValidationUtil.isEmpty(jgChangeRegistrationUnitEq.getIsInvalid()) ? "0" : jgChangeRegistrationUnitEq.getIsInvalid());
        //登记机关
        exportParamsMap.put("receiveOrgName", transfer.getReceiveOrgName());
        //使用登记证编号
        exportParamsMap.put("useRegistrationCode", ValidationUtil.isEmpty(transfer.getUseRegistCode()) ? "" : transfer.getUseRegistCode());
        //使用单位名称
        exportParamsMap.put("useUnitName", transfer.getNewUseUnitName());
        //监管码
        LambdaQueryWrapper<OtherInfo> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(OtherInfo::getRecord, jgChangeRegistrationUnitEq.getEquId());
        OtherInfo tzsJgOtherInfo = tzsJgOtherInfoMapper.selectOne(queryWrapper1);
        exportParamsMap.put("supervisoryCode", tzsJgOtherInfo.getSupervisoryCode());

        getAuditPassedDate(transfer.getAuditPassDate(), exportParamsMap);

        //设备使用地址


        //查询设备注册信息
        IdxBizJgRegisterInfo registerInfo = idxBizJgRegisterInfoService.getOne(new QueryWrapper<IdxBizJgRegisterInfo>().eq("RECORD", jgChangeRegistrationUnitEq.getEquId()));
        if (!ValidationUtil.isEmpty(registerInfo)) {
            //设备种类、类别、品种
            String equList = registerInfo.getEquList();//设备种类
            String equCategory = registerInfo.getEquCategory();//设备类别
            String equDefine = registerInfo.getEquDefine();//设备品种
            List<EquipmentCategory> categoryList0 = commonService.getEquipmentCategoryList(equList, null);
            List<EquipmentCategory> categoryList1 = commonService.getEquipmentCategoryList(equCategory, null);
            if (org.apache.commons.collections.CollectionUtils.isNotEmpty(categoryList1)) {
                exportParamsMap.put("equList", categoryList0.get(0).getName());
            }
            if (org.apache.commons.collections.CollectionUtils.isNotEmpty(categoryList1)) {
                exportParamsMap.put("equCategory", categoryList1.get(0).getName());
            }
            if (!ValidationUtil.isEmpty(equDefine)) {
                List<EquipmentCategory> categoryList2 = commonService.getEquipmentCategoryList(equDefine, null);
                if (org.apache.commons.collections.CollectionUtils.isNotEmpty(categoryList2)) {
                    exportParamsMap.put("equDefine", categoryList2.get(0).getName());
                }
            }
            //设备代码
            exportParamsMap.put("equCode", registerInfo.getEquCode());
        }

        //单位内部编码
        IdxBizJgUseInfo useInfo = idxBizJgUseInfoService.getOneData(jgChangeRegistrationUnitEq.getEquId());
        if (!ValidationUtil.isEmpty(useInfo)) {
            exportParamsMap.put("useInnerCode", useInfo.getUseInnerCode());

            String fullAddress = "";
            String province = ValidationUtil.isEmpty(useInfo.getProvinceName()) ? "" : useInfo.getProvinceName();
            String city = ValidationUtil.isEmpty(useInfo.getCityName()) ? "" : useInfo.getCityName();
            String county = ValidationUtil.isEmpty(useInfo.getCountyName()) ? "" : useInfo.getCountyName();
            String street = ValidationUtil.isEmpty(useInfo.getStreetName()) ? "" : useInfo.getStreetName();
            String address = ValidationUtil.isEmpty(useInfo.getAddress()) ? "" : useInfo.getAddress();
            fullAddress = province + city + county + street + address;
            exportParamsMap.put("fullAddress", fullAddress);
        }
        IdxBizJgFactoryInfo factoryInfo = idxBizJgFactoryInfoService.getOneData(jgChangeRegistrationUnitEq.getEquId());
        //产品编号(出厂编号)
        if (!ValidationUtil.isEmpty(factoryInfo)) {
            exportParamsMap.put("factoryNum", factoryInfo.getFactoryNum());
        }
        //调用生成使用登记证
        exportParamsMap.put("excelType", "变更登记");
        exportParamsMap.put("tableName", "特种设备单位变更登记");
        exportParamsMap.put("applyNo", transfer.getApplyNo());
        if ("0".equals(printType)) {
            //调用生成使用登记证
            commonService.generateCertificateReport(exportParamsMap, response);
        } else {
            commonService.generatePdfPrint(exportParamsMap, response);
        }
    }


    private String buildTaskContent(JgChangeRegistrationUnit obj) {
        //发起电梯登记业务申请，【申请单号SYDJ202400001】
        return "发起了【单位变更登记】业务申请，【申请单号" + obj.getApplyNo() + "】";
    }

    private String buildRecordContent(JgChangeRegistrationUnit obj) {
        //张三办理了【单位变更】 ，单号【DWBG202407050001】，原恒星电梯单位变更为新恒星电梯有限公司，办理日期2024-07-05
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日");
        return obj.getCreateUserName() + "办理了【单位变更登记】，单号【"
                + obj.getApplyNo() + "】，原" + obj.getUseUnitName() + "变更为新"
                + obj.getNewUseUnitName() + "，申请日期" + simpleDateFormat.format(obj.getCreateDate());
    }

    private void createTaskModel(JgChangeRegistrationUnit dto, String taskName, String submitType, String nextUserIds) {
        ReginParams reginParams = JSON.parseObject(redisUtils.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken())).toString(), ReginParams.class);
        if ("1".equals(submitType)) {
            TaskModelDto taskModelDto = new TaskModelDto();
            taskModelDto.setFlowCreateDate(dto.getApplyDate());
            taskModelDto.setTaskName(taskName);
            taskModelDto.setTaskCode(dto.getApplyNo());
            taskModelDto.setTaskContent(this.buildTaskContent(dto));
            taskModelDto.setTaskDesc("");
            taskModelDto.setTaskType(BusinessTypeEnum.JG_COMPANY_CHANGE_REGISTRATION.getCode());
            taskModelDto.setTaskTypeLabel(BusinessTypeEnum.JG_COMPANY_CHANGE_REGISTRATION.getName());
            taskModelDto.setRelationId(dto.getInstanceId());
            taskModelDto.setExecuteUserIds(nextUserIds);
            taskModelDto.setFlowStatus(this.getTaskStatusByName(dto.getStatus()));
            taskModelDto.setFlowStatusLabel(dto.getStatus());
            taskModelDto.setTaskStatusLabel(dto.getAuditStatus());
            taskModelDto.setStartUserId(RequestContext.getExeUserId());
            taskModelDto.setStartUser(reginParams.getUserModel().getRealName());
            taskModelDto.setStartUserCompanyName(dto.getUseUnitName());
            taskModelDto.setNextExecuteUser(dto.getNextExecutorIds());
            taskModelDto.setStartDate(dto.getCreateDate());
            TaskMessageDto obj = new TaskMessageDto();
            obj.setInstanceId(dto.getInstanceId());
            obj.setStatus(dto.getStatus());
            obj.setPromoter(dto.getPromoter());
            obj.setNextExecuteUserIds(dto.getNextExecuteUserIds());
            obj.setSequenceNbr(dto.getSequenceNbr());
            obj.setNextTaskId(dto.getNextTaskId());
            taskModelDto.setModel(obj);
            commonServiceImpl.buildTaskModel(Collections.singletonList(taskModelDto));
        }
    }

    private void buildRoleList(List<ProcessTaskDTO> processTasks, List<String> roleListNext, List<String> roleListAll) {
        processTasks.forEach(p -> {
            p.getNextCandidateGroups().values().forEach(e -> {
                roleListNext.addAll(e);
                roleListAll.addAll(e);
            });
            roleListAll.addAll(p.getCandidateGroups());
        });
    }

//    private void executeOneStep(JgChangeRegistrationUnit jgChangeRegistrationName, String taskName, String nextUserIds, String operate) {
//        // 先更新之前的待办
//        TaskV2Model taskV2Model = updateTaskModel(jgChangeRegistrationName, operate);
//        TaskModelDto taskModelDto = new TaskModelDto();
//        taskModelDto.setTaskDesc("");
//        taskModelDto.setTaskContent(this.buildTaskContent(jgChangeRegistrationName));
//        taskV2Model.setTaskName(taskName);
//        taskModelDto.setTaskDesc("");
//        taskModelDto.setTaskCode(jgChangeRegistrationName.getApplyNo());
//        taskV2Model.setExecuteUserIds(nextUserIds);
//        taskV2Model.setRelationId(jgChangeRegistrationName.getInstanceId());
//        taskV2Model.setTaskStatus(this.getTaskStatusByName(jgChangeRegistrationName.getAuditStatus()));
//        taskV2Model.setTaskStatusLabel(jgChangeRegistrationName.getAuditStatus());
//        taskV2Model.setTaskType(BusinessTypeEnum.JG_COMPANY_CHANGE_REGISTRATION.getCode());
//        taskModelDto.setStartUser(jgChangeRegistrationName.getCreateUserName());
//        taskV2Model.setTaskTypeLabel(BusinessTypeEnum.JG_COMPANY_CHANGE_REGISTRATION.getName());
//        taskModelDto.setStartDate(jgChangeRegistrationName.getCreateDate());
//        taskModelDto.setStartUserId(jgChangeRegistrationName.getCreateUserId());
//        taskModelDto.setStartUserCompanyName(jgChangeRegistrationName.getUseUnitName());
//        taskModelDto.setExecuteUserIds(nextUserIds);
//        TaskModelDto modelDto = new TaskModelDto();
//        BeanUtil.copyProperties(taskV2Model,modelDto);
//        modelDto.setNextExecuteUser(jgChangeRegistrationName.getNextExecutorIds());
//        modelDto.setModel(jgChangeRegistrationName);
//        // 再插入新代办、数据待定
//        commonServiceImpl.buildTaskModel(Collections.singletonList(modelDto));
//    }

    private void executeOneStep(JgChangeRegistrationUnit jgChangeRegistrationName, String taskName, String nextUserIds, String operate) {
        // 先更新之前的待办
        TaskV2Model taskV2Model = updateTaskModel(jgChangeRegistrationName, operate);
        taskV2Model.setTaskDesc("");
        taskV2Model.setTaskName(taskName);
        taskV2Model.setTaskDesc("");
        taskV2Model.setTaskCode(jgChangeRegistrationName.getApplyNo());
        taskV2Model.setExecuteUserIds(nextUserIds);
        taskV2Model.setRelationId(jgChangeRegistrationName.getInstanceId());
        FlowStatusEnum flowStatusEnum = this.getTaskStatus(operate);
        taskV2Model.setTaskStatus(this.getTaskStatusByName(jgChangeRegistrationName.getStatus()));
        taskV2Model.setTaskStatusLabel(jgChangeRegistrationName.getStatus());
        taskV2Model.setFlowStatus(this.getTaskStatusByName(jgChangeRegistrationName.getStatus()));
        taskV2Model.setFlowStatusLabel(jgChangeRegistrationName.getStatus());
        //  taskV2Model.setTaskType(BusinessTypeEnum.JG_COMPANY_CHANGE_REGISTRATION.getCode());
        //  taskV2Model.setStartUser(jgChangeRegistrationName.getCreateUserName());
        //  taskV2Model.setTaskTypeLabel(BusinessTypeEnum.JG_COMPANY_CHANGE_REGISTRATION.getName());
        //  taskV2Model.setStartDate(jgChangeRegistrationName.getCreateDate());
        //  taskV2Model.setStartUserId(jgChangeRegistrationName.getCreateUserId());
        //  taskV2Model.setStartUserCompanyName(jgChangeRegistrationName.getUseUnitName());
        taskV2Model.setExecuteUserIds(nextUserIds);
        TaskModelDto modelDto = new TaskModelDto();
        BeanUtil.copyProperties(taskV2Model, modelDto);
        modelDto.setNextExecuteUser(jgChangeRegistrationName.getNextExecutorIds());
        if (jgChangeRegistrationName.getStatus().equals(WorkFlowStatusEnum.UNIT_RENAME_SUBMIT.getReject())) {
            modelDto.setPageType("edit");
        }
        TaskMessageDto obj = new TaskMessageDto();
        obj.setInstanceId(jgChangeRegistrationName.getInstanceId());
        obj.setStatus(jgChangeRegistrationName.getStatus());
        obj.setPromoter(jgChangeRegistrationName.getPromoter());
        obj.setNextExecuteUserIds(jgChangeRegistrationName.getNextExecuteUserIds());
        obj.setSequenceNbr(jgChangeRegistrationName.getSequenceNbr());
        obj.setNextTaskId(jgChangeRegistrationName.getNextTaskId());
        modelDto.setModel(obj);
        // 再插入新代办、数据待定
        commonServiceImpl.buildTaskModel(Collections.singletonList(modelDto));
    }


    private TaskV2Model updateTaskModel(JgChangeRegistrationUnit jgChangeRegistrationName, String operate) {
        Map<String, Object> params = new HashMap<>();
        FlowStatusEnum flowStatusEnum = this.getTaskStatus(operate);
        params.put("relationId", jgChangeRegistrationName.getInstanceId());
        params.put("taskStatus", flowStatusEnum.getCode());
        params.put("taskStatusLabel", flowStatusEnum.getName());
        params.put("flowStatus", this.getTaskStatusByName(jgChangeRegistrationName.getStatus()));
        params.put("flowStatusLabel", jgChangeRegistrationName.getStatus());
        params.put("model", jgChangeRegistrationName);
        return commonServiceImpl.updateTaskModel(params);
    }

    private FlowStatusEnum getTaskStatus(String operate) {
        if ("0".equals(operate)) {
            return FlowStatusEnum.TO_BE_FINISHED;
        } else {
            return FlowStatusEnum.REJECTED;
        }
    }


    private String getNextUserOrgCode(String operate, JgChangeRegistrationUnit jgChangeRegistrationName) {
        if ("0".equals(operate)) {
            // 执行通过节点，单位code为接收机构单位信息
            return jgChangeRegistrationName.getReceiveOrgCode();
        }
        if (jgChangeRegistrationName.getStatus().equals(WorkFlowStatusEnum.UNIT_RENAME_RECEIVE.getPass())
                || jgChangeRegistrationName.getStatus().equals(WorkFlowStatusEnum.UNIT_RENAME_RECEIVE.getReject())
                || jgChangeRegistrationName.getStatus().equals(WorkFlowStatusEnum.UNIT_RENAME_RECEIVE.getRollBack())) {
            // 驳回且当前节点为一键节点时，单位code为发起人单位信息
            return jgChangeRegistrationName.getUseUnitCreditCode();
        }
        // 2、3级驳回时，单位code为接收单位code
        return jgChangeRegistrationName.getReceiveOrgCode();
    }

    private Integer getTaskStatusByName(String auditStatus) {
        return commonServiceImpl.getDictionaryCodeByName(auditStatus);
    }
}