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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
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.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
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.JgScrapCancelDto;
import com.yeejoin.amos.boot.module.jg.api.entity.JgScrapCancel;
import com.yeejoin.amos.boot.module.jg.api.entity.JgScrapCancelEq;
import com.yeejoin.amos.boot.module.jg.api.enums.CancelTypeEnum;
import com.yeejoin.amos.boot.module.jg.api.enums.WorkFlowStatusEnum;
import com.yeejoin.amos.boot.module.jg.api.mapper.JgScrapCancelEqMapper;
import com.yeejoin.amos.boot.module.jg.api.mapper.JgScrapCancelMapper;
import com.yeejoin.amos.boot.module.jg.api.service.IJgScrapCancelService;
import com.yeejoin.amos.boot.module.jg.biz.feign.TzsServiceFeignClient;
import com.yeejoin.amos.boot.module.jg.biz.service.IIdxBizJgRegisterInfoService;
import com.yeejoin.amos.boot.module.jg.flc.api.fegin.WorkFlowFeignService;
import com.yeejoin.amos.boot.module.ymt.api.entity.IdxBizJgRegisterInfo;
import com.yeejoin.amos.boot.module.ymt.api.entity.IdxBizJgUseInfo;
import com.yeejoin.amos.boot.module.ymt.api.entity.SuperviseInfo;
import com.yeejoin.amos.boot.module.ymt.api.enums.ApplicationFormTypeEnum;
import com.yeejoin.amos.boot.module.ymt.api.enums.EquimentEnum;
import com.yeejoin.amos.boot.module.ymt.api.enums.FlowStatusEnum;
import com.yeejoin.amos.boot.module.ymt.api.mapper.IdxBizJgOtherInfoMapper;
import com.yeejoin.amos.boot.module.ymt.api.mapper.IdxBizJgRegisterInfoMapper;
import com.yeejoin.amos.boot.module.ymt.api.mapper.IdxBizJgUseInfoMapper;
import com.yeejoin.amos.boot.module.ymt.api.mapper.SuperviseInfoMapper;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.feign.workflow.Workflow;
import com.yeejoin.amos.feign.workflow.model.ActWorkflowBatchDTO;
import com.yeejoin.amos.feign.workflow.model.ActWorkflowStartDTO;
import com.yeejoin.amos.feign.workflow.model.AjaxResult;
import com.yeejoin.amos.feign.workflow.model.TaskResultDTO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
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.utils.ResponseModel;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 设备注销报废服务实现类
 *
 * @author system_generator
 * @date 2023-12-20
 */
@Service
public class JgScrapCancelServiceImpl extends BaseService<JgScrapCancelDto, JgScrapCancel, JgScrapCancelMapper> implements IJgScrapCancelService {


    @Autowired
    private JgScrapCancelEqServiceImpl jgScrapCancelEqService;

    @Autowired
    private JgScrapCancelEqMapper jgScrapCancelEqMapper;
    @Autowired
    WorkFlowFeignService workFlowFeginService;

    @Autowired
    TzsServiceFeignClient tzsServiceFeignClient;

    @Autowired
    private IdxBizJgUseInfoMapper idxBizJgUseInfoMapper;

    @Autowired
    IdxBizJgOtherInfoMapper idxBizJgOtherInfoMapper;

    @Autowired
    SuperviseInfoMapper superviseInfoMapper;
    @Autowired
    RedisUtils redisUtils;

    public Page<Map<String, Object>> getList(JgScrapCancelDto dto, Page<Map<String, Object>> page, List<String> roleIds) {
        ReginParams reginParams = JSONObject.parseObject(redisUtils.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken())).toString(), ReginParams.class);
        String orgCode = reginParams.getCompany().getCompanyCode();
        Page<Map<String, Object>> listPage = this.baseMapper.getListPage(page, dto, roleIds, orgCode);
        listPage.getRecords().forEach(item -> {
            if (item.containsKey("auditStatus") && Objects.nonNull(item.get("auditStatus"))) {
                item.put("auditStatusDesc", item.get("auditStatus").toString());
            }
            if (item.containsKey("cancelType") && Objects.nonNull(item.get("cancelType"))) {
                item.put("cancelTypeDesc", CancelTypeEnum.getNameByType(item.get("cancelType").toString()));
            }
        });
        return listPage;
    }


    private void convertField(JgScrapCancelDto model) {
        // 处理图片
        if (!ValidationUtil.isEmpty(model.getCancelCertificateList())) {
            model.setCancelCertificate(JSON.toJSONString(model.getCancelCertificateList()));
        }
        String receiveOrgId = model.getReceiveOrgCode();
        if (!ObjectUtils.isEmpty(receiveOrgId)) {
            String[] receiveOrgIdList = receiveOrgId.split("_");
            if (receiveOrgIdList.length > 1) {
                model.setReceiveOrgCode(receiveOrgIdList[0]);
                model.setReceiveOrgName(receiveOrgIdList[1]);
            }
        }
    }


    @SuppressWarnings({"Duplicates", "rawtypes"})
    @Transactional(rollbackFor = Exception.class)
    public void save(String submitType, Map<String, JSONObject> jgInstallationNoticeDtoMap) {
        ReginParams reginParams = JSONObject.parseObject(redisUtils.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken())).toString(), ReginParams.class);
        String[] taskName = new String[]{"流程结束"};
        JSONObject jgScrapCancelAdd = jgInstallationNoticeDtoMap.get("jgScrapCancelAdd");
        String equipId = jgScrapCancelAdd.get("record").toString();
        jgScrapCancelAdd.remove("record");

        JgScrapCancelDto model = JSON.parseObject(jgScrapCancelAdd.toJSONString(), JgScrapCancelDto.class);
        model.setSEQUENCE_NBR(equipId);
//        JgScrapCancelDto model = (JgScrapCancelDto) jgInstallationNoticeDtoMap.get("jgScrapCancelAdd");
        // 字段转换
        convertField(model);
        // 获取告知设备信息
        // 设备信息转换
        if (StrUtil.isEmpty(model.getSEQUENCE_NBR())) {
            return;
        }
        List<Map<String, Object>> deviceList = new ArrayList<>();
        HashMap<String, Object> map1 = new HashMap<>();
        map1.put("SEQUENCE_NBR", model.getSEQUENCE_NBR());
        deviceList.add(map1);

        // 获取告知单号
        ResponseModel<List<String>> listResponseModel = tzsServiceFeignClient.applicationFormCode(ApplicationFormTypeEnum.SBZX.getCode(), deviceList.size());
        if (!ObjectUtils.isEmpty(listResponseModel) && listResponseModel.getStatus() != HttpStatus.OK.value()) {
            log.error(" 获取告知单号失败");
            throw new RuntimeException();
        }
        List<String> applyNoList = listResponseModel.getResult();
        if (CollectionUtils.isEmpty(applyNoList)) {
            return;
        }

        ArrayList<String> roleListFirst = new ArrayList<>();
        ArrayList<String> roleListSecond = new ArrayList<>();
        // 判断当前是否为提交
        List<String> instanceIdList = new ArrayList<>();
        if ("1".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("scrapCancel");
                dto.setBusinessKey(String.valueOf(i));
                list.add(dto);
            }
            actWorkflowBatchDTO.setProcess(list);
            try {
                FeignClientResult result = Workflow.taskV2Client.startByVariableBatch(actWorkflowBatchDTO);
                List<Object> returnList = (List<Object>) result.getResult();
                for (Object obj : returnList) {
                    JSONObject jsonObject = JSON.parseObject(JSONObject.toJSONString(obj));
                    String instanceId = jsonObject.getString("id");
                    instanceIdList.add(instanceId);
                    // 查询下节点任务
                    if (returnList.get(0).equals(obj)) {
                        getNext(roleListFirst, instanceId, taskName);
                    }
                    // 推动下一个节点
                    AjaxResult ajaxResult = Workflow.taskClient.getTask(instanceId);
                    JSONObject dataObject = JSON.parseObject(JSON.toJSONString(ajaxResult.get("data")));
                    String taskId = dataObject.getString("id");
                    //组装信息
                    TaskResultDTO dto = new TaskResultDTO();
                    dto.setResultCode("approvalStatus");
                    dto.setTaskId(taskId);
                    dto.setComment("提交流程");
                    HashMap<String, Object> map = new HashMap<>();
                    map.put("approvalStatus", "0");
                    dto.setVariable(map);
                    //执行流程
                    AjaxResult ajaxResult1 = null;
                    try {
                        ajaxResult1 = Workflow.taskClient.completeByTask(taskId, dto);
                        if (ajaxResult1.get("code").equals(200)) {
                            getNext(roleListSecond, instanceId, taskName);
                            roleListFirst.addAll(roleListSecond);
                        } else {
                            log.error("提交失败");
                        }
                    } catch (Exception e) {
                        log.error("提交失败：{}", e);
                    }
                }
            } catch (Exception e) {
                log.error("提交失败：{}", e);
            }
        }

        List<JgScrapCancel> list = new ArrayList<>();
        List<JgScrapCancelEq> equipList = new ArrayList<>();
        deviceList.forEach(obj -> {
            JgScrapCancelEq jgRelationEquip = new JgScrapCancelEq();
            JgScrapCancel dto = new JgScrapCancel();
            BeanUtils.copyProperties(model, dto);
            int i = deviceList.indexOf(obj);
            String applyNo = applyNoList.get(i);
            dto.setApplyNo(applyNo);
            dto.setCreateDate(new Date());
            dto.setNextExecuteIds(String.join(",", roleListSecond));
            dto.setInstanceStatus(String.join(",", roleListFirst));
            dto.setPromoter(reginParams.getUserModel().getUserId());
//            dto.setStatus(taskName[0]);
            jgRelationEquip.setEquId(String.valueOf(obj.get("SEQUENCE_NBR")));
            jgRelationEquip.setEquipTransferId(applyNo);
            if (!CollectionUtils.isEmpty(instanceIdList)) {
                dto.setInstanceId(instanceIdList.get(i));
                dto.setAuditStatus(String.valueOf(WorkFlowStatusEnum.CANCEL_RECEIVE.getPass()));
            } else {
                dto.setAuditStatus(String.valueOf(WorkFlowStatusEnum.CANCEL_SUBMIT.getPass()));
            }
            dto.setUseUnitCode(reginParams.getCompany().getCompanyCode());
            dto.setUseUnitName(reginParams.getCompany().getCompanyName());
            list.add(dto);
            equipList.add(jgRelationEquip);
        });
        this.saveBatch(list);
        List<JgScrapCancelEq> jgScrapCancelEqList = equipList.stream().map(t -> {
            List<JgScrapCancel> collect = list.stream().filter(item -> t.getEquipTransferId().equals(item.getApplyNo())).collect(Collectors.toList());
            Long sequenceNbr = collect.get(0).getSequenceNbr();
            return t.setEquipTransferId(String.valueOf(sequenceNbr));
        }).collect(Collectors.toList());
        jgScrapCancelEqService.saveBatch(jgScrapCancelEqList);
    }


    public void deleteBatch(List<Long> ids) {
        JgScrapCancel jgScrapCancel = new JgScrapCancel();
        jgScrapCancel.setIsDelete(true);
        LambdaQueryWrapper<JgScrapCancel> lambda = new QueryWrapper<JgScrapCancel>().lambda();
        lambda.in(JgScrapCancel::getSequenceNbr, ids);
        this.update(jgScrapCancel, lambda);
    }


    public JgScrapCancelDto updateInfo(String submitType, JgScrapCancelDto jgScrapCancelDto, String op) {
        if (Objects.isNull(jgScrapCancelDto) || StringUtils.isEmpty(submitType)) {
            throw new IllegalArgumentException("参数不能为空");
        }
        String[] taskName = new String[]{"流程结束"};
        // 字段转换
        this.convertField(jgScrapCancelDto);
        ArrayList<String> roleListFirst = new ArrayList<>();
        ArrayList<String> roleListSecond = new ArrayList<>();
        if ("1".equals(submitType)) {
            AjaxResult ajaxResult;
            // 发起流程
            if (!StringUtils.hasText(jgScrapCancelDto.getInstanceId())) {
                ActWorkflowStartDTO dto = new ActWorkflowStartDTO();
                dto.setProcessDefinitionKey("scrapCancel");
                dto.setBusinessKey("1");
                try {
                    ajaxResult = Workflow.taskClient.startByVariable(dto);
                    String instanceId = ((Map) ajaxResult.get("data")).get("id").toString();
                    jgScrapCancelDto.setInstanceId(instanceId);
                    // 查询下节点任务
                    getNext(roleListFirst, instanceId, taskName);
                    jgScrapCancelDto.setInstanceStatus(String.join(",", roleListFirst));
                } catch (Exception e) {
                    log.error("提交失败：{}", e);
                }
            }
            JgScrapCancel jgScrapCancel = new JgScrapCancel();
            BeanUtils.copyProperties(jgScrapCancelDto, jgScrapCancel, "useUnitName", "useUnitName");
            boolean submit = submit(jgScrapCancel, op);
            LambdaUpdateWrapper<JgScrapCancelEq> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(JgScrapCancelEq::getEquipTransferId, jgScrapCancel.getSequenceNbr());
            JgScrapCancelEq jgScrapCancelEq = new JgScrapCancelEq();
            jgScrapCancelEq.setEquId(jgScrapCancelDto.getRecord());
            jgScrapCancelEqMapper.update(jgScrapCancelEq, updateWrapper);
            if (submit) {
                // 查询下节点任务
                getNext(roleListSecond, jgScrapCancel.getInstanceId(), taskName);

                String join = String.join(",", roleListSecond);
//                jgScrapCancel.setStatus(taskName[0]);
                if (!ObjectUtils.isEmpty(jgScrapCancel.getInstanceStatus())) {
                    jgScrapCancel.setInstanceStatus(jgScrapCancel.getInstanceStatus() + "," + join);
                } else {
                    jgScrapCancel.setInstanceStatus(String.join(",", roleListSecond));
                }
                jgScrapCancel.setPromoter(RequestContext.getExeUserId());
                jgScrapCancel.setNextExecuteIds(String.join(",", roleListSecond));
                jgScrapCancel.setAuditStatus(String.valueOf(WorkFlowStatusEnum.CANCEL_RECEIVE.getPass()));
                this.updateById(jgScrapCancel);
            }
        } else {
            JgScrapCancel bean = new JgScrapCancel();
            BeanUtils.copyProperties(jgScrapCancelDto, bean);
            this.updateById(bean);
            LambdaUpdateWrapper<JgScrapCancelEq> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(JgScrapCancelEq::getEquipTransferId, bean.getSequenceNbr());
            JgScrapCancelEq jgScrapCancelEq = new JgScrapCancelEq();
            jgScrapCancelEq.setEquId(jgScrapCancelDto.getRecord());
            jgScrapCancelEqMapper.update(jgScrapCancelEq, updateWrapper);
        }
        return jgScrapCancelDto;
    }


    public boolean submit(JgScrapCancel 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);
        dto.setComment("提交流程");
        HashMap<String, Object> map = new HashMap<>();
        map.put("approvalStatus", op);
        dto.setVariable(map);
        //执行流程
        AjaxResult ajaxResult1 = null;
        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;
        }
    }

    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");
            AjaxResult taskGroupName = Workflow.taskClient.getTaskGroupName(nextTaskId);
            taskName[0] = taskNoAuth.getString("name");
            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());
                }
            }
        }
    }
    @Autowired
    IdxBizJgRegisterInfoMapper idxBizJgRegisterInfoMapper;

    @Autowired
    IIdxBizJgRegisterInfoService idxBizJgRegisterInfoService;

    public Map<String, Object> queryBySequenceNbr(Long sequenceNbr) {
        // 安装告知信息
        JgScrapCancel notice = this.baseMapper.selectById(sequenceNbr);
        if (Objects.isNull(notice)) {
            return null;
        }
        Map<String, Object> installationInfo = BeanUtil.beanToMap(notice);
        installationInfo.put("receiveOrgCode", notice.getReceiveOrgCode() + "_" + notice.getReceiveOrgName());
        installationInfo.put("cancelCertificateList", JSON.parseArray(installationInfo.get("cancelCertificate").toString()));
        LambdaQueryWrapper<JgScrapCancelEq> lambdaEq = new QueryWrapper<JgScrapCancelEq>().lambda();
        lambdaEq.eq(JgScrapCancelEq::getEquipTransferId, sequenceNbr);
        JgScrapCancelEq jgScrapCancelEq = jgScrapCancelEqMapper.selectOne(lambdaEq);
        // 设备信息
        installationInfo.put("record", jgScrapCancelEq.getEquId());

        LambdaQueryWrapper<IdxBizJgRegisterInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(IdxBizJgRegisterInfo::getRecord, jgScrapCancelEq.getEquId());
        queryWrapper.last("limit 1");
        IdxBizJgRegisterInfo one = idxBizJgRegisterInfoMapper.selectOne(queryWrapper);
        installationInfo.put("equCode", one.getEquCode());
        Map<String, Object> detailFieldCamelCaseByRecord = idxBizJgRegisterInfoService.getDetailFieldCamelCaseByRecord(jgScrapCancelEq.getEquId());
//        Map<String, Object> equipmentInfos = this.baseMapper.queryEquipInformation(sequenceNbr);
        BeanUtil.copyProperties(installationInfo, detailFieldCamelCaseByRecord);
        return new HashMap<String, Object>() {{
            this.put("jgScrapCancelAdd", detailFieldCamelCaseByRecord);
        }};
    }


    public void revocation(String instanceId) {
        ReginParams reginParams = JSONObject.parseObject(redisUtils.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken())).toString(), ReginParams.class);
//        String taskName = "";
        String taskCode = FlowStatusEnum.TO_BE_FINISHED.getName();
        JgScrapCancel jgScrapCancel = new JgScrapCancel();
        LambdaQueryWrapper<JgScrapCancel> lambda = new QueryWrapper<JgScrapCancel>().lambda();
        lambda.eq(JgScrapCancel::getInstanceId, instanceId);
        ArrayList<String> roleList = new ArrayList<>();
        try {
            workFlowFeginService.rollBack(instanceId);
            JSONObject taskNoAuth = workFlowFeginService.getTaskNoAuth(instanceId);
            JSONObject nextTask = JSON.parseObject(JSON.toJSONString(taskNoAuth.get("data")));
//            taskName = nextTask.getString("name");
            if (!ObjectUtils.isEmpty(taskNoAuth.get("data"))) {
                String nextTaskId = nextTask.getString("id");
                FeignClientResult<JSONObject> nodeInfo = workFlowFeginService.getNodeInfo(nextTaskId);
                JSONObject result = nodeInfo.getResult();
                Map<String, Object> taskInfo = (Map<String, Object>) result.get("taskInfo");
                taskCode = 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")) {
                        roleList.add(((Map<?, ?>) datum).get("groupId").toString());
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (!FlowStatusEnum.TO_BE_FINISHED.getName().equals(taskCode)) {
            jgScrapCancel.setAuditStatus(WorkFlowStatusEnum.getMessage(taskCode).getRollBack());
        }
        String join = String.join(",", roleList);
        jgScrapCancel.setPromoter(reginParams.getUserModel().getUserId());
        jgScrapCancel.setNextExecuteIds(join);
        this.update(jgScrapCancel, lambda);
    }


    public void flowExecute(Long id, String instanceId, String operate, String comment) {
        try {
            JSONObject task = workFlowFeginService.getTaskNoAuth(instanceId);
            JSONObject taskMessage = JSON.parseObject(JSON.toJSONString(task.get("data")));
            String taskId = taskMessage.getString("id");
            //组装信息
            TaskResultDTO dto = new TaskResultDTO();
            dto.setResultCode("approvalStatus");
            dto.setTaskId(taskId);
            dto.setComment(comment);
            HashMap<String, Object> map = new HashMap<>();
            map.put("approvalStatus", operate);
            dto.setVariable(map);
            //执行流程
            Workflow.taskClient.completeByTask(taskId, dto);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 更新下一步执行人
        updateExecuteIds(instanceId, id, operate);

    }


    public void updateExecuteIds(String instanceId, Long sequenceNbr, String operate) {
        ReginParams reginParams = JSONObject.parseObject(redisUtils.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken())).toString(), ReginParams.class);
        String role = "";
//        String taskName = "流程结束";
        String taskCode = FlowStatusEnum.TO_BE_FINISHED.getName();
        ArrayList<String> roleList = new ArrayList<>();
        JgScrapCancel jgScrapCancel = this.getBaseMapper().selectById(sequenceNbr);
        try {
            // 查询下节点任务
            JSONObject taskNoAuth = workFlowFeginService.getTaskNoAuth(instanceId);
            if (!ObjectUtils.isEmpty(taskNoAuth.get("data"))) {
                JSONObject nextTask = JSON.parseObject(JSON.toJSONString(taskNoAuth.get("data")));
                String nextTaskId = nextTask.getString("id");
                FeignClientResult<JSONObject> nodeInfo = workFlowFeginService.getNodeInfo(nextTaskId);
                JSONObject result = nodeInfo.getResult();
                Map<String, Object> taskInfo = (Map<String, Object>) result.get("taskInfo");
                taskCode = 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")) {
                        roleList.add(((Map) datum).get("groupId").toString());
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (!FlowStatusEnum.TO_BE_FINISHED.getName().equals(taskCode)) {
            role = String.join(",", roleList);
            jgScrapCancel.setNextExecuteIds(role);
            jgScrapCancel.setPromoter(reginParams.getUserModel().getUserId());
            jgScrapCancel.setInstanceId(instanceId);
            if (!ObjectUtils.isEmpty(jgScrapCancel.getInstanceStatus())) {
                jgScrapCancel.setInstanceStatus(jgScrapCancel.getInstanceStatus() + "," + role);
            } else {
                jgScrapCancel.setInstanceStatus(role);
            }
            if ("0".equals(operate)) {
                // 通过操作
                jgScrapCancel.setAuditStatus(WorkFlowStatusEnum.getMessage(taskCode).getPass());
            } else {
                // 驳回操作
                jgScrapCancel.setAuditStatus(WorkFlowStatusEnum.getMessage(taskCode).getReject());
                jgScrapCancel.setPromoter(null);
            }
        } else {

            LambdaQueryWrapper<JgScrapCancelEq> lambdaEq = new QueryWrapper<JgScrapCancelEq>().lambda();
            lambdaEq.eq(JgScrapCancelEq::getEquipTransferId, sequenceNbr);
            JgScrapCancelEq jgScrapCancelEq = jgScrapCancelEqMapper.selectOne(lambdaEq);

            ResponseModel<String> responseModel = tzsServiceFeignClient.useRegistrationCode(idxBizJgOtherInfoMapper.getSupervisoryCodeByEquipmentCode(jgScrapCancelEq.getEquId()));
            String newUseRegistrationCertificateNumber = responseModel.getResult().split("-")[0];

            Map<String, Map<String, Object>> resultMap = new HashMap<>();
            Map<String, Object> map1 = new HashMap<>();
            map1.put("USE_ORG_CODE", newUseRegistrationCertificateNumber);
            if (CancelTypeEnum.SCRAPPED.getCode().equals(jgScrapCancel.getCancelType())) {
                IdxBizJgUseInfo idxBizJgUseInfo = new IdxBizJgUseInfo();
                idxBizJgUseInfo.setEquState(String.valueOf(EquimentEnum.BAOFEI.getCode()));
                LambdaQueryWrapper<IdxBizJgUseInfo> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(IdxBizJgUseInfo::getRecord, jgScrapCancelEq.getEquId());
                idxBizJgUseInfoMapper.update(idxBizJgUseInfo, wrapper);
                map1.put("EQU_STATE", String.valueOf(EquimentEnum.BAOFEI.getCode()));
            } else {
                SuperviseInfo superviseInfo = new SuperviseInfo();
                superviseInfo.setOrgBranchCode("");
                superviseInfo.setOrgBranchName("");
                LambdaQueryWrapper<SuperviseInfo> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(SuperviseInfo::getRecord, jgScrapCancelEq.getEquId());
                superviseInfoMapper.update(superviseInfo, wrapper);
                map1.put("ORG_BRANCH_CODE", "");
                map1.put("ORG_BRANCH_NAME", "");
            }
            resultMap.put(jgScrapCancelEq.getEquId(), map1);
            tzsServiceFeignClient.commonUpdateEsDataByIds(resultMap);
            jgScrapCancel.setAuditStatus(FlowStatusEnum.TO_BE_FINISHED.getName());
            jgScrapCancel.setAuditPassDate(new Date());
        }
        this.getBaseMapper().updateById(jgScrapCancel);

    }
}