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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aspose.words.SaveFormat;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yeejoin.amos.boot.biz.common.utils.DateUtils;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.module.jg.api.dto.ByteArrayMultipartFile;
import com.yeejoin.amos.boot.module.jg.api.dto.JgInstallationNoticeDto;
import com.yeejoin.amos.boot.module.jg.api.entity.JgInstallationNotice;
import com.yeejoin.amos.boot.module.jg.api.entity.JgInstallationNoticeEq;
import com.yeejoin.amos.boot.module.jg.api.enums.FlowStatusEnum;
import com.yeejoin.amos.boot.module.jg.api.mapper.JgInstallationNoticeEqMapper;
import com.yeejoin.amos.boot.module.jg.api.mapper.JgInstallationNoticeMapper;
import com.yeejoin.amos.boot.module.jg.api.service.IJgInstallationNoticeService;
import com.yeejoin.amos.boot.module.jg.biz.feign.TzsServiceFeignClient;
import com.yeejoin.amos.boot.module.ymt.api.entity.OtherInfo;
import com.yeejoin.amos.boot.module.ymt.api.entity.RegistrationInfo;
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.ymt.api.enums.ApplicationFormTypeEnum;
import com.yeejoin.amos.boot.module.ymt.api.mapper.*;
import com.yeejoin.amos.boot.module.ymt.api.service.ICreateCodeService;
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.util.ObjectUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import org.typroject.tyboot.core.rdbms.service.BaseService;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.text.ParseException;

/**
 * 服务实现类
 *
 * @author system_generator
 * @date 2023-12-12
 */
@Service
public class JgInstallationNoticeServiceImpl extends BaseService<JgInstallationNoticeDto,JgInstallationNotice,JgInstallationNoticeMapper> implements IJgInstallationNoticeService {

    private static final String SUBMIT_TYPE_FLOW = "1";
    private static final String PROCESS_DEFINITION_KEY = "installationNotification";
    private static final String TABLE_PAGE_ID = "1734141426742095873";


    //西安行政区划code
    private static final String XIAN = "610100";

    //咸阳行政区划code
    private static final String XIAN_YANG = "610400";

    @Autowired
    EquipmentCategoryMapper equipmentCategoryMapper;

    @Autowired
    JgInstallationNoticeEqMapper jgInstallationNoticeEqMapper;

    @Autowired
    private JgInstallationNoticeMapper jgInstallationNoticeMapper;
    @Autowired
    private ICreateCodeService iCreateCodeService;
//    @Autowired
//    private EquipmentCategoryServiceImpl equipmentCategoryService;
    @Autowired
    RegistrationInfoMapper tzsJgRegistrationInfoMapper;
    @Autowired
    OtherInfoMapper tzsJgOtherInfoMapper;
    @Autowired
    TzsServiceFeignClient tzsServiceFeignClient;



    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) {
        // 安装告知信息
        JgInstallationNotice notice = jgInstallationNoticeMapper.selectById(sequenceNbr);
        if (Objects.isNull(notice)) {
            return null;
        }
        Map<String, Object> installationInfo = BeanUtil.beanToMap(notice);

        installationInfo.put("province", notice.getProvince() + "_" + notice.getProvinceName());
        installationInfo.put("city", notice.getCity() + "_" + notice.getCityName());
        installationInfo.put("county", notice.getCounty() + "_" + notice.getCountyName());
        installationInfo.put("useUnitCreditCode", notice.getUseUnitCreditCode() + "_" + notice.getUseUnitName());
        installationInfo.put("receiveOrgCreditCode", notice.getReceiveOrgCreditCode() + "_" + notice.getReceiveOrgName());
        installationInfo.put("inspectUnitId", notice.getInspectUnitId() + "_" + notice.getInspectUnitName());

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

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

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

        return new HashMap<String, Map<String, Object>>() {{
            this.put("installationInfo", installationInfo);
            this.put("equipmentInfo", equipmentInfos.get(0));
        }};
    }

    /**
     * 更新安装告知
     *
     * @param noticeDto 安装告知
     */
    @SuppressWarnings({"rawtypes", "Duplicates"})
    public JgInstallationNoticeDto updateInstallationNotice(JgInstallationNoticeDto noticeDto, String op) {
        if (Objects.isNull(noticeDto) || StringUtils.isEmpty(op)) {
            throw new IllegalArgumentException("参数不能为空");
        }

        // 字段转换
        this.convertField(noticeDto);

        AjaxResult ajaxResult;
        // 发起流程
        if (!StringUtils.hasText(noticeDto.getInstanceId())) {
            ActWorkflowStartDTO dto = new ActWorkflowStartDTO();
            dto.setProcessDefinitionKey("installationNotification");
            dto.setBusinessKey("1");
            try {
                ajaxResult = Workflow.taskClient.startByVariable(dto);
            } catch (Exception e) {
                log.error("提交失败：{}", e);
            }
        }

        ajaxResult = Workflow.taskClient.getTask(noticeDto.getInstanceId());
        JSONObject dataObject = JSON.parseObject(JSON.toJSONString(ajaxResult.get("data")));
        String taskId = dataObject.getString("id");
        //组装信息
        TaskResultDTO taskResultDTO = new TaskResultDTO();
        taskResultDTO.setResultCode("approvalStatus");
        taskResultDTO.setTaskId(taskId);
        taskResultDTO.setComment("提交流程");
        HashMap<String, Object> map = new HashMap<>();
        map.put("approvalStatus", op);
        taskResultDTO.setVariable(map);
        //执行流程
        AjaxResult ajaxResult1;
        try {
            ajaxResult1 = Workflow.taskClient.completeByTask(taskId, taskResultDTO);
            if (ajaxResult1.get("code").equals(200)) {
                noticeDto.setNoticeStatus(String.valueOf(FlowStatusEnum.TO_BE_PROCESSED.getCode()));
                JgInstallationNotice bean = new JgInstallationNotice();
                BeanUtils.copyProperties(noticeDto, bean);
                jgInstallationNoticeMapper.updateById(bean);
            }
        } catch (Exception e) {
            log.error("提交失败：{}", e);
        }

        return noticeDto;
    }



    /**
     * 分页查询
     *
     * @param page  分页对象
     * @param model 查询参数
     * @param type  类型：enterprise-企业端、supervision-监管端
     * @return 安装告知列表
     */
    @Override
    public Page<JgInstallationNoticeDto> queryForJgInstallationNoticePage(Page<JgInstallationNotice> page, JgInstallationNoticeDto model, String type) {
        Page<JgInstallationNotice> noticePage = jgInstallationNoticeMapper.queryForPage(page, model, type);

        // 将Page<JgInstallationNotice>转化为Page<JgInstallationNoticeDto>
        Page<JgInstallationNoticeDto> noticeDtoPage = new Page<>();
        BeanUtils.copyProperties(noticePage, noticeDtoPage, "records");
        List<JgInstallationNoticeDto> records = noticePage.getRecords().stream().map(notice -> {
            JgInstallationNoticeDto noticeDto = new JgInstallationNoticeDto();
            BeanUtils.copyProperties(notice, noticeDto);
            if (Objects.nonNull(notice.getNoticeStatus())) {
                String noticeStatusDesc = FlowStatusEnum.getNameByType(Long.valueOf(notice.getNoticeStatus()));
                noticeDto.setNoticeStatusDesc(noticeStatusDesc);
            }
            return noticeDto;
        }).collect(java.util.stream.Collectors.toList());
        noticeDtoPage.setRecords(records);

        return noticeDtoPage;
    }

    /**
     * 列表查询 示例
     */
    public List<JgInstallationNoticeDto> queryForJgInstallationNoticeList() {
        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<JgInstallationNotice> jgInstallationNotices = this.listByIds(Arrays.asList(sequenceNbrs));
        jgInstallationNotices.forEach(notice -> {
            if (StringUtils.hasText(notice.getInspectUnitId())) {
                throw new IllegalStateException("所选数据已存在流程，不能删除！");
            }
            notice.setIsDelete(true);
        });
        return this.updateBatchById(jgInstallationNotices);
    }

    /**
     * 打印安装告知单
     *
     * @param sequenceNbr 主键
     * @return pdf文件路径
     */
    @Override
    public String generateInstallationNoticeReport(Long sequenceNbr) {
        if (Objects.isNull(sequenceNbr)) {
            throw new IllegalArgumentException("参数不能为空");
        }

        JgInstallationNotice jgInstallationNotice = this.getById(sequenceNbr);
        List<Map<String, Object>> informationList = jgInstallationNoticeMapper.queryEquipInformation(sequenceNbr);
        if (Objects.isNull(jgInstallationNotice) || CollectionUtils.isEmpty(informationList)) {
            throw new IllegalArgumentException("安装告知单不存在");
        }
        Map<String, Object> installation = informationList.get(0);

        Function<String, String> getValue = key -> installation.getOrDefault(key, "").toString();

        // 组装模板变量
        Map<String, Object> placeholders = new HashMap<>();
        placeholders.put("sequenceNbr", getValue.apply("sequenceNbr"));
        placeholders.put("installUnitName", getValue.apply("installUnitName"));
        placeholders.put("applyNo", getValue.apply("applyNo"));
        placeholders.put("productName", getValue.apply("productName"));
        placeholders.put("equipType", getValue.apply("equType"));
        placeholders.put("equipCode", getValue.apply("equRegisterCode"));
        placeholders.put("produceCode", getValue.apply("produceCode")); // TODO: 制造编号
        placeholders.put("produceUnitName", getValue.apply("produceUnitName"));
        placeholders.put("produceLicenseNum", getValue.apply("produceLicenseNum"));
        placeholders.put("fullAddress", getValue.apply("provinceName") + getValue.apply("cityName") + getValue.apply("countyName") + getValue.apply("address"));
        placeholders.put("installStartDate", getValue.apply("installStartDate"));
        placeholders.put("installType", getValue.apply("installType")); // TODO: 施工类别
        placeholders.put("installLicenseNo", getValue.apply("installLicenseNo"));
        placeholders.put("installLicenseExpirationDate", getValue.apply("installLicenseExpirationDate"));
        placeholders.put("installLeaderName", getValue.apply("installLeaderName"));
        placeholders.put("installLeaderPhone", getValue.apply("installLeaderPhone"));
        placeholders.put("installUnitAddress", getValue.apply("installUnitAddress")); // TODO: 施工单位地址
        placeholders.put("useUnitName", getValue.apply("useUnitName"));
        placeholders.put("useUnitLeaderName", getValue.apply("safetyManager"));
        placeholders.put("useUnitLeaderPhone", getValue.apply("safetyManagerPhone"));
        placeholders.put("useUnitLeaderAddress", getValue.apply("useUnitProvinceName") + getValue.apply("useUnitCityName") + getValue.apply("useUnitCountyName") + getValue.apply("useUnitAddress"));
        // 生成二维码
        String qrCode = ImageUtils.generateQRCode(getValue.apply("applyNo"), 300, 300);
        placeholders.put("qrCode", qrCode);

        // word转pdf
        File pdfFile;
        try {
            pdfFile = this.wordToPdf("installation-notification-report.ftl", placeholders);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        // 上传pdf至文件服务器
        String url = this.uploadFile(pdfFile);

        // 删除临时文件
        try {
            Files.deleteIfExists(pdfFile.toPath());
        } catch (IOException e) {
            log.error("删除临时文件失败：{}", e);
        }

        // 更新到数据库
        jgInstallationNotice.setNoticeReportUrl(url);
        this.updateById(jgInstallationNotice);

        return url;
    }

    /**
     * word 转 pdf
     *
     * @param wordPath word文件路径
     */
    private File wordToPdf(String wordPath, Map<String, Object> placeholders) throws Exception {
        Assert.hasText(wordPath, "word文件路径不能为空");

        String tempFileName = "安装告知单_" + System.currentTimeMillis() + "_temp.pdf";

        WordTemplateUtils instance = WordTemplateUtils.getInstance();

        return instance.fillAndConvertDocFile(wordPath, tempFileName, placeholders, SaveFormat.PDF);
    }

    /**
     * 上传文件至文件服务器
     *
     * @param file 文件
     */
    private String uploadFile(File file) {
        Assert.notNull(file, "文件不能为空");

        MultipartFile multipartFile = new ByteArrayMultipartFile("file", "file.pdf", "application/pdf", file2byte(file));
        FeignClientResult<Map<String, String>> result = Systemctl.fileStorageClient.updateCommonFile(multipartFile);
        String urlString = "";
        if (result != null) {
            for (String s : result.getResult().keySet()) {
                urlString = s;
            }
        }
        return urlString;
    }

    @Override
    @SuppressWarnings({"Duplicates", "rawtypes"})
    @Transactional(rollbackFor = Exception.class)
    public void saveNotice(String submitType, Map<String, JgInstallationNoticeDto> jgInstallationNoticeDtoMap) {
        JgInstallationNoticeDto model = jgInstallationNoticeDtoMap.get(TABLE_PAGE_ID);
        // 字段转换
        convertField(model);

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

        // 获取告知单号
        List<String> applyNoList = iCreateCodeService.createApplicationFormCode(ApplicationFormTypeEnum.AZGZ.getCode(), deviceList.size());
        if (CollectionUtils.isEmpty(applyNoList)) {
            return;
        }

        // 判断当前是否为提交
        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));
                    instanceIdList.add(jsonObject.getString("id"));
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        List<JgInstallationNotice> list = new ArrayList<>();
        List<JgInstallationNoticeEq> equipList = new ArrayList<>();
        deviceList.forEach(obj -> {
            JgInstallationNoticeEq jgRelationEquip = new JgInstallationNoticeEq();
            JgInstallationNotice dto = new JgInstallationNotice();
            BeanUtils.copyProperties(model, dto);
            int i = deviceList.indexOf(obj);
            String applyNo = applyNoList.get(i);
            dto.setApplyNo(applyNo);
            jgRelationEquip.setEquId(String.valueOf(obj.get("SEQUENCE_NBR")));
            jgRelationEquip.setEquipTransferId(applyNo);
            if (!CollectionUtils.isEmpty(instanceIdList)) {
                dto.setInstanceId(instanceIdList.get(i));
                dto.setNoticeStatus(String.valueOf(FlowStatusEnum.TO_BE_PROCESSED.getCode()));
            } else {
                dto.setNoticeStatus(String.valueOf(FlowStatusEnum.TO_BE_SUBMITTED.getCode()));
            }
            list.add(dto);
            equipList.add(jgRelationEquip);
        });

        jgInstallationNoticeMapper.insertBatchSomeColumn(list);

        List<JgInstallationNoticeEq> jgRelationEquipList = equipList.stream().map(jgRelationEquip -> {
            List<JgInstallationNotice> collect = list.stream().filter(jgInstallationNotice -> jgRelationEquip.getEquipTransferId().equals(jgInstallationNotice.getApplyNo())).collect(Collectors.toList());
            Long sequenceNbr = collect.get(0).getSequenceNbr();
            return jgRelationEquip.setEquipTransferId(String.valueOf(sequenceNbr));
        }).collect(Collectors.toList());

        jgInstallationNoticeEqMapper.insertBatchSomeColumn(jgRelationEquipList);

    }

    private void convertField(JgInstallationNoticeDto model) {
        // 处理图片
        model.setProxyStatementAttachment(JSON.toJSONString(model.getProxyStatementAttachmentList()));
        model.setInstallContractAttachment(JSON.toJSONString(model.getInstallContractAttachmentList()));

        // 分割省市区字段
        String province = model.getProvince();
        if (!ObjectUtils.isEmpty(province)) {
            String[] provinceList = province.split("_");
            if (provinceList.length > 1) {
                model.setProvince(provinceList[0]);
                model.setProvinceName(provinceList[1]);
            }
        }

        String city = model.getCity();
        if (!ObjectUtils.isEmpty(city)) {
            String[] cityList = city.split("_");
            if (cityList.length > 1) {
                model.setCity(cityList[0]);
                model.setCityName(cityList[1]);
            }
        }

        String county = model.getCounty();
        if (!ObjectUtils.isEmpty(county)) {
            String[] countyList = county.split("_");
            if (countyList.length > 1) {
                model.setCounty(countyList[0]);
                model.setCountyName(countyList[1]);
            }
        }

        // 分割单位
        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 receiveOrgId = model.getReceiveOrgCreditCode();
        if (!ObjectUtils.isEmpty(receiveOrgId)) {
            String[] receiveOrgIdList = receiveOrgId.split("_");
            if (receiveOrgIdList.length > 1) {
                model.setReceiveOrgCreditCode(receiveOrgIdList[0]);
                model.setReceiveOrgName(receiveOrgIdList[1]);
            }
        }

        String inspectUnitId = model.getInspectUnitId();
        if (!ObjectUtils.isEmpty(inspectUnitId)) {
            String[] inspectUnitIdList = inspectUnitId.split("_");
            if (inspectUnitIdList.length > 1) {
                model.setInspectUnitId(inspectUnitIdList[0]);
                model.setInspectUnitName(inspectUnitIdList[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 boolean submit(JgInstallationNotice notice,String op) {

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

    public void cancel(JgInstallationNoticeDto noticeDto) {
        FeignClientResult ajaxResult = Workflow.taskV2Client.rollBack(noticeDto.getInstanceId());
        JgInstallationNotice jgInstallationNotice = this.baseMapper.selectById(noticeDto.getSequenceNbr());
        if(ajaxResult.getStatus() == 200) {
            jgInstallationNotice.setNoticeStatus(String.valueOf(FlowStatusEnum.TO_BE_SUBMITTED.getCode()));
            jgInstallationNotice.setStatus(String.valueOf(FlowStatusEnum.ROBACK.getCode()));
            jgInstallationNoticeMapper.updateById(jgInstallationNotice);
        }
    }

    public void accept(JgInstallationNoticeDto dto,String op) {

        JgInstallationNotice jgInstallationNotice = this.jgInstallationNoticeMapper.selectById(dto.getSequenceNbr());
        // 组装设备注册代码
        StringBuffer stringBuffer = new StringBuffer();
        String ym = null;
        try {
            ym = DateUtils.dateFormat(new Date(), DateUtils.DATE_PATTERN_MM);
        } catch (ParseException e) {
            log.error("日期转换失败：{}", e);
        }

        LambdaQueryWrapper<JgInstallationNoticeEq> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(JgInstallationNoticeEq::getEquipTransferId,dto.getSequenceNbr());
        JgInstallationNoticeEq jgRelationEquip = jgInstallationNoticeEqMapper.selectOne(queryWrapper);

        LambdaQueryWrapper<OtherInfo> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(OtherInfo::getRecord,jgRelationEquip.getEquId());
        OtherInfo tzsJgOtherInfo = tzsJgOtherInfoMapper.selectOne(queryWrapper1);

        LambdaQueryWrapper<RegistrationInfo> queryWrapper2 = new LambdaQueryWrapper<>();
        queryWrapper2.eq(RegistrationInfo::getRecord,jgRelationEquip.getEquId());
        RegistrationInfo tzsJgRegistrationInfo = tzsJgRegistrationInfoMapper.selectOne(queryWrapper2);

        stringBuffer.append(tzsJgRegistrationInfo.getEquCategory()).append(dto.getCity()).append(ym);
        String equCode = stringBuffer.toString();
        String deviceRegistrationCode = iCreateCodeService.createDeviceRegistrationCode(equCode);
        Map<String, Object> map = new HashMap<>();
        map.put("cityCode",dto.getCity());
        map.put("countyCode",dto.getCounty());
        map.put("equCategory",tzsJgRegistrationInfo.getEquCategory());
        map.put("isXiXian",dto.getIsXixian());
        Map<String, Object> mapCode;
        ResponseModel<Map<String, Object>> code = tzsServiceFeignClient.createCode(map);
        mapCode = code.getResult();


        boolean submit = submit(jgInstallationNotice, op);
        if(submit) {
            if("0".equals(op)) {
                jgInstallationNotice.setNoticeStatus(String.valueOf(FlowStatusEnum.HAVE_PROCESSED.getCode()));
                this.generateInstallationNoticeReport(jgInstallationNotice.getSequenceNbr());
            } else {
                jgInstallationNotice.setNoticeStatus(String.valueOf(FlowStatusEnum.TO_BE_SUBMITTED.getCode()));
                jgInstallationNotice.setStatus(String.valueOf(FlowStatusEnum.REJECTED.getCode()));
            }
            jgInstallationNotice.setEquRegisterCode(deviceRegistrationCode);
            jgInstallationNoticeMapper.updateById(jgInstallationNotice);

            // 更新其他业务表
            tzsJgOtherInfo.setCode96333(mapCode.get("code96333").toString());
            tzsJgOtherInfo.setSupervisoryCode(mapCode.get("superviseCode").toString());
            tzsJgRegistrationInfo.setEquCode(deviceRegistrationCode);
            tzsJgOtherInfoMapper.updateById(tzsJgOtherInfo);
            tzsJgRegistrationInfoMapper.updateById(tzsJgRegistrationInfo);
        }

//        // 组装监管码
//        String division = "";
//        if (((XIAN.equals(dto.getCity()) || XIAN_YANG.equals(dto.getCity())) && "1".equals(dto.getIsXixian()))) {
//            division = "X";
//        } else {
//            //生成监管码前缀
//            Map<String, Object> divisionMap = equipmentCategoryMapper.getAdministrativeDivision(EquipmentCategoryEnum.XZQH.getCode(), dto.getCounty());
//            division = ObjectUtils.isEmpty(divisionMap) ? equipmentCategoryMapper.getAdministrativeDivision(EquipmentCategoryEnum.XZQH.getCode(), dto.getCity()).get("code").toString() : divisionMap.get("code").toString();
//        }
//
//        // 组装96333码
//        String prefix = "";
//        if (((XIAN.equals(dto.getCity()) || XIAN_YANG.equals(dto.getCity())) && "1".equals(dto.getIsXixian()))) {
//            prefix = EquipmentCategoryEnum.XXCSM.getValue();
//        } else {
//            Map<String, Object> elevatorMap = equipmentCategoryMapper.getAdministrativeDivision(EquipmentCategoryEnum.XZQHDT.getCode(), dto.getCounty());
//            prefix = ObjectUtils.isEmpty(elevatorMap) ? equipmentCategoryMapper.getAdministrativeDivision(EquipmentCategoryEnum.XZQHDT.getCode(), dto.getCity()).get("code").toString() : elevatorMap.get("code").toString();
//        }
    }






}