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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
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.JgChangeRegistrationNameDto;
import com.yeejoin.amos.boot.module.jg.api.entity.*;
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.IJgChangeRegistrationNameService;
import com.yeejoin.amos.boot.module.jg.biz.feign.TzsServiceFeignClient;
import com.yeejoin.amos.boot.module.jg.flc.api.fegin.WorkFlowFeignService;
import com.yeejoin.amos.boot.module.ymt.api.entity.TzBaseEnterpriseInfo;
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.TzBaseEnterpriseInfoMapper;
import com.yeejoin.amos.boot.module.ymt.flc.api.entity.RegUnitInfo;
import com.yeejoin.amos.boot.module.ymt.flc.api.feign.AccessFeignService;
import com.yeejoin.amos.boot.module.ymt.flc.api.mapper.RegUnitInfoMapper;
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-25
 */
@Service
public class JgChangeRegistrationNameServiceImpl extends BaseService<JgChangeRegistrationNameDto, JgChangeRegistrationName, JgChangeRegistrationNameMapper> implements IJgChangeRegistrationNameService {

    @Autowired
    private JgChangeRegistrationNameEqServiceImpl jgChangeRegistrationNameEqService;

    @Autowired
    private JgRegistrationHistoryServiceImpl jgRegistrationHistoryService;

    @Autowired
    RedisUtils redisUtils;

    @Autowired
    JgChangeRegistrationNameMapper jgChangeRegistrationNameMapper;

    @Autowired
    TzsServiceFeignClient tzsServiceFeignClient;

    @Autowired
    WorkFlowFeignService workFlowFeignService;

    @Autowired
    private JgChangeRegistrationReformEqMapper jgChangeRegistrationReformEqMapper;

    @Autowired
    private JgChangeRegistrationTransferEqMapper jgChangeRegistrationTransferEqMapper;

    @Autowired
    private JgUseRegistrationEqMapper jgUseRegistrationEqMapper;

    @Autowired
    private JgChangeRegistrationUnitEqMapper jgChangeRegistrationUnitEqMapper;

    @Autowired
    private JgChangeRegistrationNameEqMapper jgChangeRegistrationNameEqMapper;

    @Autowired
    private RegUnitInfoMapper regUnitInfoMapper;

    @Autowired
    private TzBaseEnterpriseInfoMapper tzBaseEnterpriseInfoMapper;

    @Autowired
    AccessFeignService accessFeignService;

    @Transactional(rollbackFor = Exception.class)
    public void save(String submitType, Map<String, JSONObject> jgRegistrationInfoMap) {
        ReginParams reginParams = JSON.parseObject(redisUtils.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken())).toString(), ReginParams.class);
        String[] taskName = new String[]{"流程结束"};
        JSONObject jgRegistrationInfo = jgRegistrationInfoMap.get("jgRegistrationInfo");

        JgChangeRegistrationNameDto model = JSON.parseObject(jgRegistrationInfo.toJSONString(), JgChangeRegistrationNameDto.class);


        List<Map<String, Object>> deviceList = jgChangeRegistrationNameMapper.getEquipInfoByOrgCode(reginParams.getCompany().getCompanyCode());

        // 获取告知单号
        ResponseModel<List<String>> listResponseModel = tzsServiceFeignClient.applicationFormCode(ApplicationFormTypeEnum.SBZX.getCode(), 1);
        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)) {
            // 发起流程
            ActWorkflowBatchDTO actWorkflowBatchDTO = new ActWorkflowBatchDTO();
            List<ActWorkflowStartDTO> list = new ArrayList<>();
            ActWorkflowStartDTO dto = new ActWorkflowStartDTO();
            dto.setProcessDefinitionKey("unitRename");
            dto.setBusinessKey("1");
            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 dto2 = new TaskResultDTO();
                    dto2.setResultCode("approvalStatus");
                    dto2.setTaskId(taskId);
                    dto2.setComment("提交流程");
                    HashMap<String, Object> map = new HashMap<>();
                    map.put("approvalStatus", "0");
                    dto2.setVariable(map);
                    //执行流程
                    AjaxResult ajaxResult1 = null;
                    try {
                        ajaxResult1 = Workflow.taskClient.completeByTask(taskId, dto2);
                        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);
            }
        }

        JgChangeRegistrationName dto = new JgChangeRegistrationName();
        // 字段转换
        convertField(model);
        BeanUtils.copyProperties(model, dto);

        dto.setApplyNo(applyNoList.get(0));
        dto.setCreateDate(new Date());
        dto.setNextExecutorIds(String.join(",", roleListSecond));
        dto.setInstanceStatus(String.join(",", roleListFirst));
        dto.setPromoter(reginParams.getUserModel().getUserId());
        if (!CollectionUtils.isEmpty(instanceIdList)) {
            dto.setInstanceId(instanceIdList.get(0));
            dto.setAuditStatus(String.valueOf(WorkFlowStatusEnum.UNIT_RENAME_RECEIVE.getPass()));
        } else {
            dto.setAuditStatus(String.valueOf(WorkFlowStatusEnum.UNIT_RENAME_SUBMIT.getPass()));
        }
        dto.setUseUnitCreditCode(reginParams.getCompany().getCompanyCode());
        dto.setUseUnitName(reginParams.getCompany().getCompanyName());
        this.save(dto);

        List<JgChangeRegistrationNameEq> equipList = new ArrayList<>();
        List<JgRegistrationHistory> list = new ArrayList<>();
        deviceList.forEach(obj -> {
            JgChangeRegistrationNameEq jgRelationEquip = new JgChangeRegistrationNameEq();
            jgRelationEquip.setEquId(String.valueOf(obj.get("equipId")));
            jgRelationEquip.setNameChangeRegistrationId(String.valueOf(dto.getSequenceNbr()));
            jgRelationEquip.setIsInvalid("0");
            jgRelationEquip.setCreateDate(dto.getCreateDate());
            jgRelationEquip.setCreateUserId(reginParams.getUserModel().getUserId());
            jgRelationEquip.setCreateUserName(reginParams.getUserModel().getRealName());
            equipList.add(jgRelationEquip);

            JgRegistrationHistory jgRegistrationHistory = new JgRegistrationHistory();
            jgRegistrationHistory.setCreateUserId(reginParams.getUserModel().getUserId());
            jgRegistrationHistory.setCreateDate(dto.getCreateDate());
            jgRegistrationHistory.setChangeData(JSON.toJSONString(dto));
            jgRegistrationHistory.setOldData(JSON.toJSONString(dto));
            jgRegistrationHistory.setRegistrationClass("使用单位名称变更登记");
            jgRegistrationHistory.setStatus("new");
            jgRegistrationHistory.setEquId(String.valueOf(obj.get("equipId")));
            jgRegistrationHistory.setSupervisoryCode(String.valueOf(obj.get("supervisoryCode")));
            jgRegistrationHistory.setUseRegistrationCode(String.valueOf(obj.get("useOrgCode")));
            jgRegistrationHistory.setCurrentDocumentId(dto.getApplyNo());
            list.add(jgRegistrationHistory);
        });
        jgChangeRegistrationNameEqService.saveBatch(equipList);
        jgRegistrationHistoryService.saveBatch(list);
    }

    public JgChangeRegistrationNameDto updateInfo(String submitType, JgChangeRegistrationNameDto jgChangeRegistrationNameDto, String op) {
        ReginParams reginParams = JSON.parseObject(redisUtils.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken())).toString(), ReginParams.class);
        if (Objects.isNull(jgChangeRegistrationNameDto) || StringUtils.isEmpty(submitType)) {
            throw new IllegalArgumentException("参数不能为空");
        }
        String[] taskName = new String[]{"流程结束"};
        // 字段转换
        this.convertField(jgChangeRegistrationNameDto);
        ArrayList<String> roleListFirst = new ArrayList<>();
        ArrayList<String> roleListSecond = new ArrayList<>();
        if ("1".equals(submitType)) {
            AjaxResult ajaxResult;
            // 发起流程
            if (!StringUtils.hasText(jgChangeRegistrationNameDto.getInstanceId())) {
                ActWorkflowStartDTO dto = new ActWorkflowStartDTO();
                dto.setProcessDefinitionKey("unitRename");
                dto.setBusinessKey("1");
                try {
                    ajaxResult = Workflow.taskClient.startByVariable(dto);
                    String instanceId = ((Map) ajaxResult.get("data")).get("id").toString();
                    jgChangeRegistrationNameDto.setInstanceId(instanceId);
                    // 查询下节点任务
                    getNext(roleListFirst, instanceId, taskName);
                    jgChangeRegistrationNameDto.setInstanceStatus(String.join(",", roleListFirst));
                } catch (Exception e) {
                    log.error("提交失败：{}", e);
                }
            }
            JgChangeRegistrationName jgChangeRegistrationName = this.getById(jgChangeRegistrationNameDto.getSequenceNbr());
            BeanUtils.copyProperties(jgChangeRegistrationNameDto, jgChangeRegistrationName);

            boolean submit = submit(jgChangeRegistrationName, op);
            //删除重新生成 eq表数据
            if (!Objects.isNull(jgChangeRegistrationName.getSequenceNbr())) {
                jgChangeRegistrationNameMapper.deleteByChangeRegistrationId(jgChangeRegistrationName.getSequenceNbr());
            }
            if (!Objects.isNull(jgChangeRegistrationName.getApplyNo())) {
                jgChangeRegistrationNameMapper.deleteHistoryInfoById(jgChangeRegistrationName.getApplyNo());
            }


            List<Map<String, Object>> deviceList = jgChangeRegistrationNameMapper.getEquipInfoByOrgCode(reginParams.getCompany().getCompanyCode());
            List<JgRegistrationHistory> list = new ArrayList<>();
            List<JgChangeRegistrationNameEq> equipList = new ArrayList<>();
            deviceList.forEach(obj -> {
                JgChangeRegistrationNameEq jgRelationEquip = new JgChangeRegistrationNameEq();
                jgRelationEquip.setEquId(String.valueOf(obj.get("equipId")));
                jgRelationEquip.setNameChangeRegistrationId(String.valueOf(jgChangeRegistrationName.getSequenceNbr()));
                jgRelationEquip.setIsInvalid("0");
                jgRelationEquip.setCreateDate(jgChangeRegistrationName.getCreateDate());
                jgRelationEquip.setCreateUserId(reginParams.getUserModel().getUserId());
                jgRelationEquip.setCreateUserName(reginParams.getUserModel().getRealName());
                equipList.add(jgRelationEquip);

                JgRegistrationHistory jgRegistrationHistory = new JgRegistrationHistory();
                jgRegistrationHistory.setCreateUserId(reginParams.getUserModel().getUserId());
                jgRegistrationHistory.setCreateDate(jgChangeRegistrationName.getCreateDate());
                jgRegistrationHistory.setChangeData(JSON.toJSONString(jgChangeRegistrationName));
                jgRegistrationHistory.setOldData(JSON.toJSONString(jgChangeRegistrationName));
                jgRegistrationHistory.setRegistrationClass("使用单位名称变更登记");
                jgRegistrationHistory.setStatus("new");
                jgRegistrationHistory.setEquId(String.valueOf(obj.get("equipId")));
                jgRegistrationHistory.setSupervisoryCode(String.valueOf(obj.get("supervisoryCode")));
                jgRegistrationHistory.setUseRegistrationCode(String.valueOf(obj.get("useOrgCode")));
                jgRegistrationHistory.setCurrentDocumentId(jgChangeRegistrationName.getApplyNo());
                list.add(jgRegistrationHistory);

            });
            jgChangeRegistrationNameEqService.saveBatch(equipList);
            jgRegistrationHistoryService.saveBatch(list);
            if (submit) {
                // 查询下节点任务
                getNext(roleListSecond, jgChangeRegistrationName.getInstanceId(), taskName);
                String join = String.join(",", roleListSecond);
                if (!ObjectUtils.isEmpty(jgChangeRegistrationName.getInstanceStatus())) {
                    jgChangeRegistrationName.setInstanceStatus(jgChangeRegistrationName.getInstanceStatus() + "," + join);
                } else {
                    jgChangeRegistrationName.setInstanceStatus(String.join(",", roleListSecond));
                }
                jgChangeRegistrationName.setPromoter(RequestContext.getExeUserId());
                jgChangeRegistrationName.setNextExecutorIds(String.join(",", roleListSecond));
                jgChangeRegistrationName.setAuditStatus(String.valueOf(WorkFlowStatusEnum.UNIT_RENAME_RECEIVE.getPass()));
                this.updateById(jgChangeRegistrationName);
            }
        } else {
            JgChangeRegistrationName bean = new JgChangeRegistrationName();
            BeanUtils.copyProperties(jgChangeRegistrationNameDto, bean);
            this.updateById(bean);
        }
        return jgChangeRegistrationNameDto;
    }


    public boolean submit(JgChangeRegistrationName 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;
        }
    }

    private void convertField(JgChangeRegistrationNameDto model) {
        // 处理文件
        if (!ValidationUtil.isEmpty(model.getChangeCertificateList())) {
            model.setChangeCertificate(JSON.toJSONString(model.getChangeCertificateList()));
        }
        String receiveOrgId = model.getReceiveOrgCode();
        if (!ObjectUtils.isEmpty(receiveOrgId)) {
            String[] receiveOrgIdList = receiveOrgId.split("_");
            if (receiveOrgIdList.length > 1) {
                model.setReceiveOrgCode(receiveOrgIdList[0]);
                model.setReceiveOrgName(receiveOrgIdList[1]);
            }
        }
    }


    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());
                }
            }
        }
    }

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


    public void revocation(String instanceId) {
        ReginParams reginParams = JSONObject.parseObject(redisUtils.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken())).toString(), ReginParams.class);
        String taskCode = FlowStatusEnum.TO_BE_FINISHED.getName();
        JgChangeRegistrationName jgChangeRegistrationName = new JgChangeRegistrationName();
        LambdaQueryWrapper<JgChangeRegistrationName> lambda = new QueryWrapper<JgChangeRegistrationName>().lambda();
        lambda.eq(JgChangeRegistrationName::getInstanceId, instanceId);
        ArrayList<String> roleList = new ArrayList<>();
        try {
            workFlowFeignService.rollBack(instanceId);
            JSONObject taskNoAuth = workFlowFeignService.getTaskNoAuth(instanceId);
            JSONObject nextTask = JSON.parseObject(JSON.toJSONString(taskNoAuth.get("data")));
            if (!ObjectUtils.isEmpty(taskNoAuth.get("data"))) {
                String nextTaskId = nextTask.getString("id");
                FeignClientResult<JSONObject> nodeInfo = workFlowFeignService.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)) {
            jgChangeRegistrationName.setAuditStatus(WorkFlowStatusEnum.getMessage(taskCode).getRollBack());
        }
        String join = String.join(",", roleList);
        jgChangeRegistrationName.setPromoter(reginParams.getUserModel().getUserId());
        jgChangeRegistrationName.setNextExecutorIds(join);
        this.update(jgChangeRegistrationName, lambda);
    }


    public void flowExecute(Long id, String instanceId, String operate, String comment) {
        try {
            JSONObject task = workFlowFeignService.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 = JSON.parseObject(redisUtils.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken())).toString(), ReginParams.class);
        String role = "";
        String taskCode = FlowStatusEnum.TO_BE_FINISHED.getName();
        ArrayList<String> roleList = new ArrayList<>();
        JgChangeRegistrationName jgChangeRegistrationName = this.getBaseMapper().selectById(sequenceNbr);
        try {
            // 查询下节点任务
            JSONObject taskNoAuth = workFlowFeignService.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 = workFlowFeignService.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);
            jgChangeRegistrationName.setNextExecutorIds(role);
            jgChangeRegistrationName.setPromoter(reginParams.getUserModel().getUserId());
            jgChangeRegistrationName.setInstanceId(instanceId);
            if (!ObjectUtils.isEmpty(jgChangeRegistrationName.getInstanceStatus())) {
                jgChangeRegistrationName.setInstanceStatus(jgChangeRegistrationName.getInstanceStatus() + "," + role);
            } else {
                jgChangeRegistrationName.setInstanceStatus(role);
            }
            if ("0".equals(operate)) {
                // 通过操作
                jgChangeRegistrationName.setAuditStatus(WorkFlowStatusEnum.getMessage(taskCode).getPass());
            } else {
                // 驳回操作
                jgChangeRegistrationName.setAuditStatus(WorkFlowStatusEnum.getMessage(taskCode).getReject());
                jgChangeRegistrationName.setPromoter(null);
            }
        } else {
            jgChangeRegistrationName.setAuditStatus(FlowStatusEnum.TO_BE_FINISHED.getName());
            jgChangeRegistrationName.setAuditPassDate(new Date());
            // 修改业务信息
            updateInfoOther(jgChangeRegistrationName);
        }
        this.getBaseMapper().updateById(jgChangeRegistrationName);

    }


    public void updateInfoOther(JgChangeRegistrationName jgChangeRegistrationName) {
        LambdaQueryWrapper<JgChangeRegistrationNameEq> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(JgChangeRegistrationNameEq::getNameChangeRegistrationId, jgChangeRegistrationName.getSequenceNbr());
        List<String> collect = jgChangeRegistrationNameEqService.list(wrapper).stream().map(JgChangeRegistrationNameEq::getEquId).collect(Collectors.toList());
        if (CollUtil.isNotEmpty(collect)) {
            LambdaUpdateWrapper<JgChangeRegistrationReformEq> updateWrapper1 = new LambdaUpdateWrapper<>();
            updateWrapper1.in(JgChangeRegistrationReformEq::getEquId, collect);
            updateWrapper1.ne(JgChangeRegistrationReformEq::getEquipTransferId, jgChangeRegistrationName.getSequenceNbr());
            JgChangeRegistrationReformEq jgChangeRegistrationReformEq = new JgChangeRegistrationReformEq();
            jgChangeRegistrationReformEq.setIsInvalid(Boolean.TRUE);
            jgChangeRegistrationReformEqMapper.update(jgChangeRegistrationReformEq, updateWrapper1);

            LambdaUpdateWrapper<JgChangeRegistrationTransferEq> updateWrapper2 = new LambdaUpdateWrapper<>();
            updateWrapper2.in(JgChangeRegistrationTransferEq::getEquId, collect);
            updateWrapper2.ne(JgChangeRegistrationTransferEq::getEquipTransferId, jgChangeRegistrationName.getSequenceNbr());
            JgChangeRegistrationTransferEq jgChangeRegistrationTransferEq = new JgChangeRegistrationTransferEq();
            jgChangeRegistrationReformEq.setIsInvalid(Boolean.TRUE);
            jgChangeRegistrationTransferEqMapper.update(jgChangeRegistrationTransferEq, updateWrapper2);

            LambdaUpdateWrapper<JgUseRegistrationEq> updateWrapper3 = new LambdaUpdateWrapper<>();
            updateWrapper3.in(JgUseRegistrationEq::getEquId, collect);
            updateWrapper3.ne(JgUseRegistrationEq::getEquipTransferId, jgChangeRegistrationName.getSequenceNbr());
            JgUseRegistrationEq jgUseRegistrationEq = new JgUseRegistrationEq();
            jgUseRegistrationEq.setIsInvalid(Boolean.TRUE);
            jgUseRegistrationEqMapper.update(jgUseRegistrationEq, updateWrapper3);

            LambdaUpdateWrapper<JgChangeRegistrationUnitEq> updateWrapper4 = new LambdaUpdateWrapper<>();
            updateWrapper4.in(JgChangeRegistrationUnitEq::getEquId, collect);
            updateWrapper4.ne(JgChangeRegistrationUnitEq::getUnitChangeRegistrationId, jgChangeRegistrationName.getSequenceNbr());
            JgChangeRegistrationUnitEq jgChangeRegistrationUnitEq = new JgChangeRegistrationUnitEq();
            jgChangeRegistrationUnitEq.setIsInvalid("1");
            jgChangeRegistrationUnitEqMapper.update(jgChangeRegistrationUnitEq, updateWrapper4);

            LambdaUpdateWrapper<JgChangeRegistrationNameEq> updateWrapper5 = new LambdaUpdateWrapper<>();
            updateWrapper5.in(JgChangeRegistrationNameEq::getEquId, collect);
            updateWrapper5.ne(JgChangeRegistrationNameEq::getNameChangeRegistrationId, jgChangeRegistrationName.getSequenceNbr());
            JgChangeRegistrationNameEq jgChangeRegistrationNameEq = new JgChangeRegistrationNameEq();
            jgChangeRegistrationNameEq.setIsInvalid("1");
            jgChangeRegistrationNameEqMapper.update(jgChangeRegistrationNameEq, updateWrapper5);
        }

        LambdaUpdateWrapper<RegUnitInfo> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(RegUnitInfo::getUnitCode, jgChangeRegistrationName.getUseUnitCreditCode());
        RegUnitInfo regUnitInfo = new RegUnitInfo();
        regUnitInfo.setName(jgChangeRegistrationName.getNewUseUnitName());
        regUnitInfoMapper.update(regUnitInfo, updateWrapper);

        LambdaUpdateWrapper<TzBaseEnterpriseInfo> updateWrapper2 = new LambdaUpdateWrapper<>();
        updateWrapper2.eq(TzBaseEnterpriseInfo::getUseCode, jgChangeRegistrationName.getUseUnitCreditCode());
        TzBaseEnterpriseInfo tzBaseEnterpriseInfo = new TzBaseEnterpriseInfo();
        regUnitInfo.setName(jgChangeRegistrationName.getNewUseUnitName());
        tzBaseEnterpriseInfoMapper.update(tzBaseEnterpriseInfo, updateWrapper2);

        // TODO: 2023/12/25 修改平台机构名称
    }

    public Map<String, Object> queryBySequenceNbr(Long sequenceNbr) {
        ReginParams reginParams = JSON.parseObject(redisUtils.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken())).toString(), ReginParams.class);
        Map<String, Object> resultMap = accessFeignService.getData(reginParams.getCompany().getCompanyCode()).getResult();
        String unitName = String.valueOf(resultMap.get("unitName"));
        JgChangeRegistrationName jgChangeRegistrationName = new JgChangeRegistrationName();
        Map<String, Object> dtoMap = new HashMap<>();
        Map<String, Object> map = new HashMap<>();
        if (!Objects.isNull(sequenceNbr)) {
            jgChangeRegistrationName = this.baseMapper.selectById(sequenceNbr);
            jgChangeRegistrationName.setReceiveOrgCode(jgChangeRegistrationName.getReceiveOrgCode() + "_" + jgChangeRegistrationName.getReceiveOrgName());
        } else {
            jgChangeRegistrationName.setUseUnitCreditCode(reginParams.getCompany().getCompanyCode());
            jgChangeRegistrationName.setNewUseUnitName(unitName);
            jgChangeRegistrationName.setUseUnitName(reginParams.getCompany().getCompanyName());
        }
        BeanUtil.copyProperties(jgChangeRegistrationName, dtoMap);
        dtoMap.put("changeCertificateList", JSON.parseArray(jgChangeRegistrationName.getChangeCertificate()));
        map.put("jgRegistrationInfo", dtoMap);
        return map;
    }

    public Page<Map<String, Object>> getList(JgChangeRegistrationNameDto dto, Page<Map<String, Object>> page, List<String> roleIds) {
        ReginParams reginParams = JSON.parseObject(redisUtils.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken())).toString(), ReginParams.class);
        String orgCode = reginParams.getCompany().getCompanyCode();
        if (org.apache.commons.lang3.StringUtils.isNotBlank(dto.getReceiveOrgCode())) {
            String[] receiveOrgIdList = dto.getReceiveOrgCode().split("_");
            if (receiveOrgIdList.length > 1) {
                dto.setReceiveOrgCode(receiveOrgIdList[0]);
            }
        }
        Page<Map<String, Object>> listPage = this.baseMapper.getListPage(page, dto, roleIds, orgCode);
        return listPage;
    }
}