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.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.biz.common.bo.CompanyBo;
import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.amos.boot.biz.common.utils.RedisKey;
import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;
import com.yeejoin.amos.boot.module.jg.api.common.StringUtil;
import com.yeejoin.amos.boot.module.jg.api.dto.*;
import com.yeejoin.amos.boot.module.jg.api.entity.JgChangeRegistrationTransfer;
import com.yeejoin.amos.boot.module.jg.api.entity.JgChangeRegistrationTransferEq;
import com.yeejoin.amos.boot.module.jg.api.entity.JgRegistrationHistory;
import com.yeejoin.amos.boot.module.jg.api.enums.BusinessTypeEnum;
import com.yeejoin.amos.boot.module.jg.api.enums.EquipTypeEnum;
import com.yeejoin.amos.boot.module.jg.api.enums.WorkFlowStatusEnum;
import com.yeejoin.amos.boot.module.jg.api.mapper.*;
import com.yeejoin.amos.boot.module.jg.api.service.IJgChangeRegistrationTransferEqService;
import com.yeejoin.amos.boot.module.jg.api.service.IJgChangeRegistrationTransferService;
import com.yeejoin.amos.boot.module.jg.api.service.IJgRegistrationHistoryService;
import com.yeejoin.amos.boot.module.jg.api.vo.SortVo;
import com.yeejoin.amos.boot.module.jg.biz.feign.TzsServiceFeignClient;
import com.yeejoin.amos.boot.module.jg.biz.service.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.*;
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.boot.module.ymt.api.mapper.IdxBizJgSupervisionInfoMapper;
import com.yeejoin.amos.feign.systemctl.model.TaskV2Model;
import com.yeejoin.amos.feign.workflow.model.ActWorkflowBatchDTO;
import com.yeejoin.amos.feign.workflow.model.ActWorkflowStartDTO;
import com.yeejoin.amos.feign.workflow.model.ProcessTaskDTO;
import com.yeejoin.amos.feign.workflow.model.TaskResultDTO;
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.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
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.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.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

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

/**
 * 移装变更登记登记服务实现类
 *
 * @author system_generator
 * @date 2023-12-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
    RestHighLevelClient restHighLevelClient;
    @Autowired
    WorkFlowFeignService workFlowFeginService;
    @Autowired
    RedisUtils redisUtils;
    @Autowired
    ICommonService iCommonService;
    @Autowired
    TzsServiceFeignClient tzsServiceFeignClient;
    @Autowired
    ICmWorkflowService icmWorkflowService;
    @Autowired
    CommonServiceImpl commonService;
    @Autowired
    private IJgChangeRegistrationTransferEqService jgChangeRegistrationTransferEqService;
    @Autowired
    private IJgRegistrationHistoryService jgRegistrationHistoryService;
    @Autowired
    private IIdxBizJgUseInfoService useInfoService;
    @Autowired
    private IdxBizJgUseInfoServiceImpl idxBizJgUseInfoService;
    @Autowired
    private IdxBizJgRegisterInfoServiceImpl idxBizJgRegisterInfoService;
    @Autowired
    private IdxBizJgFactoryInfoServiceImpl idxBizJgFactoryInfoService;
    //改造登记关系表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
    IdxBizJgSupervisionInfoMapper idxBizJgSupervisionInfoMapper;
    @Autowired
    CommonServiceImpl commonServiceImpl;

    @Autowired
    private RedissonClient redissonClient;

    /**
     * 新增移装变更登记
     *
     * @param submitType
     * @param map
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public List<JgChangeRegistrationTransferDto> 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());
        // 统计使用
        CompanyBo companyBo = commonServiceImpl.getOneCompany(oldTransfer.getReceiveCompanyCode());
        oldTransfer.setReceiveCompanyOrgCode(companyBo.getOrgCode());
        String fullAddress = "";
        String province = (String) tableData.get("province");
        String city = (String) tableData.get("city");
        String county = (String) tableData.get("county");
        String street = (String) tableData.get("street");
        String address = (String) tableData.get("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;
        }
        //设备移装详细地址
        oldTransfer.setFullAddress(fullAddress);

        //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", "", String.valueOf(map.get("nextTaskId")));
            } else {
                // 如果是新启动的流程开启自动访问
                String equipListName = Optional.ofNullable(tableData.get("equListDesc")).orElse("无").toString();
                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.getReceiveCompanyCode());

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

        JgChangeRegistrationTransferDto resultDto = new JgChangeRegistrationTransferDto();
        Bean.copyExistPropertis(oldTransfer, resultDto);
        //组装返回信息，添加设备信息的展示
        resultDto.setEquCategory((String) tableData.get("equCategoryDesc"));
        resultDto.setProductName((String) tableData.get("productName"));
        resultDto.setAllAddress(oldTransfer.getFullAddress());
        resultDto.setEquCode((String) tableData.get("equCode"));
        resultDto.setInnerCode((String) tableData.get("useInnerCode"));
        return Collections.singletonList(resultDto);
    }

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

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

            WorkflowResultDto workflowResult;
            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.completeOrReject(taskId, dto, operate);
            workflowResult = commonService.buildWorkFlowInfo(Collections.singletonList(complete)).get(0);
            // 更新下一步执行人
            this.updateExecuteIds(instanceId, transfer, operate, workflowResult);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            if(lock.isHeldByCurrentThread()){
                lock.unlock();
            }
        }
    }

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

            ReginParams reginParams = JSONObject.parseObject(redisUtils.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken())).toString(), ReginParams.class);

            JgChangeRegistrationTransfer jgTransfer;
            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);

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

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

    /**
     * 批量删除
     *
     * @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);
                }
            }

            // 删除待办
            this.deleteTaskBatch(Arrays.asList(sequenceNbrs));

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

    // 删除待办
    private void deleteTaskBatch(List<Long> ids) {
        ids.forEach(id -> commonService.deleteTaskModel(id + ""));
    }

    /**
     * 根据移装变更记录sequenceNbr查询详情
     * @param sequenceNbr 变更记录sequenceNbr
     * @return
     */
    @Override
    public Map<String, Map<String, Object>> getTransferDetail(String sequenceNbr) {
        Map<String, Map<String, Object>> pageDataMap = new HashMap<>();
        Map<String, Object> resultDataMap = new HashMap<>();
        //移装变更详情
        JgChangeRegistrationTransfer transferById = this.getById(sequenceNbr);
        //查询设备详情
        String equipId = jgChangeRegistrationTransferEqMapper.getEquipIdByEquipTransferId(sequenceNbr);

        if (ValidationUtil.equals(FlowStatusEnum.TO_BE_FINISHED.getName(), transferById.getStatus())) {
            // 执行完成时查询历史表
            JgRegistrationHistory historyData = jgRegistrationHistoryService.getDteailByRecord(equipId, transferById.getApplyNo());
            if (!ValidationUtil.isEmpty(historyData)) {
                Map<String,Object> newPosition = JSON.parseObject(historyData.getChangeData(),Map.class);
                resultDataMap.putAll(newPosition);
                if (!ValidationUtil.isEmpty(transferById)) {
                    Map<String, Object> transferToMap = Bean.BeantoMap(transferById);
                    resultDataMap.putAll(transferToMap);
                }
            }
        } else {
            // 非执行完成状态显示最新设备信息
            Map<String, Object> equipDetailMap = idxBizJgRegisterInfoService.getDetailFieldCamelCaseByRecord(equipId);
            resultDataMap.putAll(equipDetailMap);
            if (!ValidationUtil.isEmpty(transferById)) {
                Map<String, Object> transferToMap = Bean.BeantoMap(transferById);
                resultDataMap.putAll(transferToMap);
            }
            JgRegistrationHistory historyData = jgRegistrationHistoryService.getDteailByRecord(equipId, transferById.getApplyNo());
            Map<String,Object> changeData = JSON.parseObject(historyData.getChangeData(),Map.class);
            // 省市区街道字段等业务字段
            resultDataMap.put("transferProvince", changeData.get("transferProvince"));
            resultDataMap.put("transferCity", changeData.get("transferCity"));
            resultDataMap.put("transferCounty", changeData.get("transferCounty"));
            resultDataMap.put("transferStreet", changeData.get("transferStreet"));
            resultDataMap.put("transferUsePlace", changeData.get("transferUsePlace"));
            resultDataMap.put("transferAddress", changeData.get("transferAddress"));
            resultDataMap.put("transferLongitudeLatitude", changeData.get("transferLongitudeLatitude"));
            resultDataMap.put("orgBranchCode", changeData.get("orgBranchCode"));
            resultDataMap.put("orgBranchName", changeData.get("orgBranchName"));
            resultDataMap.put("transferIsXixian", changeData.get("transferIsXixian"));
            resultDataMap.put("transferSafetyManager", changeData.get("transferSafetyManager"));
            resultDataMap.put("transferPhone", changeData.get("transferPhone"));
            resultDataMap.put("transferUseInfo", changeData.get("transferUseInfo"));
            resultDataMap.put("useInnerCode", equipDetailMap.get("equCode"));
            resultDataMap.put("receiveOrgCode", transferById.getReceiveCompanyCode() + "_" + transferById.getReceiveOrgName());
        }
        String transferSafetyManager = Optional.ofNullable(resultDataMap.get("transferSafetyManager")).orElse("").toString();
        if(StringUtil.isNotEmpty(transferSafetyManager)){
            String[] transferSafetyManagerList = transferSafetyManager.split("_");
            if(transferSafetyManagerList.length>1){
                resultDataMap.put("transferSafetyManagerName",transferSafetyManagerList[1]);
            }
        }
        if (!resultDataMap.isEmpty()) {
            pageDataMap.put(TABLE_PAGE_ID, resultDataMap);
        }
        return pageDataMap;
    }

    /**
     * 分页查询
     *
     * @param page
     * @param params
     * @param companyTypeCode
     * @param companyType
     * @return
     */
    @Override
    public Page<Map<String, Object>> queryListForPage(Page<Map<String, Object>> page,String sort, JgChangeRegistrationTransferDto params, String companyTypeCode, String companyType) {
        SortVo sortMap = commonService.sortFieldConversion(sort);
        Page<Map<String, Object>> listPage = this.baseMapper.getListPage(page,sortMap, params, companyTypeCode, RequestContext.getExeUserId());
        listPage.getRecords().forEach(x-> x.put("companyType",companyType));
        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);
                    taskModelDto.setFlowCode(jgChangeRegistrationTransfer.getNextTaskId());
                    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.setNextTaskId(null);
            //更新下一步可执行人
            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);
            commonService.updateTaskModel(map);
        }
        // redis流程实时数据更新
        commonServiceImpl.saveExecuteFlowData2Redis(instanceId, this.buildInstanceRuntimeData(jgChangeRegistrationTransfer));
        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);
            String useRegistrationCode = commonServiceImpl.generateRegistrationCode(transferEq.getEquId(), supervisoryCode, updateData.getReceiveCompanyCode());
            if (!ValidationUtil.isEmpty(useRegistrationCode)) {
                updateData.setUseRegistrationCode(useRegistrationCode);
            }
            //补充移装变更表
            this.updateTransferByBaseInfo(updateData);
            //查询移装记录
            JgChangeRegistrationTransfer transfer = this.getBaseMapper().selectById(sequenceNbr);
            //查询修改后的新数据
            JgRegistrationHistory newData = jgRegistrationHistoryService.getDteailByRecord(transferEq.getEquId(), transfer.getApplyNo());
            //替换历史数据表和设备使用表
            this.replacementHistoryData(transferEq.getEquId(), transfer.getApplyNo(), newData, useRegistrationCode);
            //更新使用注册登记证编号及ES中的信息
            this.updataRegisterInfoAndEsData(transferEq.getEquId(), newData, useRegistrationCode);
            //修改各类告知列表，置为废弃
            this.updataInvalidStatusByHistory(transferEq.getEquId(), transferEq.getEquipTransferId());
        }
    }

    /**
     * 修改历史数据表和设备使用表
     *
     * @param record              设备Id
     * @param applyNo             申请记录编号
     * @param newData             设备移装的新数据
     * @param useRegistrationCode 使用登记编号
     */
    public void replacementHistoryData(String record, String applyNo, JgRegistrationHistory newData, String useRegistrationCode) {

        if (!ValidationUtil.isEmpty(record) && !ValidationUtil.isEmpty(applyNo)) {
            //查询设备旧数据
            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("tansferProvince");
                //市
                String city = newPosition.getString("transferCity");
                //区县
                String county = newPosition.getString("transferCounty");
                //街道
                String street = newPosition.getString("transferStreet");
                //地址
                String address = newPosition.getString("transferAddress");
                //经纬度
                String longitudeLatitude = newPosition.getString("transferLongitudeLatitude");
                //使用场所
                String usePlace = newPosition.getString("transferUsePlace");
                //所属监管单位
                String supervisionUnit = newPosition.getString("transferSupervisionUnit");
                //是否西咸
                String isXixian = newPosition.getString("transferIsXixian");
                //安全管理员
                String safetyManager = newPosition.getString("transferSafetyManager");
                //产权单位
                String transferUseInfo = newPosition.getString("transferUseInfo");
                //安全管理员电话
                String phone = newPosition.getString("transferPhone");

                // 分割省市区街道字段
                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);
                }
                if(!ObjectUtils.isEmpty(usePlace)){
                    useInfo.setUsePlace(usePlace);
                }
                if(!ObjectUtils.isEmpty(isXixian)){
                    useInfo.setIsNotXiXian(isXixian);
                }
                if(!ObjectUtils.isEmpty(safetyManager)){
                    String[] safetyManagerList = safetyManager.split("_");
                    if (safetyManagerList.length>1){
                        useInfo.setSafetyManagerId(safetyManagerList[0]);
                        useInfo.setSafetyManager(safetyManagerList[1]);
                    }
                }
                if(!ObjectUtils.isEmpty(phone)){
                    useInfo.setPhone(phone);
                }
                if(!ObjectUtils.isEmpty(transferUseInfo)){
                    String[] useInfoList = transferUseInfo.split("_");
                    if(useInfoList.length>1){
                        useInfo.setEstateUnitCreditCode(useInfoList[0]);
                        useInfo.setEstateUnitName(useInfoList[1]);
                    }
                }

                IdxBizJgSupervisionInfo idxBizJgSupervisionInfo = new IdxBizJgSupervisionInfo();
                if(!ObjectUtils.isEmpty(supervisionUnit)){
                    String[] supervisionUnitList = supervisionUnit.split("_");
                    if(supervisionUnitList.length>1){
                        idxBizJgSupervisionInfo.setOrgBranchCode(supervisionUnitList[0]);
                        idxBizJgSupervisionInfo.setOrgBranchName(supervisionUnitList[1]);
                        LambdaQueryWrapper<IdxBizJgSupervisionInfo> eq = new QueryWrapper<IdxBizJgSupervisionInfo>().lambda().eq(IdxBizJgSupervisionInfo::getRecord,record);
                        idxBizJgSupervisionInfoMapper.update(idxBizJgSupervisionInfo, eq);
                    }
                }

                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, JgRegistrationHistory newData, String useRegistrationCode) {
        //更新使用注册登记证编号
        idxBizJgRegisterInfoMapper.updateUseOrgCodeByEquip(equId, useRegistrationCode);

        //获取移装新位置，更新ES
        String newUsePlace = "";
        String newAddress = "";
        String newLongitudeLatitude = "";
        if (!ValidationUtil.isEmpty(newData)) {
            JSONObject newPosition = JSON.parseObject(newData.getChangeData());
            String province = newPosition.getString("transferProvince");
            String city = newPosition.getString("transferCity");
            String county = newPosition.getString("transferCounty");
            String street = newPosition.getString("transferStreet");
            String address = newPosition.getString("transferAddress");
            String longitudeLatitude = newPosition.getString("longitudeLatitude");
            // 分割省市区街道字段
            if (!ObjectUtils.isEmpty(province)) {
                String[] provinceList = province.split("_");
                if (provinceList.length > 1) {
                    newUsePlace += provinceList[1] + "/";
                }
            }
            if (!ObjectUtils.isEmpty(city)) {
                String[] cityList = city.split("_");
                if (cityList.length > 1) {
                    newUsePlace += cityList[1] + "/";
                }
            }
            if (!ObjectUtils.isEmpty(county)) {
                String[] countyList = county.split("_");
                if (countyList.length > 1) {
                    newUsePlace += countyList[1]+ "/";
                }
            }
            if (!ObjectUtils.isEmpty(street)) {
                String[] countyList = street.split("_");
                if (countyList.length > 1) {
                    newUsePlace += countyList[1];
                }
            }

            if (!ObjectUtils.isEmpty(address)) {
                newAddress = address;
            }
            if (!ObjectUtils.isEmpty(longitudeLatitude)) {
                newLongitudeLatitude = longitudeLatitude;
            }
        }
        //es中的编号信息
        Map<String, Map<String, Object>> resultMap = new HashMap<>();
        Map<String, Object> map1 = new HashMap<>();
        map1.put("USE_PLACE", newUsePlace);
        map1.put("ADDRESS", newAddress);
        map1.put("LONGITUDE_LATITUDE", newLongitudeLatitude);
        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, String printType) {
        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());

        getAuditPassedDate(transfer.getAuditPassDate(), exportParamsMap);

        //设备使用地址
        if (!ValidationUtil.isEmpty(transferHistory)) {
            String fullAddress = "";
            JSONObject newPosition = JSON.parseObject(transferHistory.getChangeData());
            String province = newPosition.getString("transferProvince");
            String city = newPosition.getString("transferCity");
            String county = newPosition.getString("transferCounty");
            String street = newPosition.getString("transferStreet");
            String address = newPosition.getString("transferAddress");

            // 分割省市区街道字段
            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());
        }
        exportParamsMap.put("applyNo", transfer.getApplyNo());
        if ("0".equals(printType)) {
            //调用生成使用登记证
            commonService.generateCertificateReport(exportParamsMap, response);
        }else{
            commonService.generatePdfPrint(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(sorkflow.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("无"), Optional.ofNullable(transfer.getSupervisoryCode()).orElse("无"), Optional.ofNullable(transfer.getApplyNo()).orElse("无"));
    }

    public String getNextUserOrgCode(String operate, JgChangeRegistrationTransfer contract) {
        String code = null;
        if ("0".equals(operate)) {
            code = contract.getReceiveCompanyCode();
        } 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.getReceiveCompanyCode() : 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";
        }
    }

    public Map<String, Object> getDetailFieldCamelCase( String record) {
        Map<String, Object> result = new HashMap<>();
        result = idxBizJgRegisterInfoService.getDetailFieldCamelCaseByRecord(record);
        //移装变更-省份回显
        result.put("transferProvince",result.get("province"));
        //移装变更-市回显
        result.put("transferCity",result.get("city"));
        //移装变更-区回显
        result.put("transferCounty",result.get("county"));
        //移装变更-街道回显
        result.put("transferStreet",result.get("factoryUseSiteStreet")+"_"+result.get("streetName"));
        //移装变更-移装场所
        result.put("transferUsePlace",result.get("usePlace"));
        //移装变更-详细地址
        result.put("transferAddress",result.get("useAddress"));
        //移装变更-经纬度
        result.put("transferLongitudeLatitude",result.get("longitudeLatitude"));
        //移装变更-属地监管部门
        result.put("orgBranchCode",result.get("orgBranchCode")+"_"+result.get("orgBranchName"));
        //移装变更-所属经营单位
        result.put("transferIsXixian",result.get("isNotXiXian"));
        //移装变更-安全管理员
        result.put("transferSafetyManager",result.get("safetyManagerId")+"_"+result.get("safetyManager"));
        //移装变更-安全管理员姓名
        result.put("transferSafetyManagerName",result.get("safetyManager"));
        //移装变更-电话
        result.put("transferPhone",result.get("phone"));
        //移装变更-产权单位
        result.put("transferUseInfo",result.get("estateUnitCreditCode")+"_"+result.get("estateUnitName"));
        return result;
    }
}