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.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aspose.words.SaveFormat;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.amos.boot.module.jg.api.dto.ByteArrayMultipartFile;
import com.yeejoin.amos.boot.module.jg.api.dto.JgChangeRegistrationUnitDto;
import com.yeejoin.amos.boot.module.jg.api.entity.*;
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.IJgChangeRegistrationUnitService;
import com.yeejoin.amos.boot.module.jg.biz.feign.TzsServiceFeignClient;
import com.yeejoin.amos.boot.module.jg.biz.service.ICommonService;
import com.yeejoin.amos.boot.module.jg.biz.utils.ImageUtils;
import com.yeejoin.amos.boot.module.jg.biz.utils.WordTemplateUtils;
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.mapper.*;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.feign.systemctl.Systemctl;
import com.yeejoin.amos.feign.workflow.Workflow;
import com.yeejoin.amos.feign.workflow.model.ActWorkflowBatchDTO;
import com.yeejoin.amos.feign.workflow.model.ActWorkflowStartDTO;
import com.yeejoin.amos.feign.workflow.model.AjaxResult;
import com.yeejoin.amos.feign.workflow.model.TaskResultDTO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.rdbms.service.BaseService;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.time.LocalDate;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 单位变更登记服务实现类
 *
 * @author system_generator
 * @date 2023-12-22
 */
@Service
public class JgChangeRegistrationUnitServiceImpl extends BaseService<JgChangeRegistrationUnitDto,JgChangeRegistrationUnit,JgChangeRegistrationUnitMapper> implements IJgChangeRegistrationUnitService {
    private static final String SUBMIT_TYPE_FLOW = "1";
    private static final String PROCESS_DEFINITION_KEY = "unitChange";
    private static final String TABLE_PAGE_ID = "1734141426742095873";



    @Autowired
    EquipmentCategoryMapper equipmentCategoryMapper;

    @Autowired
    JgChangeRegistrationUnitEqMapper JgChangeRegistrationUnitEqMapper;

    @Autowired
    private JgChangeRegistrationUnitMapper JgChangeRegistrationUnitMapper;
    //    @Autowired
//    private EquipmentCategoryServiceImpl equipmentCategoryService;
    @Autowired
    RegistrationInfoMapper tzsJgRegistrationInfoMapper;
    @Autowired
    OtherInfoMapper tzsJgOtherInfoMapper;
    @Autowired
    UseInfoMapper useInfoMapper;
    @Autowired
    TzsServiceFeignClient tzsServiceFeignClient;
    @Autowired
    SupervisoryCodeInfoMapper supervisoryCodeInfoMapper;

    @Autowired
    WorkFlowFeignService workFlowFeginService;

    @Autowired
    private JgRegistrationHistoryMapper jgRegistrationHistoryMapper;

    @Autowired
    private IdxBizJgRegisterInfoMapper idxBizJgRegisterInfoMapper;

    //改造登记关系表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 IdxBizJgUseInfoServiceImpl idxBizJgUseInfoService;
    @Autowired
    private IdxBizJgRegisterInfoServiceImpl idxBizJgRegisterInfoService;
    @Autowired
    private IdxBizJgFactoryInfoServiceImpl idxBizJgFactoryInfoService;

    @Autowired
    ICommonService commonService;




    public static byte[] file2byte(File file) {
        try {
            FileInputStream in = new FileInputStream(file);
            //当文件没有结束时，每次读取一个字节显示
            byte[] data = new byte[in.available()];
            in.read(data);
            in.close();
            return data;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 根据sequenceNbr查询
     *
     * @param sequenceNbr 主键
     * @return 单位变更
     */
    @Override
    public Map<String, Map<String, Object>> queryBySequenceNbr(Long sequenceNbr) {
        // 变更单位信息
        JgChangeRegistrationUnit notice = JgChangeRegistrationUnitMapper.selectById(sequenceNbr);
        if (Objects.isNull(notice)) {
            return null;
        }
        Map<String, Object> changeInfo = BeanUtil.beanToMap(notice);

        if(!ValidationUtil.isEmpty(notice.getReceiveOrgCode()) && !ValidationUtil.isEmpty(notice.getReceiveOrgName())) {
            changeInfo.put("receiveOrgCode", notice.getReceiveOrgCode() + "_" + notice.getReceiveOrgName());
        }
        if(!ValidationUtil.isEmpty(notice.getUseUnitCreditCode()) && !ValidationUtil.isEmpty(notice.getUseUnitName())) {
            changeInfo.put("useUnitCreditCode", notice.getUseUnitCreditCode() + "_" + notice.getUseUnitName());
        }
        if(!ValidationUtil.isEmpty(notice.getNewUseUnitCreditCode()) && !ValidationUtil.isEmpty(notice.getNewUseUnitName())) {
            changeInfo.put("newUseUnitCreditCode", notice.getNewUseUnitCreditCode() + "_" + notice.getNewUseUnitName());
        }
        changeInfo.put("changeCertificateList", notice.getChangeCertificate());

        String[] fields = {"productPhoto", "designDoc", "designStandard", "factoryStandard",
                "productQualityYieldProve", "insUseMaintainExplain", "inspectReport",
                "proxyStatementAttachment", "installContractAttachment", "changeCertificateList"};

        // 设备信息
        List<Map<String, Object>> equipmentInfos = JgChangeRegistrationUnitMapper.queryEquipInformation(sequenceNbr);

        for (String s:fields) {
            if(changeInfo.containsKey(s)) {
                changeInfo.put(s, JSON.parseArray(changeInfo.get(s).toString()));
            }
            if(equipmentInfos.get(0).containsKey(s)) {
                equipmentInfos.get(0).put(s, JSON.parseArray(equipmentInfos.get(0).get(s).toString()));
            }
        }

        Map<String, Object> newMap = new HashMap<>();
        newMap.putAll(changeInfo);
        newMap.putAll(equipmentInfos.get(0));

        return new HashMap<String, Map<String, Object>>() {{
            this.put("changeRegisInfo", newMap);
        }};
    }

    /**
     * 更新单位变更
     *
     * @param noticeDto 单位变更
     */
    @SuppressWarnings({"rawtypes", "Duplicates"})
    public JgChangeRegistrationUnitDto updateInstallationNotice(String submitType, JgChangeRegistrationUnitDto noticeDto, String op) {
        if (Objects.isNull(noticeDto) || StringUtils.isEmpty(submitType)) {
            throw new IllegalArgumentException("参数不能为空");
        }
        String[] taskName = new String[]{"流程结束"};
        // 字段转换
        this.convertField(noticeDto);
        ArrayList<String> roleListFirst = new ArrayList<>();
        ArrayList<String> roleListSecond = new ArrayList<>();
        if (SUBMIT_TYPE_FLOW.equals(submitType)) {
            AjaxResult ajaxResult;
            // 发起流程
            if (!StringUtils.hasText(noticeDto.getInstanceId())) {
                ActWorkflowStartDTO dto = new ActWorkflowStartDTO();
                dto.setProcessDefinitionKey(PROCESS_DEFINITION_KEY);
                dto.setBusinessKey("1");
                try {
                    ajaxResult = Workflow.taskClient.startByVariable(dto);
                    String instanceId = ((Map) ajaxResult.get("data")).get("id").toString();
                    noticeDto.setInstanceId(instanceId);
                    // 查询下节点任务
                    getNext(roleListFirst, instanceId,taskName);
                    noticeDto.setInstanceStatus(String.join(",", roleListFirst));
                } catch (Exception e) {
                    log.error("提交失败：{}", e);
                }
            }

            JgChangeRegistrationUnit notice = new JgChangeRegistrationUnit();
            BeanUtils.copyProperties(noticeDto,notice);

            boolean submit = submit(notice, op);

            if(submit) {
                // 查询下节点任务
                getNext(roleListSecond, notice.getInstanceId(),taskName);
                notice.setStatus(taskName[0]);
                if (!ObjectUtils.isEmpty(notice.getInstanceStatus())) {
                    notice.setInstanceStatus(notice.getInstanceStatus() + "," + roleListSecond);
                } else {
                    notice.setInstanceStatus(String.join(",", roleListSecond));
                }
                notice.setPromoter(RequestContext.getExeUserId());
                notice.setNextExecutorIds(String.join(",", roleListSecond));
                notice.setStatus(WorkFlowStatusEnum.UNITCHANGE_RECEIVE.getPass());
                JgChangeRegistrationUnitMapper.updateById(notice);
            }
        } else {
            JgChangeRegistrationUnit bean = new JgChangeRegistrationUnit();
            BeanUtils.copyProperties(noticeDto, bean);
            JgChangeRegistrationUnitMapper.updateById(bean);
        }
        return noticeDto;
    }



    /**
     * 分页查询
     *
     * @param page  分页对象
     * @param model 查询参数
     * @param type  类型：enterprise-企业端、supervision-监管端
     * @return 单位变更列表
     */
    @Override
    public Page<JgChangeRegistrationUnitDto> queryForJgChangeRegistrationUnitPage(Page<JgChangeRegistrationUnit> page, JgChangeRegistrationUnitDto model, String type , ReginParams reginParams) {

        String orgCode;
        orgCode = reginParams.getCompany().getCompanyCode();

        Page<JgChangeRegistrationUnit> noticePage = JgChangeRegistrationUnitMapper.queryForPage(page, model, type, orgCode, model.getRoleIds());

        Page<JgChangeRegistrationUnitDto> noticeDtoPage = new Page<>();
        BeanUtils.copyProperties(noticePage, noticeDtoPage, "records");
        List<JgChangeRegistrationUnitDto> records = noticePage.getRecords().stream().map(notice -> {
            JgChangeRegistrationUnitDto noticeDto = new JgChangeRegistrationUnitDto();
            BeanUtils.copyProperties(notice, noticeDto);
            return noticeDto;
        }).collect(java.util.stream.Collectors.toList());
        noticeDtoPage.setRecords(records);

        return noticeDtoPage;
    }

    /**
     * 列表查询 示例
     */
    public List<JgChangeRegistrationUnitDto> queryForJgChangeRegistrationUnitList() {
        return this.queryForList("", false);
    }

    /**
     * 批量删除
     *
     * @param sequenceNbrs 主键
     * @return 是否删除成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteForBatch(Long[] sequenceNbrs) {
        if (Objects.isNull(sequenceNbrs) || sequenceNbrs.length == 0) {
            return false;
        }
        Collection<JgChangeRegistrationUnit> JgChangeRegistrationUnits = this.listByIds(Arrays.asList(sequenceNbrs));
        JgChangeRegistrationUnits.forEach(notice -> {
            notice.setIsDelete(true);
        });
        return this.updateBatchById(JgChangeRegistrationUnits);
    }


    @Override
    @SuppressWarnings({"Duplicates", "rawtypes"})
    @Transactional(rollbackFor = Exception.class)
    public void saveNotice(String submitType, JgChangeRegistrationUnitDto model, ReginParams reginParams) {
        String[] taskName = new String[]{"流程结束"};

        // 字段转换
        convertField(model);

        // 获取单位变更设备列表
        List<Map<String, Object>> deviceList = model.getDeviceList();
        if (CollectionUtils.isEmpty(deviceList)) {
            return;
        }

        // 获取单位变更单号
        ResponseModel<List<String>> listResponseModel = tzsServiceFeignClient.applicationFormCode(ApplicationFormTypeEnum.DWBG.getCode(), deviceList.size());
        List<String> applyNoList = listResponseModel.getResult();
        if (CollectionUtils.isEmpty(applyNoList)) {
            log.error("生成申请变更单位编失败");
            return;
        }

        ArrayList<String> roleListFirst = new ArrayList<>();
        ArrayList<String> roleListSecond = new ArrayList<>();
        // 判断当前是否为提交
        List<String> instanceIdList = new ArrayList<>();
        if (SUBMIT_TYPE_FLOW.equals(submitType)) {
            // 发起流程
            // ActWorkflowStartDTO dto = new ActWorkflowStartDTO();
            ActWorkflowBatchDTO actWorkflowBatchDTO = new ActWorkflowBatchDTO();
            List<ActWorkflowStartDTO> list = new ArrayList<>();
            for (int i = 0; i<deviceList.size() ; i++
            ) {
                ActWorkflowStartDTO dto = new ActWorkflowStartDTO();
                dto.setProcessDefinitionKey(PROCESS_DEFINITION_KEY);
                dto.setBusinessKey(String.valueOf(i));
                // dto.setCompleteFirstTask(true);
                list.add(dto);
            }
            actWorkflowBatchDTO.setProcess(list);

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

        List<JgChangeRegistrationUnit> list = new ArrayList<>();
        List<JgChangeRegistrationUnitEq> equipList = new ArrayList<>();
        deviceList.forEach(obj -> {
            JgChangeRegistrationUnitEq jgRelationEquip = new JgChangeRegistrationUnitEq();
            JgChangeRegistrationUnit dto = new JgChangeRegistrationUnit();
            BeanUtils.copyProperties(model, dto);
            int i = deviceList.indexOf(obj);
            String applyNo = applyNoList.get(i);
            dto.setApplyNo(applyNo);
            dto.setApplyDate(new Date());
            if(SUBMIT_TYPE_FLOW.equals(submitType)) {
                dto.setNextExecutorIds(String.join(",", roleListSecond));
                dto.setInstanceStatus(String.join(",", roleListFirst));
                dto.setPromoter(reginParams.getUserModel().getUserId());
                dto.setStatus(taskName[0]);
            }
            dto.setNewUseUnitName(reginParams.getCompany().getCompanyName());
            dto.setNewUseUnitCreditCode(reginParams.getCompany().getCompanyCode());
            dto.setEquType((String.valueOf(obj.get("EQU_CATEGORY"))));
            dto.setProductNameB((String.valueOf(obj.get("PRODUCT_NAME"))));
            dto.setEquCodeB((String.valueOf(obj.get("EQU_CODE"))));
            dto.setUseInnerCode(ValidationUtil.isEmpty(obj.get("USE_INNER_CODE")) ? "" :   String.valueOf(obj.get("USE_INNER_CODE")));
            dto.setEquAddress((String.valueOf(obj.get("ADDRESS"))));

            jgRelationEquip.setEquId(String.valueOf(obj.get("SEQUENCE_NBR")));
            jgRelationEquip.setUnitChangeRegistrationId(applyNo);
            if (!CollectionUtils.isEmpty(instanceIdList)) {
                dto.setInstanceId(instanceIdList.get(i));
                dto.setStatus(WorkFlowStatusEnum.UNITCHANGE_RECEIVE.getPass());
            } else {
                dto.setStatus(WorkFlowStatusEnum.UNITCHANGE_SUBMIT.getPass());
            }
            list.add(dto);
            equipList.add(jgRelationEquip);
        });

        JgChangeRegistrationUnitMapper.insertBatchSomeColumn(list);

        List<JgChangeRegistrationUnitEq> jgRelationEquipList = equipList.stream().map(jgRelationEquip -> {
            List<JgChangeRegistrationUnit> collect = list.stream().filter(JgChangeRegistrationUnit -> jgRelationEquip.getUnitChangeRegistrationId().equals(JgChangeRegistrationUnit.getApplyNo())).collect(Collectors.toList());
            Long sequenceNbr = collect.get(0).getSequenceNbr();
            insertOrUpdateHis(JSON.parseObject(JSONObject.toJSONString(collect.get(0))), jgRelationEquip.getEquId());
            return jgRelationEquip.setUnitChangeRegistrationId(String.valueOf(sequenceNbr));
        }).collect(Collectors.toList());

        JgChangeRegistrationUnitEqMapper.insertBatchSomeColumn(jgRelationEquipList);

    }

    void getNext(ArrayList<String> roleListFirst, String instanceId, String[] taskName) {
        AjaxResult aj = Workflow.taskClient.getTaskNoAuth(instanceId);
        JSONObject taskNoAuth = JSON.parseObject(JSON.toJSONString(aj.get("data")));
        if (!ObjectUtils.isEmpty(taskNoAuth)) {
            String nextTaskId = taskNoAuth.getString("id");
            FeignClientResult<JSONObject> nodeInfo = workFlowFeginService.getNodeInfo(nextTaskId);
            JSONObject result = nodeInfo.getResult();
            Map<String, Object> taskInfo = (Map<String, Object>) result.get("taskInfo");
            taskName[0] = 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")) {
                    roleListFirst.add(((Map) datum).get("groupId").toString());
                }
            }
        }
    }

    private void convertField(JgChangeRegistrationUnitDto model) {
        // 处理图片
        if(!ValidationUtil.isEmpty(model.getChangeCertificateList())) {
            model.setChangeCertificate(JSON.toJSONString(model.getChangeCertificateList()));
        }


        // 分割单位
        String useUnitId = model.getUseUnitCreditCode();
        if (!ObjectUtils.isEmpty(useUnitId)) {
            String[] useUnitList = useUnitId.split("_");
            if (useUnitList.length > 1) {
                model.setUseUnitCreditCode(useUnitList[0]);
                model.setUseUnitName(useUnitList[1]);
            }
        }

        String newUseUnitId = model.getNewUseUnitCreditCode();
        if (!ObjectUtils.isEmpty(newUseUnitId)) {
            String[] newUseUnitList = newUseUnitId.split("_");
            if (newUseUnitList.length > 1) {
                model.setNewUseUnitCreditCode(newUseUnitList[0]);
                model.setNewUseUnitName(newUseUnitList[1]);
            }
        }

        String receiveOrgCode = model.getReceiveOrgCode();
        if (!ObjectUtils.isEmpty(receiveOrgCode)) {
            String[] receiveOrgCodeList = receiveOrgCode.split("_");
            if (receiveOrgCodeList.length > 1) {
                model.setReceiveOrgCode(receiveOrgCodeList[0]);
                model.setReceiveOrgName(receiveOrgCodeList[1]);
            }
        }

    }

    private String convertImageUrl(List<Map<String, String>> urlList) {
        String urls = "";
        if (!CollectionUtils.isEmpty(urlList)) {
            urls = urlList.stream().map(map -> map.get("url")).collect(Collectors.joining(","));
        }
        return urls;
    }

    public void insertOrUpdateHis(JSONObject map, String equipId) {
        JgRegistrationHistory jgRegistrationHistory = new JgRegistrationHistory();
        //使用登记编号
        jgRegistrationHistory.setUseRegistrationCode(idxBizJgRegisterInfoMapper.getUseOrgCodeByEquip(equipId));
        //登记类别
        jgRegistrationHistory.setRegistrationClass("单位变更登记");
        //设备id
        jgRegistrationHistory.setEquId(equipId);
        //修改数据
        jgRegistrationHistory.setChangeData(JSONObject.toJSONString(map));
        //设备监管码
        LambdaQueryWrapper<OtherInfo> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(OtherInfo::getRecord,equipId);
        OtherInfo tzsJgOtherInfo = tzsJgOtherInfoMapper.selectOne(queryWrapper1);
        jgRegistrationHistory.setSupervisoryCode(tzsJgOtherInfo.getSupervisoryCode());
        if (map.containsKey("type") && "edit".equals(String.valueOf(map.get("type")))) {
            jgRegistrationHistory.setSequenceNbr(jgRegistrationHistoryMapper.getSequenceNbrByEquidAndDocumentId(equipId, String.valueOf(map.get("sequenceNbr"))));
            jgRegistrationHistoryMapper.updateById(jgRegistrationHistory);
        } else {
            //当前单据id
             jgRegistrationHistory.setCurrentDocumentId(map.get("applyNo").toString());
            jgRegistrationHistoryMapper.insert(jgRegistrationHistory);
        }
    }

    public boolean submit(JgChangeRegistrationUnit notice,String op) {

        AjaxResult ajaxResult = Workflow.taskClient.getTask(notice.getInstanceId());
        JSONObject dataObject = JSON.parseObject(JSON.toJSONString(ajaxResult.get("data")));
        String taskId = dataObject.getString("id");
        //组装信息
        TaskResultDTO dto = new TaskResultDTO();
        dto.setResultCode("approvalStatus");
        dto.setTaskId(taskId);
        if(!ValidationUtil.isEmpty(notice.getProcessAdvice())) {
            dto.setComment(notice.getProcessAdvice());
        }
        HashMap<String, Object> map = new HashMap<>();
        if(notice.getStatus().equals(WorkFlowStatusEnum.UNIT_RENAME_SUBMIT.getReject()) || notice.getStatus().equals(WorkFlowStatusEnum.UNIT_RENAME_SUBMIT.getRollBack()) ) {
            map.put("approvalStatus", "提交");
        } else {
            map.put("approvalStatus", op);
        }
        dto.setVariable(map);
        //执行流程
        AjaxResult ajaxResult1 = null;
        try {
            ajaxResult1 = Workflow.taskClient.completeByTask(taskId, dto);
            if (ajaxResult1.get("code").equals(200)) {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            log.error("提交失败：{}", e);
            return false;
        }
    }

    public void cancel(JgChangeRegistrationUnitDto noticeDto) {
        String[] taskName = new String[]{"流程结束"};
        FeignClientResult ajaxResult = Workflow.taskV2Client.rollBack(noticeDto.getInstanceId());
        JgChangeRegistrationUnit JgChangeRegistrationUnit = this.baseMapper.selectById(noticeDto.getSequenceNbr());
        ArrayList<String> roleList = new ArrayList<>();
        if(ajaxResult.getStatus() == 200) {
            getNext(roleList, noticeDto.getInstanceId(),taskName);
            JgChangeRegistrationUnit.setStatus(WorkFlowStatusEnum.getMessage(taskName[0]).getRollBack());
            JgChangeRegistrationUnit.setPromoter("");
            JgChangeRegistrationUnit.setNextExecutorIds(String.join(",", roleList));
            JgChangeRegistrationUnitMapper.updateById(JgChangeRegistrationUnit);
        }
    }

    @Transactional
    public void accept(JgChangeRegistrationUnitDto dto,String op) {
        String[] taskName = new String[]{"已完成"};
        String userId = RequestContext.getExeUserId();
        JgChangeRegistrationUnit jgChangeRegistrationUnit = this.JgChangeRegistrationUnitMapper.selectById(dto.getSequenceNbr());
        jgChangeRegistrationUnit.setProcessAdvice(dto.getProcessAdvice());

        ArrayList<String> roleList = new ArrayList<>();
        boolean submit = submit(jgChangeRegistrationUnit, op);
        if(submit) {
            getNext(roleList, dto.getInstanceId(),taskName);
            jgChangeRegistrationUnit.setStatus(taskName[0]);
            if("0".equals(op)) {
                if(roleList.size() == 0) {
                    jgChangeRegistrationUnit.setStatus(taskName[0]);
                    jgChangeRegistrationUnit.setAuditPassDate(new Date());

                    // 生成新的使用登记编号，使用登记证  修改设备的使用登记信息表，使用单位名称，使用单位统一信用代码，使用登记证编号，更新ES
                    LambdaQueryWrapper<JgChangeRegistrationUnitEq> queryWrapper = new LambdaQueryWrapper<>();
                    queryWrapper.eq(JgChangeRegistrationUnitEq::getUnitChangeRegistrationId,dto.getSequenceNbr());
                    JgChangeRegistrationUnitEq jgChangeRegistrationUnitEq = JgChangeRegistrationUnitEqMapper.selectOne(queryWrapper);
                    String equipId = jgChangeRegistrationUnitEq.getEquId();
                    LambdaQueryWrapper<OtherInfo> queryWrapper1 = new LambdaQueryWrapper<>();
                    queryWrapper1.eq(OtherInfo::getRecord,jgChangeRegistrationUnitEq.getEquId());
                    OtherInfo tzsJgOtherInfo = tzsJgOtherInfoMapper.selectOne(queryWrapper1);

                    LambdaQueryWrapper<UseInfo> queryWrapper2 = new LambdaQueryWrapper<>();
                    queryWrapper2.eq(UseInfo::getRecord,jgChangeRegistrationUnitEq.getEquId());
                    UseInfo useInfo = useInfoMapper.selectOne(queryWrapper2);
                    useInfo.setUseUnitName(jgChangeRegistrationUnit.getNewUseUnitName());
                    useInfo.setUseUnitCreditCode(jgChangeRegistrationUnit.getNewUseUnitCreditCode());


                    String code = getCode(tzsJgOtherInfo.getSupervisoryCode());
                    if(ValidationUtil.isEmpty(code)) {
                        log.error("生成新的使用登记证编号失败");
                        return;
                    }

                    jgChangeRegistrationUnit.setUseRegistCode(code);
                    //更新使用注册登记证编号
                    idxBizJgRegisterInfoMapper.updateUseOrgCodeByEquip(equipId, code);
                    useInfoMapper.updateById(useInfo);
                    //es中的编号信息
                    Map<String, Map<String, Object>> resultMap = new HashMap<>();
                    Map<String, Object> map1 = new HashMap<>();
                    map1.put("USE_ORG_CODE", code);
                    map1.put("USE_UNIT_CREDIT_CODE",jgChangeRegistrationUnit.getNewUseUnitCreditCode());
                    map1.put("USE_UNIT_NAME",jgChangeRegistrationUnit.getNewUseUnitName());
                    resultMap.put(equipId, map1);
                    tzsServiceFeignClient.commonUpdateEsDataByIds(resultMap);
                    //修改各类告知列表，置为废弃
                    this.updataInvalidStatusByHistory(jgChangeRegistrationUnitEq.getEquId(), jgChangeRegistrationUnit.getApplyNo());

//                    TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
//                        @Override
//                        public void afterCommit() {
//                            generateInstallationNoticeReport(JgChangeRegistrationUnit.getSequenceNbr());
//                        }
//                    });
                } else {
                    jgChangeRegistrationUnit.setNextExecutorIds(String.join(",", roleList));
                    if (!ObjectUtils.isEmpty(jgChangeRegistrationUnit.getInstanceStatus())) {
                        jgChangeRegistrationUnit.setInstanceStatus(jgChangeRegistrationUnit.getInstanceStatus() + "," + String.join(",", roleList));
                    } else {
                        jgChangeRegistrationUnit.setInstanceStatus(String.join(",", roleList));
                    }
                    jgChangeRegistrationUnit.setPromoter(userId);
                    jgChangeRegistrationUnit.setStatus(WorkFlowStatusEnum.getMessage(taskName[0]).getPass());
                }
            } else {
                jgChangeRegistrationUnit.setPromoter("");
                jgChangeRegistrationUnit.setNextExecutorIds(String.join(",", roleList));
                jgChangeRegistrationUnit.setStatus(WorkFlowStatusEnum.getMessage(taskName[0]).getReject());
            }
            JgChangeRegistrationUnitMapper.updateById(jgChangeRegistrationUnit);
        }
    }

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


    public String getCode(String supervisoryCode) {
        if (!ObjectUtils.isEmpty(supervisoryCode) && supervisoryCode.length() > 5) {
            String name = EquipTypeEnum.getMessage(supervisoryCode.substring(1, 2));
            String type = supervisoryCode.substring(2, 4);
            String city = supervisoryCode.substring(0, 1);
            ResponseModel<String> stringResponseModel = tzsServiceFeignClient.useRegistrationCode(name + type + "陕" + city);
            return stringResponseModel.getResult();
        }
        return null;
    }


    /**
     * 导出使用登记证
     *
     * @param sequenceNbr
     */
    public void exportUseRegistrationCertificate(String sequenceNbr , HttpServletResponse response) {
        Map<String, Object> exportParamsMap = new HashMap<>();
        //查询移装变更详情
        JgChangeRegistrationUnit transfer = this.getById(sequenceNbr);
        LambdaQueryWrapper<JgChangeRegistrationUnitEq> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(JgChangeRegistrationUnitEq::getUnitChangeRegistrationId,transfer.getSequenceNbr());
        JgChangeRegistrationUnitEq jgChangeRegistrationUnitEq = JgChangeRegistrationUnitEqMapper.selectOne(queryWrapper);
        if (ValidationUtil.isEmpty(transfer) || ValidationUtil.isEmpty(jgChangeRegistrationUnitEq)) {
            throw new BadRequest("使用登记证导出失败,请稍后重试!");
        }
        //是否废弃
        exportParamsMap.put("isInvalid",  ValidationUtil.isEmpty(jgChangeRegistrationUnitEq.getIsInvalid()) ? "0" : jgChangeRegistrationUnitEq.getIsInvalid());
        //登记机关
        exportParamsMap.put("receiveOrgName", transfer.getReceiveOrgName());
        //使用登记证编号
        exportParamsMap.put("useRegistrationCode", ValidationUtil.isEmpty(transfer.getUseRegistCode()) ? "" : transfer.getUseRegistCode());
        //使用单位名称
        exportParamsMap.put("useUnitName", transfer.getUseUnitName());
        //监管码
        LambdaQueryWrapper<OtherInfo> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(OtherInfo::getRecord,jgChangeRegistrationUnitEq.getEquId());
        OtherInfo tzsJgOtherInfo = tzsJgOtherInfoMapper.selectOne(queryWrapper1);
        exportParamsMap.put("supervisoryCode", tzsJgOtherInfo.getSupervisoryCode());
        //发证日期（当前时间）
        LocalDate today = LocalDate.now();
        exportParamsMap.put("giveOutYear", today.getYear());
        exportParamsMap.put("giveOutMonth", today.getMonthValue());
        exportParamsMap.put("giveOutDay", today.getDayOfMonth());
        //设备使用地址


        //查询设备注册信息
        IdxBizJgRegisterInfo registerInfo = idxBizJgRegisterInfoService.getOne(new QueryWrapper<IdxBizJgRegisterInfo>().eq("RECORD", jgChangeRegistrationUnitEq.getEquId()));
        if(!ValidationUtil.isEmpty(registerInfo)){
            //设备种类、类别、品种
            String equList = registerInfo.getEquList();//设备种类
            String equCategory = registerInfo.getEquCategory();//设备类别
            String equDefine = registerInfo.getEquDefine();//设备品种
            List<EquipmentCategory> categoryList0 = commonService.getEquipmentCategoryList(equList, null);
            List<EquipmentCategory> categoryList1 = commonService.getEquipmentCategoryList(equCategory, null);
            if (org.apache.commons.collections.CollectionUtils.isNotEmpty(categoryList1)) {
                exportParamsMap.put("equList", categoryList0.get(0).getName());
            }
            if (org.apache.commons.collections.CollectionUtils.isNotEmpty(categoryList1)) {
                exportParamsMap.put("equCategory", categoryList1.get(0).getName());
            }
            if(!ValidationUtil.isEmpty(equDefine)) {
                List<EquipmentCategory> categoryList2 = commonService.getEquipmentCategoryList(equDefine, null);
                if (org.apache.commons.collections.CollectionUtils.isNotEmpty(categoryList2)) {
                    exportParamsMap.put("equDefine", categoryList2.get(0).getName());
                }
            }
            //设备代码
            exportParamsMap.put("equCode", registerInfo.getEquCode());
        }

        //单位内部编码
        IdxBizJgUseInfo useInfo = idxBizJgUseInfoService.getOneData(jgChangeRegistrationUnitEq.getEquId());
        if(!ValidationUtil.isEmpty(useInfo)){
            exportParamsMap.put("useInnerCode", useInfo.getUseInnerCode());

            String fullAddress="";
            String province = ValidationUtil.isEmpty(useInfo.getProvinceName()) ? "" :  useInfo.getProvinceName();
            String city =  ValidationUtil.isEmpty(useInfo.getCityName()) ? "" :  useInfo.getCityName();
            String county = ValidationUtil.isEmpty(useInfo.getCountyName()) ? "" :  useInfo.getCountyName();
            String street = ValidationUtil.isEmpty(useInfo.getStreetName()) ? "" :  useInfo.getStreetName();
            String address = ValidationUtil.isEmpty(useInfo.getAddress()) ? "" :  useInfo.getAddress();
            fullAddress = province + city + county + street + address;
            exportParamsMap.put("fullAddress", fullAddress);
        }
        IdxBizJgFactoryInfo factoryInfo = idxBizJgFactoryInfoService.getOneData(jgChangeRegistrationUnitEq.getEquId());
        //产品编号(出厂编号)
        if(!ValidationUtil.isEmpty(factoryInfo)){
            exportParamsMap.put("factoryNum", factoryInfo.getFactoryNum());
        }
        //调用生成使用登记证
       commonService.generateCertificateReport(exportParamsMap, response);
    }

}