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.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
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.utils.RedisKey;
import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;
import com.yeejoin.amos.boot.module.jg.api.dto.TaskMessageDto;
import com.yeejoin.amos.boot.module.jg.api.dto.TaskModelDto;
import com.yeejoin.amos.boot.module.jg.api.dto.WorkflowResultDto;
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.JgChangeRegistrationNameEqMapper;
import com.yeejoin.amos.boot.module.jg.api.mapper.JgChangeRegistrationReformEqMapper;
import com.yeejoin.amos.boot.module.jg.api.mapper.JgChangeRegistrationTransferEqMapper;
import com.yeejoin.amos.boot.module.jg.api.mapper.JgChangeRegistrationTransferMapper;
import com.yeejoin.amos.boot.module.jg.api.mapper.JgChangeRegistrationUnitEqMapper;
import com.yeejoin.amos.boot.module.jg.api.mapper.JgUseRegistrationEqMapper;
import com.yeejoin.amos.boot.module.jg.api.service.IJgChangeRegistrationTransferEqService;
import com.yeejoin.amos.boot.module.jg.api.service.IJgChangeRegistrationTransferService;
import com.yeejoin.amos.boot.module.jg.api.dto.JgChangeRegistrationTransferDto;
import com.yeejoin.amos.boot.module.jg.api.service.IJgRegistrationHistoryService;
import com.yeejoin.amos.boot.module.jg.biz.feign.TzsServiceFeignClient;
import com.yeejoin.amos.boot.module.jg.biz.service.ICmWorkflowService;
import com.yeejoin.amos.boot.module.jg.biz.service.ICommonService;
import com.yeejoin.amos.boot.module.jg.biz.service.IIdxBizJgUseInfoService;
import com.yeejoin.amos.boot.module.jg.flc.api.fegin.WorkFlowFeignService;
import com.yeejoin.amos.boot.module.ymt.api.entity.EquipmentCategory;
import com.yeejoin.amos.boot.module.ymt.api.entity.IdxBizJgFactoryInfo;
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.enums.ApplicationFormTypeEnum;
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.feign.systemctl.model.TaskV2Model;
import com.yeejoin.amos.feign.workflow.model.*;
import org.apache.commons.collections.CollectionUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.util.ObjectUtils;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.foundation.utils.Bean;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.rdbms.service.BaseService;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 移装变更登记登记服务实现类
 *
 * @author system_generator
 * @date 2023-12-20
 */
@Service
public class JgChangeRegistrationTransferServiceImpl extends BaseService<JgChangeRegistrationTransferDto, JgChangeRegistrationTransfer, JgChangeRegistrationTransferMapper> implements IJgChangeRegistrationTransferService {
    private static final String PROCESS_DEFINITION_KEY = "changeRegistrationTransfer";
    private static final String TABLE_PAGE_ID = "changeRegistrationTransfer";

    @Autowired
    private IJgChangeRegistrationTransferEqService jgChangeRegistrationTransferEqService;

    @Autowired
    private IJgRegistrationHistoryService jgRegistrationHistoryService;
    @Autowired
    private IIdxBizJgUseInfoService useInfoService;
    @Autowired
    private IdxBizJgUseInfoServiceImpl idxBizJgUseInfoService;
    @Autowired
    private IdxBizJgRegisterInfoServiceImpl idxBizJgRegisterInfoService;
    @Autowired
    private IdxBizJgFactoryInfoServiceImpl idxBizJgFactoryInfoService;


    @Autowired
    RestHighLevelClient restHighLevelClient;

    @Autowired
    WorkFlowFeignService workFlowFeginService;

    @Autowired
    RedisUtils redisUtils;

    //改造登记关系表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 IdxBizJgOtherInfoMapper idxBizJgOtherInfoMapper;
    @Autowired
    private IdxBizJgRegisterInfoMapper idxBizJgRegisterInfoMapper;

    @Autowired
    ICommonService iCommonService;

    @Autowired
    TzsServiceFeignClient tzsServiceFeignClient;

    @Autowired
    ICmWorkflowService icmWorkflowService;
    @Autowired
    CommonServiceImpl commonService;

    /**
     * 新增移装变更登记
     *
     * @param submitType
     * @param map
     * @return
     */
    public List<JgChangeRegistrationTransfer> createTransfer(String submitType, JSONObject map, ReginParams reginParams) {

        Map<String, Object> tableData = (Map<String, Object>) map.get(TABLE_PAGE_ID);
        if (ValidationUtil.isEmpty(tableData)) {
            throw new BadRequest("参数校验失败.");
        }
        String equIds = (String) tableData.get("record");
        if (ValidationUtil.isEmpty(equIds)) {
            throw new BadRequest("参数校验失败.");
        }
        CompanyBo company = reginParams.getCompany();
        String sequenceNbr = (String) map.get("sequenceNbr");
        String equId = (String) tableData.get("record");
        String receiveOrgCode = (String) tableData.get("receiveOrgCode");
        String receiveOrgName = "";
        String supervisoryCode = "";

        //移装变更数据
        JgChangeRegistrationTransfer oldTransfer = new JgChangeRegistrationTransfer();
        //移装变更设备关联数据
        JgChangeRegistrationTransferEq oldTransferEq = new JgChangeRegistrationTransferEq();
        //移装变更历史记录表
        JgRegistrationHistory oldHistory = new JgRegistrationHistory();
        //设备使用信息
        IdxBizJgUseInfo useInfo = new IdxBizJgUseInfo();

        if (!ValidationUtil.isEmpty(receiveOrgCode)) {
            String[] receiveOrgCodeList = receiveOrgCode.split("_");
            if (receiveOrgCodeList.length > 1) {
                receiveOrgCode = receiveOrgCodeList[0];
                receiveOrgName = receiveOrgCodeList[1];
            }
        }

        //有sequenceNbr代表修改数据
        if (!ValidationUtil.isEmpty(sequenceNbr)) {
            //查询移装变更记录
            oldTransfer = this.getById(sequenceNbr);
            //查询关系表
            oldTransferEq = jgChangeRegistrationTransferEqService.getDetailByEquipTransferId(sequenceNbr);
            //查询历史记录表
            if (!ValidationUtil.isEmpty(oldTransferEq)) {
                oldHistory = jgRegistrationHistoryService.getDteailByRecord(oldTransferEq.getEquId(), oldTransfer.getApplyNo());
                useInfo = idxBizJgUseInfoService.getOneData(oldTransferEq.getEquId());
            }
        } else {
            //查询申请单号
            ResponseModel<List<String>> result = tzsServiceFeignClient.applicationFormCode(ApplicationFormTypeEnum.getCode.get(String.valueOf(tableData.get("businessCode"))), 1);
            if (!result.getResult().isEmpty()) {
                //申请编号
                oldTransfer.setApplyNo(result.getResult().get(0));
            } else {
                throw new BadRequest("申请单编号生成失败,请稍后重试!");
            }
        }

        //登记类别
        oldTransfer.setRegType("移装登记");
        //注册登记日期
        oldTransfer.setRegDate(new Date());
        //使用机构
        oldTransfer.setUseUnitCreditCode(company.getCompanyCode());
        oldTransfer.setUseUnitName(company.getCompanyName());
        //录入单位统一信用代码
        oldTransfer.setInputUnitNo(company.getCompanyCode());
        // 创建人ID
        oldTransfer.setCreateUserId(reginParams.getUserModel().getUserId());

        //登记机构代码
        //登记机构公司代码
        if (!ValidationUtil.isEmpty(receiveOrgCode)) {
            oldTransfer.setReceiveOrgCode(receiveOrgCode);
            oldTransfer.setReceiveCompanyCode(receiveOrgCode);
        } else {
            oldTransfer.setReceiveOrgCode("610000");
            oldTransfer.setReceiveCompanyCode("610000");
        }
        //登记机构
        if (!ValidationUtil.isEmpty(receiveOrgName)) {
            oldTransfer.setReceiveOrgName(receiveOrgName);
        }
        //办理状态
        oldTransfer.setAuditStatus(WorkFlowStatusEnum.TRANSFER_SUBMIT.getPass());
        oldTransfer.setStatus(WorkFlowStatusEnum.TRANSFER_SUBMIT.getPass());

        //es种查询设备信息
        SearchRequest request = new SearchRequest();
        request.indices("idx_biz_view_jg_all");
        SearchSourceBuilder builder = new SearchSourceBuilder();
        builder.trackTotalHits(true);
        BoolQueryBuilder boolMust = QueryBuilders.boolQuery();
        boolMust.must(QueryBuilders.matchPhraseQuery("SEQUENCE_NBR", equId));
        builder.query(boolMust);
        request.source(builder);
        try {
            //ES中的数据
            SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
            for (org.elasticsearch.search.SearchHit hit : response.getHits().getHits()) {
                System.out.println(hit);
                JSONObject jsonObject = (JSONObject) JSONObject.toJSON(hit);
                JSONObject dto2 = jsonObject.getJSONObject("sourceAsMap");

                //设备监管码
                if (!ValidationUtil.isEmpty(dto2.get("SUPERVISORY_CODE"))) {
                    supervisoryCode = (String) dto2.get("SUPERVISORY_CODE");
                    oldTransfer.setSupervisoryCode(supervisoryCode);
                } else {
                    supervisoryCode = idxBizJgOtherInfoMapper.getSupervisoryCodeByEquipmentCode(equId);
                    if (!ValidationUtil.isEmpty(supervisoryCode)) {
                        oldTransfer.setSupervisoryCode(supervisoryCode);
                    }
                }
                //使用登记编号
                if (!ValidationUtil.isEmpty(dto2.get("USE_ORG_CODE"))) {
                    oldTransfer.setUseRegistrationCode((String) dto2.get("USE_ORG_CODE"));
                } else {
                    //使用登记编号
                    oldTransfer.setUseRegistrationCode(idxBizJgRegisterInfoMapper.getUseOrgCodeByEquip(equId));
                }

            }

            //保存【移装变更登记】基本信息
            if (!ValidationUtil.isEmpty(oldTransfer)) {
                this.saveOrUpdate(oldTransfer);
            }

            //保存设备关联表
            oldTransferEq.setEquipTransferId(oldTransfer.getSequenceNbr().toString());
            oldTransferEq.setEquId(equId);
            jgChangeRegistrationTransferEqService.saveOrUpdateTransferEqData(oldTransferEq);

            //新增历史记录表
            //使用登记证编号
            oldHistory.setUseRegistrationCode(oldTransfer.getUseRegistrationCode());
            oldHistory.setRegistrationClass("移装登记");
            //保存变更新数据
            oldHistory.setChangeData(JSON.toJSONString(tableData));
            //保存变更旧数据
            oldHistory.setOldData(JSON.toJSONString(useInfo));
            //设备监管码
            oldHistory.setSupervisoryCode(supervisoryCode);
            oldHistory.setEquId(equId);
            oldHistory.setCurrentDocumentId(oldTransfer.getApplyNo());
            oldHistory.setStatus("new");
            jgRegistrationHistoryService.saveOrUpdateHistoryData(oldHistory);

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        //发起流程
        if ("1".equals(submitType)) {
            String instanceId = "";

            if (!ValidationUtil.isEmpty(oldTransfer.getSequenceNbr()) && !ValidationUtil.isEmpty(oldTransfer.getInstanceId())) {
                this.flowExecute(oldTransfer.getSequenceNbr(), oldTransfer.getInstanceId(), "0", "");
            } else {
                // 如果是新启动的流程开启自动访问
                String equipListName = this.getBaseMapper().getEquiplistNameByEquiplist(Optional.ofNullable(tableData.get("equList").toString()).orElse(" "));
                oldTransfer.setAuditStatus(WorkFlowStatusEnum.TRANSFER_RECEIVE.getPass());
                oldTransfer.setStatus(WorkFlowStatusEnum.TRANSFER_RECEIVE.getPass());
                oldTransfer.setEquipListName(equipListName);
                oldTransfer.setCreateUserId(reginParams.getUserModel().getUserId());
                oldTransfer.setCreateUserName(reginParams.getUserModel().getRealName());
                oldTransfer.setCreateUserCompanyName(reginParams.getCompany().getCompanyName());
                //启动流程
                WorkflowResultDto workflowResult = this.startWorkFlork(oldTransfer.getReceiveOrgCode());

                this.updateExecuteIds(instanceId, oldTransfer, "startWorkfow", workflowResult);
                //删除旧的代办
                commonService.deleteTaskModel(oldTransfer.getSequenceNbr().toString());
                //生成代办
                this.createToDoTask(Arrays.asList(workflowResult), oldTransfer, submitType);
            }
        }else {
            List<TaskModelDto> modelDtos = new ArrayList<>();
            TaskModelDto dto = new TaskModelDto();
            dto.setModel(oldTransfer);
            dto.setTaskContent(this.getSummaryInfo(oldTransfer));
            dto.setTaskCode(oldTransfer.getApplyNo());
            dto.setTaskType(BusinessTypeEnum.JG_CHANGE_REGISTRATION.getCode());
            dto.setRelationId(oldTransfer.getSequenceNbr() + "");
            modelDtos.add(dto);
            commonService.buildTaskModel(modelDtos);
        }
        return  Collections.singletonList(oldTransfer);
    }

    /**
     * 修改移装变更登记
     *
     * @param map
     * @return
     */
    public List<JgChangeRegistrationTransfer> updateTransfer(String submitType, JSONObject map, ReginParams reginParams) {
        return this.createTransfer(submitType, map, reginParams);
    }

    /**
     * 执行流程
     *
     * @param id
     * @param instanceId
     * @param operate
     * @param comment
     */
    public void flowExecute(Long id, String instanceId, String operate, String comment) {
        WorkflowResultDto workflowResult = new WorkflowResultDto();
        JgChangeRegistrationTransfer transfer = this.getById(id);

        String taskId = transfer.getNextTaskId();
        //组装信息
        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);
        //下一节点执行人单位（下节点接收机构code）
        dto.setNextExecuteUserCompanyCode(this.getNextUserOrgCode(operate, transfer));
        if (!ObjectUtils.isEmpty(transfer) && (transfer.getStatus().equals(WorkFlowStatusEnum.TRANSFER_SUBMIT.getRollBack()) || transfer.getStatus().equals(WorkFlowStatusEnum.TRANSFER_SUBMIT.getReject()))) {
            map.put("approvalStatus", "提交");
        }
        //执行流程
        ProcessTaskDTO complete = icmWorkflowService.complete(taskId, dto);
        workflowResult = commonService.buildWorkFlowInfo(Collections.singletonList(complete)).get(0);
        // 更新下一步执行人
        this.updateExecuteIds(instanceId, transfer, operate, workflowResult);

    }

    /**
     * 流程撤回
     *
     * @param instanceId
     */
    public void revocation(String instanceId) {
        ReginParams reginParams = JSONObject.parseObject(redisUtils.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken())).toString(), ReginParams.class);

        JgChangeRegistrationTransfer jgTransfer = new JgChangeRegistrationTransfer();
        LambdaQueryWrapper<JgChangeRegistrationTransfer> lambda = new QueryWrapper<JgChangeRegistrationTransfer>().lambda();
        lambda.eq(JgChangeRegistrationTransfer::getInstanceId, instanceId);
        jgTransfer = this.getOne(lambda);
        ProcessTaskDTO processTask = icmWorkflowService.rollBack(instanceId);
        WorkflowResultDto workflowResult = commonService.buildWorkFlowInfo(Collections.singletonList(processTask)).get(0);
        String taskCode = "";
        String role = "";
        if (!ValidationUtil.isEmpty(workflowResult)) {
            taskCode = Optional.ofNullable(workflowResult.getNextTaskCode()).orElse("");
            role = Optional.ofNullable(workflowResult.getNextExecutorRoleIds()).orElse("");
            jgTransfer.setNextTaskId(workflowResult.getNextTaskId());
            // 更新下一步可执行人
            jgTransfer.setNextExecuteUserIds(workflowResult.getNextExecutorUserIds());
        }
        if (!ObjectUtils.isEmpty(taskCode)) {
            jgTransfer.setAuditStatus(WorkFlowStatusEnum.getMessage(taskCode).getRollBack());
            jgTransfer.setStatus(WorkFlowStatusEnum.getMessage(taskCode).getRollBack());
        }
        jgTransfer.setPromoter(reginParams.getUserModel().getUserId());
        jgTransfer.setNextExecutorIds(role);
        this.updateById(jgTransfer);
        //待办 撤回
        JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(jgTransfer));
        jsonObject.put("flowStatus", commonService.getDictionaryCodeByName(jgTransfer.getAuditStatus()));
        jsonObject.put("flowStatusLabel", jgTransfer.getAuditStatus());
        jsonObject.put("nextTaskId", jgTransfer.getNextTaskId());
        jsonObject.put("nextExecuteUser", jgTransfer.getNextExecutorIds());
        jsonObject.put("taskType", BusinessTypeEnum.JG_CHANGE_REGISTRATION.getCode());
        // 判断撤回后当前的节点，如果当前节点为提交节点则页面可编辑
        jsonObject.put("pageType",this.getPageTypeByCurrentNode(jgTransfer.getAuditStatus()));
        commonService.rollbackTask(instanceId, jsonObject);
    }


    /**
     * 批量删除
     *
     * @param sequenceNbrs
     * @return
     */
    public boolean deleteBatchBySequenceNbrs(Long[] sequenceNbrs) {
        if (Objects.isNull(sequenceNbrs) || sequenceNbrs.length == 0) {
            return false;
        }
        try {
            //删除移装变更信息
            JgChangeRegistrationTransfer transfer = new JgChangeRegistrationTransfer();
            transfer.setIsDelete(true);
            LambdaQueryWrapper<JgChangeRegistrationTransfer> transferWapper = new QueryWrapper<JgChangeRegistrationTransfer>().lambda();
            transferWapper.in(JgChangeRegistrationTransfer::getSequenceNbr, Arrays.asList(sequenceNbrs));
            this.update(transfer, transferWapper);
            //删除关联表信息
            JgChangeRegistrationTransferEq eq = new JgChangeRegistrationTransferEq();
            transfer.setIsDelete(true);
            LambdaQueryWrapper<JgChangeRegistrationTransferEq> eqWapper = new QueryWrapper<JgChangeRegistrationTransferEq>().lambda();
            eqWapper.in(JgChangeRegistrationTransferEq::getEquipTransferId, Arrays.asList(sequenceNbrs));
            jgChangeRegistrationTransferEqService.updateDate(eq, eqWapper);
            //删除历史表
            JgRegistrationHistory history = new JgRegistrationHistory();
            history.setIsDelete(true);
            List<JgChangeRegistrationTransferDto> transferDtos = this.queryBatchSeq(Arrays.asList(sequenceNbrs));
            if (!ValidationUtil.isEmpty(transferDtos)) {
                List<String> applyNos = transferDtos.stream().map(item -> item.getApplyNo()).collect(Collectors.toList());
                if (!ValidationUtil.isEmpty(applyNos)) {
                    LambdaQueryWrapper<JgRegistrationHistory> historyWapper = new QueryWrapper<JgRegistrationHistory>().lambda();
                    historyWapper.in(JgRegistrationHistory::getCurrentDocumentId, applyNos);
                    jgRegistrationHistoryService.updateDate(history, historyWapper);
                }
            }

        } catch (Exception e) {
            return false;
        }
        return true;
    }

    /**
     * 根据移装变更记录sequenceNbr查询详情
     *
     * @param sequenceNbr 变更记录sequenceNbr
     * @return
     */
    public Map<String, Map<String, Object>> getTransferDetail(String sequenceNbr, String equipId) {
        Map<String, Map<String, Object>> pageDataMap = new HashMap<>();
        Map<String, Object> resultDataMap = new HashMap<>();
        //移装变更详情
        JgChangeRegistrationTransfer transferById = this.getById(sequenceNbr);
        if (!ValidationUtil.isEmpty(transferById)) {
            Map<String, Object> transferToMap = Bean.BeantoMap(transferById);
            resultDataMap.putAll(transferToMap);
        }

        //查询设备详情
        if (ValidationUtil.isEmpty(equipId)) {
            equipId = jgChangeRegistrationTransferEqMapper.getEquipIdByEquipTransferId(sequenceNbr);
        }

        Map<String, Object> equipDetailMap = idxBizJgRegisterInfoService.getDetailFieldCamelCaseByRecord(equipId);
        resultDataMap.putAll(equipDetailMap);

        //判断流程是否执行完成，
        // 1、未执行完成时查询历史表
        // 2、执行完成后查询使用信息表
        if (!ValidationUtil.equals(FlowStatusEnum.TO_BE_FINISHED.getName(), transferById.getStatus())) {
            JgRegistrationHistory historyData = jgRegistrationHistoryService.getDteailByRecord(equipId, transferById.getApplyNo());
            if (!ValidationUtil.isEmpty(historyData)) {
                JSONObject newPosition = JSON.parseObject(historyData.getChangeData());
                String record = newPosition.getString("record");
                String receiveOrgCode = newPosition.getString("receiveOrgCode");
                String equCode = newPosition.getString("equCode");
                String province = newPosition.getString("province");
                String city = newPosition.getString("city");
                String county = newPosition.getString("county");
                String street = newPosition.getString("street");
                String address = newPosition.getString("address");
                String longitudeLatitude = newPosition.getString("longitudeLatitude");
                if (!ObjectUtils.isEmpty(record)) {
                    resultDataMap.put("record", record);
                }
                if (!ObjectUtils.isEmpty(equCode)) {
                    resultDataMap.put("equCode", equCode);
                }
                if (!ObjectUtils.isEmpty(receiveOrgCode)) {
                    resultDataMap.put("receiveOrgCode", receiveOrgCode);
                }

                // 分割省市区街道字段
                if (!ObjectUtils.isEmpty(province)) {
                    resultDataMap.put("province", province);
                }
                if (!ObjectUtils.isEmpty(city)) {
                    resultDataMap.put("city", city);
                }
                if (!ObjectUtils.isEmpty(county)) {
                    resultDataMap.put("county", county);
                }
                if (!ObjectUtils.isEmpty(street)) {
                    resultDataMap.put("street", street);
                }
                if (!ObjectUtils.isEmpty(address)) {
                    resultDataMap.put("address", address);
                }
                if (!ObjectUtils.isEmpty(longitudeLatitude)) {
                    resultDataMap.put("longitudeLatitude", JSON.parseObject(longitudeLatitude));
                }
            }
        } else {
            //设备注册信息
            IdxBizJgRegisterInfo registerInfo = idxBizJgRegisterInfoService.getOne(new QueryWrapper<IdxBizJgRegisterInfo>().eq("RECORD", equipId));
            //使用信息详情
            IdxBizJgUseInfo useInfoByRecord = idxBizJgUseInfoService.getOneData(equipId);

            if (!ValidationUtil.isEmpty(useInfoByRecord)) {
                Map<String, Object> useInfoToMap = Bean.BeantoMap(useInfoByRecord);
                String record = useInfoByRecord.getRecord();
                resultDataMap.put("record", record);
                resultDataMap.putAll(useInfoToMap);
                // 省市区街道字段
                resultDataMap.put("province", useInfoByRecord.getProvince() + "_" + useInfoByRecord.getProvinceName());
                resultDataMap.put("city", useInfoByRecord.getCity() + "_" + useInfoByRecord.getCityName());
                resultDataMap.put("county", useInfoByRecord.getCounty() + "_" + useInfoByRecord.getCountyName());
                resultDataMap.put("street", useInfoByRecord.getFactoryUseSiteStreet() + "_" + useInfoByRecord.getStreetName());
                resultDataMap.put("address", useInfoByRecord.getAddress());
                if (!ObjectUtils.isEmpty(useInfoByRecord.getLongitudeLatitude())) {
                    resultDataMap.put("longitudeLatitude", JSON.parseObject(useInfoByRecord.getLongitudeLatitude()));
                }
            }
            if (!ValidationUtil.isEmpty(registerInfo)) {
                resultDataMap.put("equCode", registerInfo.getEquCode());
            }
            resultDataMap.put("receiveOrgCode", transferById.getReceiveOrgCode() + "_" + transferById.getReceiveOrgName());
        }

        if (!resultDataMap.isEmpty()) {
            pageDataMap.put(TABLE_PAGE_ID, resultDataMap);
        }
        return pageDataMap;
    }

    /**
     * 分页查询
     *
     * @param page
     * @param params
     * @return
     */
    public Page<Map<String, Object>> queryListForPage(Page<Map<String, Object>> page, JgChangeRegistrationTransferDto params, String type) {
        Page<Map<String, Object>> listPage = this.baseMapper.getListPage(page, params, params.getRoleIds(), type);
        listPage.getRecords().stream().forEach(item -> {
            // 流程未走完时，移装地址需从 历史表中获取
            if (item.containsKey("status") && !FlowStatusEnum.TO_BE_FINISHED.getName().equals(item.get("status").toString())) {
                String fullAddress = "";
                if (item.containsKey("equipId") && item.containsKey("applyNo")) {
                    JgRegistrationHistory history = jgRegistrationHistoryService.getDteailByRecord(item.get("equipId").toString(), item.get("applyNo").toString());
                    if (!ValidationUtil.isEmpty(history)) {
                        JSONObject newPosition = JSON.parseObject(history.getChangeData());
                        String province = newPosition.getString("province");
                        String city = newPosition.getString("city");
                        String county = newPosition.getString("county");
                        String street = newPosition.getString("street");
                        String address = newPosition.getString("address");

                        // 分割省市区街道字段
                        if (!ObjectUtils.isEmpty(province)) {
                            String[] provinceList = province.split("_");
                            if (provinceList.length > 1) {
                                fullAddress += provinceList[1];
                            }
                        }
                        if (!ObjectUtils.isEmpty(city)) {
                            String[] cityList = city.split("_");
                            if (cityList.length > 1) {
                                fullAddress += cityList[1];
                            }
                        }
                        if (!ObjectUtils.isEmpty(county)) {
                            String[] countyList = county.split("_");
                            if (countyList.length > 1) {
                                fullAddress += countyList[1];
                            }
                        }
                        if (!ObjectUtils.isEmpty(street)) {
                            String[] streetList = street.split("_");
                            if (streetList.length > 1) {
                                fullAddress += streetList[1];
                            }
                        }
                        if (!ObjectUtils.isEmpty(address)) {
                            fullAddress += address;
                        }
                    }
                }
                item.put("allAddress", fullAddress);
            }
        });
        return listPage;
    }


    public void updateExecuteIds(String instanceId, JgChangeRegistrationTransfer jgChangeRegistrationTransfer, String operate, WorkflowResultDto workflowResult) {
        Boolean updateTodoAndCreate = Boolean.TRUE;
        ReginParams reginParams = JSONObject.parseObject(redisUtils.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken())).toString(), ReginParams.class);

        String taskCode = FlowStatusEnum.TO_BE_FINISHED.getName();
        if (!ObjectUtils.isEmpty(workflowResult.getNextTaskCode())) {
            taskCode = Optional.ofNullable(workflowResult.getNextTaskCode()).orElse("");
        }
        String role = Optional.ofNullable(workflowResult.getNextExecutorRoleIds()).orElse("");

        if (operate.equals("startWorkfow")) {
            role = Optional.ofNullable(workflowResult.getExecutorRoleIds()).orElse("") + "," + Optional.ofNullable(workflowResult.getNextExecutorRoleIds()).orElse("");
            operate = "0";
            instanceId = workflowResult.getInstanceId();
            updateTodoAndCreate = Boolean.FALSE;
        }

        if (!FlowStatusEnum.TO_BE_FINISHED.getName().equals(taskCode)) {
            jgChangeRegistrationTransfer.setInstanceId(instanceId);
            jgChangeRegistrationTransfer.setNextTaskId(workflowResult.getNextTaskId());
            jgChangeRegistrationTransfer.setNextExecutorIds(role);
            //更新下一步可执行人
            jgChangeRegistrationTransfer.setNextExecuteUserIds(workflowResult.getNextExecutorUserIds());

            if (!ObjectUtils.isEmpty(jgChangeRegistrationTransfer.getInstanceStatus())) {
                jgChangeRegistrationTransfer.setInstanceStatus(jgChangeRegistrationTransfer.getInstanceStatus() + "," + role);
            } else {
                jgChangeRegistrationTransfer.setInstanceStatus(role);
            }

            if ("0".equals(operate)) {
                // 通过操作
                jgChangeRegistrationTransfer.setPromoter(reginParams.getUserModel().getUserId());
                jgChangeRegistrationTransfer.setAuditStatus(WorkFlowStatusEnum.getMessage(taskCode).getPass());
                jgChangeRegistrationTransfer.setStatus(WorkFlowStatusEnum.getMessage(taskCode).getPass());
            } else {
                // 驳回操作
                jgChangeRegistrationTransfer.setAuditStatus(WorkFlowStatusEnum.getMessage(taskCode).getReject());
                jgChangeRegistrationTransfer.setStatus(WorkFlowStatusEnum.getMessage(taskCode).getReject());
                jgChangeRegistrationTransfer.setPromoter("");
            }

            if (updateTodoAndCreate) {
                // 上个代办改为已办
                HashMap<String, Object> map = new HashMap<>();
                if ("0".equals(operate)) {
                    map.put("taskStatus", FlowStatusEnum.TO_BE_FINISHED.getCode());
                    map.put("taskStatusLabel", FlowStatusEnum.TO_BE_FINISHED.getName());
                } else {
                    map.put("taskStatus", FlowStatusEnum.REJECTED.getCode());
                    map.put("taskStatusLabel", FlowStatusEnum.REJECTED.getName());
                }
                map.put("flowStatus", commonService.getDictionaryCodeByName(jgChangeRegistrationTransfer.getStatus()));
                map.put("flowStatusLabel", jgChangeRegistrationTransfer.getStatus());
                map.put("relationId", jgChangeRegistrationTransfer.getInstanceId());
                TaskV2Model taskV2Model = commonService.updateTaskModelNew(map);
                if (!ValidationUtil.isEmpty(taskV2Model)) {
                    TaskModelDto taskModelDto = new TaskModelDto();
                    BeanUtils.copyProperties(taskV2Model, taskModelDto);
                    // 创建新的代办
                    taskModelDto.setTaskName(workflowResult.getNextTaskName());
                    taskModelDto.setExecuteUserIds(workflowResult.getNextExecutorUserIds());
                    taskModelDto.setTaskStatus(FlowStatusEnum.TO_BE_PROCESSED.getCode());
                    taskModelDto.setTaskStatusLabel(FlowStatusEnum.TO_BE_PROCESSED.getName());
                    taskModelDto.setNextExecuteUser(workflowResult.getNextExecutorRoleIds());
                    taskModelDto.setTaskType(BusinessTypeEnum.JG_CHANGE_REGISTRATION.getCode());
                    taskModelDto.setTaskTypeLabel(BusinessTypeEnum.JG_CHANGE_REGISTRATION.getName());
                    taskModelDto.setRelationId(instanceId);
                    TaskMessageDto taskMessageDto = new TaskMessageDto();
                    BeanUtil.copyProperties(jgChangeRegistrationTransfer, taskMessageDto);
                    taskModelDto.setPageType(this.getPageTypeByCurrentNode(jgChangeRegistrationTransfer.getAuditStatus()));
                    taskModelDto.setModel(taskMessageDto);
                    commonService.buildTaskModel(Collections.singletonList(taskModelDto));
                }
            }

        } else {
            jgChangeRegistrationTransfer.setAuditPassDate(new Date());
            jgChangeRegistrationTransfer.setAuditStatus(FlowStatusEnum.TO_BE_FINISHED.getName());
            jgChangeRegistrationTransfer.setStatus(FlowStatusEnum.TO_BE_FINISHED.getName());
            //更新下一步可执行人
            jgChangeRegistrationTransfer.setNextExecuteUserIds("");
            //流程执行完成后，更新设备使用信息
            this.updateByFlowEnd(jgChangeRegistrationTransfer.getSequenceNbr().toString(), jgChangeRegistrationTransfer.getSupervisoryCode());
            HashMap<String, Object> map = new HashMap<>();
            map.put("taskStatus", FlowStatusEnum.TO_BE_FINISHED.getCode());
            map.put("taskStatusLabel", FlowStatusEnum.TO_BE_FINISHED.getName());
            map.put("flowStatus", FlowStatusEnum.TO_BE_FINISHED.getCode());
            map.put("flowStatusLabel", FlowStatusEnum.TO_BE_FINISHED.getName());
            map.put("relationId", jgChangeRegistrationTransfer.getInstanceId());
            map.put("model", jgChangeRegistrationTransfer);
            TaskV2Model taskV2Model = commonService.updateTaskModel(map);

        }
        this.getBaseMapper().updateById(jgChangeRegistrationTransfer);

    }

    /**
     * 流程结束后需要更新的数据
     *
     * @param sequenceNbr     移装变更单Id
     * @param supervisoryCode 监管码
     */
    public void updateByFlowEnd(String sequenceNbr, String supervisoryCode) {
        ReginParams reginParams = JSONObject.parseObject(redisUtils.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken())).toString(), ReginParams.class);
        JgChangeRegistrationTransferEq transferEq = jgChangeRegistrationTransferEqService.getDetailByEquipTransferId(sequenceNbr);
        if (!ValidationUtil.isEmpty(transferEq)) {
            JgChangeRegistrationTransfer updateData = new JgChangeRegistrationTransfer();
            updateData.setSequenceNbr(Long.valueOf(transferEq.getEquipTransferId()));
            //audit_pass_date 终审通过时间
            updateData.setAuditPassDate(new Date());
            //reg_person_id 注册登记人员ID
            updateData.setRegPersonId(reginParams.getUserModel().getUserId());
            //reg_person_name 注册登记人员
            updateData.setRegPersonName(reginParams.getUserModel().getUserName());
            //使用登记证编号
            String useRegistrationCode = this.getCode(supervisoryCode);
            if (!ValidationUtil.isEmpty(useRegistrationCode)) {
                updateData.setUseRegistrationCode(useRegistrationCode);
            }
            //补充移装变更表
            this.updateTransferByBaseInfo(updateData);
            //替换历史数据表和设备使用表
            this.replacementHistoryData(transferEq.getEquId(), sequenceNbr, useRegistrationCode);
            //更新使用注册登记证编号及ES中的信息
            this.updataRegisterInfoAndEsData(transferEq.getEquId(), useRegistrationCode);
            //修改各类告知列表，置为废弃
            this.updataInvalidStatusByHistory(transferEq.getEquId(), transferEq.getEquipTransferId());
        }
    }

    /**
     * 修改历史数据表和设备使用表
     *
     * @param record              设备Id
     * @param sequenceNbr         当前单据Id
     * @param useRegistrationCode 使用登记编号
     */
    public void replacementHistoryData(String record, String sequenceNbr, String useRegistrationCode) {
        JgChangeRegistrationTransfer transfer = this.getBaseMapper().selectById(sequenceNbr);
        if (!ValidationUtil.isEmpty(transfer)) {
            //查询修改后的新数据
            JgRegistrationHistory newData = jgRegistrationHistoryService.getDteailByRecord(record, transfer.getApplyNo());
            //查询设备旧数据
            IdxBizJgUseInfo useInfo = useInfoService.getOneData(record);

            //更新历史数据表
            newData.setStatus("history");
            if (!ValidationUtil.isEmpty(useRegistrationCode)) {
                newData.setUseRegistrationCode(useRegistrationCode);
            }
            jgRegistrationHistoryService.saveOrUpdateHistoryData(newData);

            // 更新设备移装位置使用信息
            if (!ValidationUtil.isEmpty(newData)) {
                JSONObject newPosition = JSON.parseObject(newData.getChangeData());
                String province = newPosition.getString("province");
                String city = newPosition.getString("city");
                String county = newPosition.getString("county");
                String street = newPosition.getString("street");
                String address = newPosition.getString("address");
                String longitudeLatitude = newPosition.getString("longitudeLatitude");
                // 分割省市区街道字段
                if (!ObjectUtils.isEmpty(province)) {
                    String[] provinceList = province.split("_");
                    if (provinceList.length > 1) {
                        useInfo.setProvince(provinceList[0]);
                        useInfo.setProvinceName(provinceList[1]);
                    }
                }
                if (!ObjectUtils.isEmpty(city)) {
                    String[] cityList = city.split("_");
                    if (cityList.length > 1) {
                        useInfo.setCity(cityList[0]);
                        useInfo.setCityName(cityList[1]);
                    }
                }
                if (!ObjectUtils.isEmpty(county)) {
                    String[] countyList = county.split("_");
                    if (countyList.length > 1) {
                        useInfo.setCounty(countyList[0]);
                        useInfo.setCountyName(countyList[1]);
                    }
                }
                if (!ObjectUtils.isEmpty(street)) {
                    String[] streetList = street.split("_");
                    if (streetList.length > 1) {
                        useInfo.setFactoryUseSiteStreet(streetList[0]);
                        useInfo.setStreetName(streetList[1]);
                    }
                }
                if (!ObjectUtils.isEmpty(address)) {
                    useInfo.setAddress(address);
                }
                if (!ObjectUtils.isEmpty(longitudeLatitude)) {
                    useInfo.setLongitudeLatitude(longitudeLatitude);
                }
                useInfoService.saveOrUpdateData(useInfo);
            }
        }
    }

    /**
     * 修改各类告知列表，置为废弃
     *
     * @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);
    }

    /**
     * 更新使用注册登记证编号及ES中的信息
     *
     * @param equId               设备id
     * @param useRegistrationCode 使用注册登记证编号
     */
    public void updataRegisterInfoAndEsData(String equId, String useRegistrationCode) {
        //更新使用注册登记证编号
        idxBizJgRegisterInfoMapper.updateUseOrgCodeByEquip(equId, useRegistrationCode);
        //es中的编号信息
        Map<String, Map<String, Object>> resultMap = new HashMap<>();
        Map<String, Object> map1 = new HashMap<>();
        map1.put("USE_ORG_CODE", useRegistrationCode);
        resultMap.put(equId, map1);
        tzsServiceFeignClient.commonUpdateEsDataByIds(resultMap);
    }

    //更新移装变更基本信息
    public void updateTransferByBaseInfo(JgChangeRegistrationTransfer model) {
        this.saveOrUpdate(model);
    }


    /**
     * 参数为监管码
     *
     * @param supervisoryCode
     * @return
     */
    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) {
        Map<String, Object> exportParamsMap = new HashMap<>();
        //查询移装变更详情
        JgChangeRegistrationTransfer transfer = this.getById(sequenceNbr);
        JgChangeRegistrationTransferEq transferEq = jgChangeRegistrationTransferEqService.getDetailByEquipTransferId(sequenceNbr);
        if (ValidationUtil.isEmpty(transfer) || ValidationUtil.isEmpty(transferEq)) {
            throw new BadRequest("使用登记证导出失败,请稍后重试!");
        }
        //是否废弃
        exportParamsMap.put("isInvalid", transferEq.getIsInvalid());
        JgRegistrationHistory transferHistory = jgRegistrationHistoryService.getDteailByRecord(transferEq.getEquId(), transfer.getApplyNo());
        //登记机关
        if (ValidationUtil.isEmpty(transfer.getReceiveOrgName())) {
            throw new BadRequest("使用登记证导出失败,登记机关为空!");
        }
        exportParamsMap.put("receiveOrgName", transfer.getReceiveOrgName());
        //使用登记证编号
        if (ValidationUtil.isEmpty(transfer.getUseRegistrationCode())) {
            throw new BadRequest("使用登记证导出失败,使用登记证编号为空!");
        }
        exportParamsMap.put("useRegistrationCode", transfer.getUseRegistrationCode());
        //使用单位名称
        if (ValidationUtil.isEmpty(transfer.getUseUnitName())) {
            throw new BadRequest("使用登记证导出失败,使用单位名称为空!");
        }
        exportParamsMap.put("useUnitName", transfer.getUseUnitName());
        //监管码
        if (ValidationUtil.isEmpty(transfer.getSupervisoryCode())) {
            throw new BadRequest("使用登记证导出失败,监管码为空!");
        }
        exportParamsMap.put("supervisoryCode", transfer.getSupervisoryCode());
        //发证日期（当前时间）
        LocalDate today = LocalDate.now();
        exportParamsMap.put("giveOutYear", today.getYear());
        exportParamsMap.put("giveOutMonth", today.getMonthValue());
        exportParamsMap.put("giveOutDay", today.getDayOfMonth());
        //设备使用地址
        if (!ValidationUtil.isEmpty(transferHistory)) {
            String fullAddress = "";
            JSONObject newPosition = JSON.parseObject(transferHistory.getChangeData());
            String province = newPosition.getString("province");
            String city = newPosition.getString("city");
            String county = newPosition.getString("county");
            String street = newPosition.getString("street");
            String address = newPosition.getString("address");

            // 分割省市区街道字段
            if (!ObjectUtils.isEmpty(province)) {
                String[] provinceList = province.split("_");
                if (provinceList.length > 1) {
                    fullAddress += provinceList[1];
                }
            }
            if (!ObjectUtils.isEmpty(city)) {
                String[] cityList = city.split("_");
                if (cityList.length > 1) {
                    fullAddress += cityList[1];
                }
            }
            if (!ObjectUtils.isEmpty(county)) {
                String[] countyList = county.split("_");
                if (countyList.length > 1) {
                    fullAddress += countyList[1];
                }
            }
            if (!ObjectUtils.isEmpty(street)) {
                String[] streetList = street.split("_");
                if (streetList.length > 1) {
                    fullAddress += streetList[1];
                }
            }
            if (!ObjectUtils.isEmpty(address)) {
                fullAddress += address;
            }
            if (ValidationUtil.isEmpty(fullAddress)) {
                throw new BadRequest("使用登记证导出失败,设备使用地址为空!");
            }
            exportParamsMap.put("fullAddress", fullAddress);
        }

        //查询设备注册信息
        IdxBizJgRegisterInfo registerInfo = idxBizJgRegisterInfoService.getOne(new QueryWrapper<IdxBizJgRegisterInfo>().eq("RECORD", transferEq.getEquId()));
        if (!ValidationUtil.isEmpty(registerInfo)) {
            //设备种类、类别、品种
            String equList = registerInfo.getEquList();//设备种类
            String equCategory = registerInfo.getEquCategory();//设备类别
            String equDefine = registerInfo.getEquDefine();//设备品种
            List<EquipmentCategory> categoryList0 = iCommonService.getEquipmentCategoryList(equList, null);
            List<EquipmentCategory> categoryList1 = iCommonService.getEquipmentCategoryList(equCategory, null);
            List<EquipmentCategory> categoryList2 = iCommonService.getEquipmentCategoryList(equDefine, null);
            if (CollectionUtils.isNotEmpty(categoryList0)) {
                if (ValidationUtil.isEmpty(categoryList0.get(0).getName())) {
                    throw new BadRequest("使用登记证导出失败,设备种类为空!");
                }
                exportParamsMap.put("equList", categoryList0.get(0).getName());
            }
            if (CollectionUtils.isNotEmpty(categoryList1)) {
                if (ValidationUtil.isEmpty(categoryList1.get(0).getName())) {
                    throw new BadRequest("使用登记证导出失败,设备类别为空!");
                }
                exportParamsMap.put("equCategory", categoryList1.get(0).getName());
            }
            if (CollectionUtils.isNotEmpty(categoryList2)) {
                if (ValidationUtil.isEmpty(categoryList2.get(0).getName())) {
                    throw new BadRequest("使用登记证导出失败,设备品种为空!");
                }
                exportParamsMap.put("equDefine", categoryList2.get(0).getName());
            }
            //设备代码
            if (ValidationUtil.isEmpty(registerInfo.getEquCode())) {
                throw new BadRequest("使用登记证导出失败,设备代码为空!");
            }
            exportParamsMap.put("equCode", registerInfo.getEquCode());
        }

        //单位内部编码
        IdxBizJgUseInfo useInfo = idxBizJgUseInfoService.getOneData(transferEq.getEquId());
        if (!ValidationUtil.isEmpty(useInfo)) {
            if (ValidationUtil.isEmpty(useInfo.getUseInnerCode())) {
                throw new BadRequest("使用登记证导出失败,设备单位内部编码为空!");
            }
            exportParamsMap.put("useInnerCode", useInfo.getUseInnerCode());
        }
        IdxBizJgFactoryInfo factoryInfo = idxBizJgFactoryInfoService.getOneData(transferEq.getEquId());
        //产品编号(出厂编号)
        if (!ValidationUtil.isEmpty(factoryInfo)) {
            if (ValidationUtil.isEmpty(factoryInfo.getFactoryNum())) {
                throw new BadRequest("使用登记证导出失败,产品编号为空!");
            }
            exportParamsMap.put("factoryNum", factoryInfo.getFactoryNum());
        }
        //调用生成使用登记证
        iCommonService.generateCertificateReport(exportParamsMap, response);
    }


    /**
     * 启动工作流
     */
    private WorkflowResultDto startWorkFlork(String receiveOrgCreditCode) {
        ActWorkflowBatchDTO workflowBatchParams = new ActWorkflowBatchDTO();
        List<ActWorkflowStartDTO> workflowList = new ArrayList<>();
        ActWorkflowStartDTO workflow = new ActWorkflowStartDTO();
        workflow.setProcessDefinitionKey(PROCESS_DEFINITION_KEY);
        workflow.setBusinessKey("submit");
        workflow.setCompleteFirstTask(Boolean.TRUE);
        //下一节点执行人单位（下节点接收机构code）
        workflow.setNextExecuteUserCompanyCode(receiveOrgCreditCode);
        workflowList.add(workflow);
        workflowBatchParams.setProcess(workflowList);
        List<ProcessTaskDTO> processTasks = icmWorkflowService.startBatch(workflowBatchParams);
        // 组装工作流返回的数据
        return commonService.buildWorkFlowInfo(processTasks).get(0);
    }

    /**
     * 新增代办任务
     */
    private void createToDoTask(List<WorkflowResultDto> sorkflows, JgChangeRegistrationTransfer transfer, String submitType) {
        if (!ValidationUtil.isEmpty(sorkflows)) {
            List<TaskModelDto> toDoTasklist = new ArrayList<>();
            for (WorkflowResultDto sorkflow : sorkflows) {
                TaskModelDto toDoTask = new TaskModelDto();
                toDoTask.setTaskName(sorkflow.getTaskName());
                toDoTask.setFlowCreateDate(transfer.getCreateDate());
                toDoTask.setTaskCode(transfer.getApplyNo());
                toDoTask.setTaskContent(this.getSummaryInfo(transfer));
//                toDoTask.setTaskDesc();
                toDoTask.setTaskType(BusinessTypeEnum.JG_CHANGE_REGISTRATION.getCode());
                toDoTask.setTaskTypeLabel(BusinessTypeEnum.JG_CHANGE_REGISTRATION.getName());
                toDoTask.setRelationId(transfer.getInstanceId());
                toDoTask.setExecuteUserIds(sorkflow.getNextExecutorUserIds());
                FlowStatusEnum flowStatusEnum = this.getTaskStatus(submitType);
                toDoTask.setTaskStatus(flowStatusEnum.getCode());
                toDoTask.setTaskStatusLabel(flowStatusEnum.getName());
                toDoTask.setFlowStatus(commonService.getDictionaryCodeByName(transfer.getStatus()));
                toDoTask.setFlowStatusLabel(transfer.getStatus());
                toDoTask.setFlowCode(transfer.getNextTaskId());
                toDoTask.setStartUserId(transfer.getCreateUserId());
                toDoTask.setStartUser(transfer.getCreateUserName());
                toDoTask.setStartUserCompanyName(transfer.getCreateUserCompanyName());
                toDoTask.setStartDate(new Date());
                toDoTask.setNextExecuteUser(transfer.getNextExecutorIds());
                TaskMessageDto taskMessageDto = new TaskMessageDto();
                BeanUtil.copyProperties(transfer, taskMessageDto);
                toDoTask.setModel(taskMessageDto);
                toDoTasklist.add(toDoTask);
            }
            commonService.buildTaskModel(toDoTasklist);
        }
    }

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

    /**
     * @return String
     * @deprecated 动态获取
     */
    public String getSummaryInfo(JgChangeRegistrationTransfer transfer) {
        String result = "来自%s【%s】的业务办理，【申请单号：%s】";
        return String.format(result, Optional.ofNullable(transfer.getEquipListName()).orElse("无"), transfer.getSupervisoryCode(), transfer.getApplyNo());
    }

    public String getNextUserOrgCode(String operate, JgChangeRegistrationTransfer contract) {
        String code = null;
        if ("0".equals(operate)) {
            code = contract.getReceiveOrgCode();
        } else {
            //驳回
            if (WorkFlowStatusEnum.TRANSFER_RECEIVE.getPass().equals(contract.getAuditStatus()) ||
                    WorkFlowStatusEnum.TRANSFER_RECEIVE.getReject().equals(contract.getAuditStatus()) ||
                    WorkFlowStatusEnum.TRANSFER_RECEIVE.getRollBack().equals(contract.getAuditStatus())) {
                code = contract.getUseUnitCreditCode();
            }
        }
        return code == null ? contract.getReceiveOrgCode() : code;
    }

    private String getPageTypeByCurrentNode(String auditStatus) {
        if(WorkFlowStatusEnum.TRANSFER_SUBMIT.getPass().equals(auditStatus) ||
                WorkFlowStatusEnum.TRANSFER_SUBMIT.getReject().equals(auditStatus) ||
                WorkFlowStatusEnum.TRANSFER_SUBMIT.getRollBack().equals(auditStatus)
        ){
            // urlInfo.json 文件的 pageType
            return "edit";
        } else {
            // urlInfo.json 文件的 pageType
            return "look";
        }
    }
}