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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.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.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.EquipTypeEnum;
import com.yeejoin.amos.boot.module.jg.api.enums.UseStatusEnum;
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.IIdxBizJgUseInfoService;
import com.yeejoin.amos.boot.module.jg.flc.api.fegin.WorkFlowFeignService;
import com.yeejoin.amos.boot.module.ymt.api.entity.IdxBizJgRegisterInfo;
import com.yeejoin.amos.boot.module.ymt.api.entity.IdxBizJgUseInfo;
import com.yeejoin.amos.boot.module.ymt.api.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.component.feign.model.FeignClientResult;
import com.yeejoin.amos.feign.workflow.Workflow;
import com.yeejoin.amos.feign.workflow.model.ActWorkflowStartDTO;
import com.yeejoin.amos.feign.workflow.model.AjaxResult;
import com.yeejoin.amos.feign.workflow.model.TaskResultDTO;
import org.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.factory.annotation.Autowired;
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 java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 移装变更登记登记服务实现类
 *
 * @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
    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
    TzsServiceFeignClient tzsServiceFeignClient;

    /**
     * 新增移装变更登记
     *
     * @param submitType
     * @param map
     * @return
     */
    public boolean createTransfer(String submitType, Map<String, Object> map, ReginParams reginParams) {
        Map<String, Object> tableData = (Map<String, Object>) map.get(TABLE_PAGE_ID);
        CompanyBo company = reginParams.getCompany();
        String sequenceNbr = (String) tableData.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];
            }
        }
        //查询申请单号
        ResponseModel<List<String>> result = tzsServiceFeignClient.applicationFormCode(ApplicationFormTypeEnum.YZBG.getCode(), 1);
        if (!result.getResult().isEmpty()) {
            //申请编号
            oldTransfer.setApplyNo(result.getResult().get(0));
        } else {
            throw new BadRequest("申请单编号生成失败,请稍后重试!");
        }

        //有sequenceNbr代表修改数据
        if (!ValidationUtil.isEmpty(sequenceNbr)) {
            //查询移装变更记录
            oldTransfer = this.getById(sequenceNbr);
            //查询关系表
            oldTransferEq = jgChangeRegistrationTransferEqService.getDetailByEquipTransferId(sequenceNbr);
            //查询历史记录表
            if (!ValidationUtil.isEmpty(oldTransferEq)) {
                oldHistory = jgRegistrationHistoryService.getDteailByRecord(oldTransferEq.getEquId(), sequenceNbr);
                useInfo = idxBizJgUseInfoService.getOneData(oldTransferEq.getEquId());
            }
        }

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

        //登记机构代码
        //登记机构公司代码
        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(FlowStatusEnum.TO_BE_SUBMITTED.getName());
        oldTransfer.setStatus(UseStatusEnum.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);
                    }
                }

                //使用登记编号  X
                if (!ValidationUtil.isEmpty(dto2.get("USE_REGISTRATION_CODE"))) {
                    oldTransfer.setUseRegistrationCode((String) dto2.get("USE_REGISTRATION_CODE"));
                }

                //检验机构统一信用代码  X
                if (!ValidationUtil.isEmpty(dto2.get("INSPECT_UNIT_CREDIT_CODE"))) {
                    oldTransfer.setInspectUnitCreditCode((String) dto2.get("INSPECT_UNIT_CREDIT_CODE"));
                }
                //检验单位  X
                if (!ValidationUtil.isEmpty(dto2.get("INSPECT_UNIT_NAME"))) {
                    oldTransfer.setInspectUnitName((String) dto2.get("INSPECT_UNIT_NAME"));
                }
                //检验结果照片  X
                if (!ValidationUtil.isEmpty(dto2.get("INSPECT_RESULT_PHOTO"))) {
                    oldTransfer.setInspectResultPhoto((String) dto2.get("INSPECT_RESULT_PHOTO"));
                }
                //检验结果  X
                if (!ValidationUtil.isEmpty(dto2.get("INSPECT_RESULT"))) {
                    oldTransfer.setInspectResult((String) dto2.get("INSPECT_RESULT"));
                }
                //安装单位名称  X
                if (!ValidationUtil.isEmpty(dto2.get("INSTALL_UNIT_NAME"))) {
                    oldTransfer.setSupervisoryCode((String) dto2.get("INSTALL_UNIT_NAME"));
                }
            }

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

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

            //新增历史记录表
            oldHistory.setRegistrationClass("移装登记");
            //保存变更新数据
            oldHistory.setChangeData(JSON.toJSONString(tableData));
            //保存变更旧数据
            oldHistory.setOldData(JSON.toJSONString(useInfo));
            //设备监管码
            oldHistory.setSupervisoryCode(supervisoryCode);
            oldHistory.setEquId(equId);
            oldHistory.setCurrentDocumentId(oldTransfer.getSequenceNbr().toString());
            oldHistory.setStatus("new");

            jgRegistrationHistoryService.saveOrUpdateHistoryData(oldHistory);

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

        //发起流程
        if (!ObjectUtils.isEmpty(map.get("submit"))) {
            String instanceId = "";
            if (map.containsKey("instanceId")) {
                instanceId = map.get("instanceId").toString();
            } else {
                // 启动并执行流程
                instanceId = startByVariable();
                this.updateExecuteIds(instanceId, oldTransfer.getSequenceNbr(), "0");
            }

            if (!ObjectUtils.isEmpty(instanceId)) {
                // 修改数据信息
                this.updateExecuteIds(instanceId, oldTransfer.getSequenceNbr(), "0");
                // 默认执行流程
                this.flowExecute(oldTransfer.getSequenceNbr(), instanceId, "0", "", false);
            }
        }
        return true;
    }

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

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

    }

    /**
     * 流程撤回
     *
     * @param instanceId
     */
    public void revocation(String instanceId) {
        ReginParams reginParams = JSONObject.parseObject(redisUtils.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken())).toString(), ReginParams.class);
        String taskCode = "";
        JgChangeRegistrationTransfer jgTransfer = new JgChangeRegistrationTransfer();
        LambdaQueryWrapper<JgChangeRegistrationTransfer> lambda = new QueryWrapper<JgChangeRegistrationTransfer>().lambda();
        lambda.eq(JgChangeRegistrationTransfer::getInstanceId, instanceId);
        ArrayList<String> roleList = new ArrayList<>();
        try {
            workFlowFeginService.rollBack(instanceId);
            JSONObject taskNoAuth = workFlowFeginService.getTaskNoAuth(instanceId);
            JSONObject nextTask = JSON.parseObject(JSON.toJSONString(taskNoAuth.get("data")));

            if (!ObjectUtils.isEmpty(taskNoAuth.get("data"))) {
                String nextTaskId = nextTask.getString("id");
                FeignClientResult<JSONObject> nodeInfo = workFlowFeginService.getNodeInfo(nextTaskId);
                JSONObject result = nodeInfo.getResult();
                Map<String, Object> taskInfo = (Map<String, Object>) result.get("taskInfo");
                taskCode = String.valueOf(taskInfo.get("taskDefinitionKey"));
                AjaxResult taskGroupName = Workflow.taskClient.getTaskGroupName(nextTaskId);
                JSONArray data = JSON.parseArray(JSON.toJSONString(taskGroupName.get("data")));
                for (Object datum : data) {
                    if (((Map<?, ?>) datum).containsKey("groupId")) {
                        roleList.add(((Map<?, ?>) datum).get("groupId").toString());
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (!ObjectUtils.isEmpty(taskCode)) {
            jgTransfer.setStatus(WorkFlowStatusEnum.getMessage(taskCode).getRollBack());
        }
        String join = String.join(",", roleList);
        jgTransfer.setPromoter("");
        jgTransfer.setNextExecutorIds(join);
        this.update(jgTransfer, lambda);
    }

    /**
     * 批量删除
     *
     * @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);
            LambdaQueryWrapper<JgRegistrationHistory> historyWapper = new QueryWrapper<JgRegistrationHistory>().lambda();
            historyWapper.in(JgRegistrationHistory::getCurrentDocumentId, Arrays.asList(sequenceNbrs));
            jgRegistrationHistoryService.updateDate(history, historyWapper);
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    /**
     * 根据设备Id查询详情
     *
     * @param equipId 设备Id
     * @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);
        }
        //判断流程是否执行完成，
        // 1、未执行完成时查询历史表
        // 2、执行完成后查询使用信息表
        if (!ValidationUtil.equals(FlowStatusEnum.TO_BE_FINISHED.getName(), transferById.getStatus())) {
            JgRegistrationHistory historyData = jgRegistrationHistoryService.getDteailByRecord(equipId, transferById.getSequenceNbr().toString());
            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);
                resultDataMap.put("record", useInfoByRecord.getRecord());
                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) {
        Page<Map<String, Object>> listPage = this.baseMapper.getListPage(page, params, params.getRoleIds());
        return listPage;
    }

    //启动流程
    public String startByVariable() {
        String instanceId = "";
        //启动流程
        try {
            ActWorkflowStartDTO dto = new ActWorkflowStartDTO();
            dto.setProcessDefinitionKey(PROCESS_DEFINITION_KEY);
            dto.setBusinessKey("submit");
            AjaxResult ajaxResult = Workflow.taskClient.startByVariable(dto);
            instanceId = ((Map) ajaxResult.get("data")).get("id").toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return instanceId;
    }

    public void updateExecuteIds(String instanceId, Long sequenceNbr, String operate) {
        ReginParams reginParams = JSONObject.parseObject(redisUtils.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken())).toString(), ReginParams.class);
        String role = "";
        String taskCode = FlowStatusEnum.TO_BE_FINISHED.getName();
        ArrayList<String> roleList = new ArrayList<>();
        JgChangeRegistrationTransfer jgChangeRegistrationTransfer = this.getBaseMapper().selectById(sequenceNbr);
        try {
            // 查询下节点任务
            JSONObject taskNoAuth = workFlowFeginService.getTaskNoAuth(instanceId);
            if (!ObjectUtils.isEmpty(taskNoAuth.get("data"))) {
                JSONObject nextTask = JSON.parseObject(JSON.toJSONString(taskNoAuth.get("data")));
                String nextTaskId = nextTask.getString("id");
                FeignClientResult<JSONObject> nodeInfo = workFlowFeginService.getNodeInfo(nextTaskId);
                JSONObject result = nodeInfo.getResult();
                Map<String, Object> taskInfo = (Map<String, Object>) result.get("taskInfo");
                taskCode = String.valueOf(taskInfo.get("taskDefinitionKey"));
                AjaxResult taskGroupName = Workflow.taskClient.getTaskGroupName(nextTaskId);
                JSONArray data = JSON.parseArray(JSON.toJSONString(taskGroupName.get("data")));
                for (Object datum : data) {
                    if (((Map) datum).containsKey("groupId")) {
                        roleList.add(((Map) datum).get("groupId").toString());
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (!FlowStatusEnum.TO_BE_FINISHED.getName().equals(taskCode)) {
            role = String.join(",", roleList);
            jgChangeRegistrationTransfer.setNextExecutorIds(role);
            jgChangeRegistrationTransfer.setPromoter(reginParams.getUserModel().getUserId());
            jgChangeRegistrationTransfer.setInstanceId(instanceId);
            if (!ObjectUtils.isEmpty(jgChangeRegistrationTransfer.getExecuteSequence())) {
                jgChangeRegistrationTransfer.setExecuteSequence(jgChangeRegistrationTransfer.getExecuteSequence() + "," + role);
            } else {
                jgChangeRegistrationTransfer.setExecuteSequence(role);
            }
            if ("0".equals(operate)) {
                // 通过操作
                jgChangeRegistrationTransfer.setAuditStatus(WorkFlowStatusEnum.getMessage(taskCode).getPass());
                jgChangeRegistrationTransfer.setStatus(WorkFlowStatusEnum.getMessage(taskCode).getPass());
            } else {
                // 驳回操作
                jgChangeRegistrationTransfer.setAuditStatus(WorkFlowStatusEnum.getMessage(taskCode).getPass());
                jgChangeRegistrationTransfer.setStatus(WorkFlowStatusEnum.getMessage(taskCode).getReject());
                jgChangeRegistrationTransfer.setPromoter("");
            }

        } else {
            jgChangeRegistrationTransfer.setAuditStatus(taskCode);
            jgChangeRegistrationTransfer.setStatus(taskCode);
            //流程执行完成后，更新设备使用信息
            this.updateByFlowEnd(sequenceNbr.toString(), jgChangeRegistrationTransfer.getSupervisoryCode());
        }
        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) {
        //查询修改后的新数据
        JgRegistrationHistory newData = jgRegistrationHistoryService.getDteailByRecord(record, sequenceNbr);
        //查询设备旧数据
        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;
    }
}