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.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.amos.boot.biz.common.entity.DataDictionary;
import com.yeejoin.amos.boot.biz.common.service.IDataDictionaryService;
import com.yeejoin.amos.boot.biz.common.utils.DateUtils;
import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;
import com.yeejoin.amos.boot.module.jg.api.dto.ByteArrayMultipartFile;
import com.yeejoin.amos.boot.module.jg.api.dto.JgMaintainNoticeDto;
import com.yeejoin.amos.boot.module.jg.api.entity.JgMaintainNotice;
import com.yeejoin.amos.boot.module.jg.api.entity.JgMaintainNoticeEq;
import com.yeejoin.amos.boot.module.jg.api.mapper.JgMaintainNoticeEqMapper;
import com.yeejoin.amos.boot.module.jg.api.mapper.JgMaintainNoticeMapper;
import com.yeejoin.amos.boot.module.jg.api.service.IJgMaintainNoticeService;
import com.yeejoin.amos.boot.module.jg.biz.feign.TzsServiceFeignClient;
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.entity.RegistrationInfo;
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.EquipmentCategoryMapper;
import com.yeejoin.amos.boot.module.ymt.api.mapper.OtherInfoMapper;
import com.yeejoin.amos.boot.module.ymt.api.mapper.RegistrationInfoMapper;
import com.yeejoin.amos.boot.module.ymt.api.mapper.SupervisoryCodeInfoMapper;
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.stereotype.Service;
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 java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.text.ParseException;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 服务实现类
 *
 * @author system_generator
 * @date 2023-12-12
 */
@Service
public class JgMaintainNoticeServiceImpl extends BaseService<JgMaintainNoticeDto, JgMaintainNotice, JgMaintainNoticeMapper> implements IJgMaintainNoticeService {

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

    @Autowired
    EquipmentCategoryMapper equipmentCategoryMapper;
    @Autowired
    JgMaintainNoticeEqMapper jgMaintainNoticeEqMapper;
    @Autowired
    private JgMaintainNoticeMapper jgMaintainNoticeMapper;
    @Autowired
    private ICreateCodeService iCreateCodeService;
    @Autowired
    RegistrationInfoMapper tzsJgRegistrationInfoMapper;

    @Autowired
    OtherInfoMapper tzsJgOtherInfoMapper;

    @Autowired
    TzsServiceFeignClient tzsServiceFeignClient;

    @Autowired
    SupervisoryCodeInfoMapper supervisoryCodeInfoMapper;

    @Autowired
    IDataDictionaryService dataDictionaryService;

    @Autowired
    RedisUtils redisUtils;

    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) {
        // 维修告知信息
        JgMaintainNotice notice = jgMaintainNoticeMapper.selectById(sequenceNbr);
        if (Objects.isNull(notice))
            return null;
        Map<String, Object> maintainInfo = BeanUtil.beanToMap(notice);
        maintainInfo.put("powerOfAttorneyList", JSON.parseArray(notice.getPowerOfAttorney()));
        maintainInfo.put("constructionContractList", JSON.parseArray(notice.getConstructionContract()));
        maintainInfo.put("province", notice.getProvince() + "_" + notice.getProvinceName());
        maintainInfo.put("city", notice.getCity() + "_" + notice.getCityName());
        maintainInfo.put("constructionManagerId", notice.getConstructionManagerId() + "_" + notice.getConstructionManager());
        maintainInfo.put("county", notice.getCounty() + "_" + notice.getCountyName());
        maintainInfo.put("fullAddress", notice.getProvinceName() + notice.getCityName() + notice.getCounty() + notice.getStreetName() + notice.getAddress());
        maintainInfo.put("useUnitCreditCode", notice.getUseUnitCreditCode() + "_" + notice.getUseUnitName());
        maintainInfo.put("receiveOrgCode", notice.getReceiveOrgCode() + "_" + notice.getReceiveOrgName());
        if (!ValidationUtil.isEmpty(notice.getInspectionUnitCreditCode()) && !ValidationUtil.isEmpty(notice.getInspectionUnitName())) {
            maintainInfo.put("inspectUnitId", notice.getInspectionUnitCreditCode() + "_" + notice.getInspectionUnitName());
        }
        if (!ValidationUtil.isEmpty(notice.getStreet()) && !ValidationUtil.isEmpty(notice.getStreetName())) {
            maintainInfo.put("street", notice.getStreet() + "_" + notice.getStreetName());
        }
        String[] fields = {"productPhoto",  "designDoc", "designStandard", "factoryStandard", "productQualityYieldProve",
                "insUseMaintainExplain", "inspectReport", "proxyStatementAttachment", "installContractAttachment"};
        // 设备信息 "equCategory",  "equDefine",  "equRegisterCode",  "produceCountry",  "produceLicenseNum",
        List<Map<String, Object>> equipmentInfos = jgMaintainNoticeMapper.queryEquipInformation(sequenceNbr);
        for (String s : fields) {
            if (maintainInfo.containsKey(s))
                maintainInfo.put(s, JSON.parseArray(maintainInfo.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>>() {{
            put(TABLE_PAGE_ID, maintainInfo);
            put("equipmentInfo", equipmentInfos.get(0));
        }};
    }

    /**
     * 更新维修告知
     *
     * @param noticeDto 维修告知
     */
    @SuppressWarnings({"rawtypes", "Duplicates"})
    @Transactional
    public JgMaintainNoticeDto updateMaintainNotice(String submitType, JgMaintainNoticeDto 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("maintainNotice");
                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("JgMaintainNoticeServiceImpl.updateMaintainNotice启动失败：{}", e);
                    throw new RuntimeException(e);
                }
            }
            JgMaintainNotice notice = new JgMaintainNotice();
            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.setNextExecuteIds(String.join(",", roleListSecond));
                notice.setNoticeStatus(String.valueOf(FlowStatusEnum.TO_BE_PROCESSED.getCode()));
                updateById(notice);
            }
        } else {
            JgMaintainNotice bean = new JgMaintainNotice();
            BeanUtils.copyProperties(noticeDto, bean);
            jgMaintainNoticeMapper.updateById(bean);
        }
        return noticeDto;
    }


    /**
     * 分页查询
     *
     * @param page  分页对象
     * @param model 查询参数
     * @param type  类型：enterprise-企业端、supervision-监管端
     * @return 维修告知列表
     */
    @Override
    public Page<JgMaintainNoticeDto> queryForJgMaintainNoticePage(Page<JgMaintainNotice> page, JgMaintainNoticeDto model, String type, ReginParams reginParams) {
        String orgCode = reginParams.getCompany().getCompanyCode();
        List<DataDictionary> dictionaries = dataDictionaryService.getByType("WXLX");
        Page<JgMaintainNotice> noticePage = jgMaintainNoticeMapper.queryForPage(page, model, type, orgCode);
        Page<JgMaintainNoticeDto> noticeDtoPage = new Page<>();
        BeanUtils.copyProperties(noticePage, noticeDtoPage, "records");
        List<JgMaintainNoticeDto> records = noticePage.getRecords().stream().map(notice -> {
            JgMaintainNoticeDto noticeDto = new JgMaintainNoticeDto();
            BeanUtils.copyProperties(notice, noticeDto);
            if (Objects.nonNull(notice.getNoticeStatus())) {
                String noticeStatusDesc = FlowStatusEnum.getNameByType(Long.valueOf(notice.getNoticeStatus()));
                noticeDto.setNoticeStatusDesc(noticeStatusDesc);
            }
            if (Objects.nonNull(notice.getMaintainType())) {
                noticeDto.setMaintainTypeDesc(dictionaries.stream().filter(d -> notice.getMaintainType().equals(d.getCode())).map(DataDictionary::getName).collect(Collectors.joining()));
            }
            noticeDto.setFullAddress(notice.getProvinceName() + notice.getCityName() + notice.getCountyName() + notice.getStreetName() + notice.getAddress());
            return noticeDto;
        }).collect(java.util.stream.Collectors.toList());
        noticeDtoPage.setRecords(records);
        return noticeDtoPage;
    }

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

    /**
     * 打印维修告知单
     *
     * @param sequenceNbr 主键
     * @return pdf文件路径
     */
    @Override
    public String generateMaintainNoticeReport(Long sequenceNbr) {
        if (Objects.isNull(sequenceNbr)) {
            throw new IllegalArgumentException("参数不能为空");
        }
        JgMaintainNotice JgMaintainNotice = this.getById(sequenceNbr);
        List<Map<String, Object>> informationList = jgMaintainNoticeMapper.queryEquipInformation(sequenceNbr);
        if (Objects.isNull(JgMaintainNotice) || 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", "维修"); // TODO: 施工类别
        placeholders.put("installLicenseNo", "");
        placeholders.put("installLicenseExpirationDate", "");
        placeholders.put("installLeaderName", getValue.apply("installLeaderName"));// 施工负责人
        placeholders.put("installLeaderPhone", getValue.apply("installLeaderPhone"));// 施工负责人手机
        placeholders.put("installUnitAddress", getValue.apply("provinceName") + getValue.apply("cityName") + getValue.apply("countyName") + getValue.apply("address")); // 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) {
            log.error("word转pdf失败：{}", e);
            throw new RuntimeException(e);
        }
        // 上传pdf至文件服务器
        String url = this.uploadFile(pdfFile);
        // 删除临时文件
        try {
            Files.deleteIfExists(pdfFile.toPath());
        } catch (IOException e) {
            log.error("删除临时文件失败：{}", e);
            throw new RuntimeException(e);
        }
        // 更新到数据库
        JgMaintainNotice.setNoticeReportUrl(url);
        this.updateById(JgMaintainNotice);
        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, JgMaintainNoticeDto> jgMaintainNoticeDtoMap, ReginParams reginParams) {
        String[] taskName = new String[]{"流程结束"};
        JgMaintainNoticeDto model = jgMaintainNoticeDtoMap.get(TABLE_PAGE_ID);
        // 字段转换
        convertField(model);
        // 获取告知设备列表
        List<Map<String, Object>> deviceList = model.getDeviceList();
        if (CollectionUtils.isEmpty(deviceList)) {
            return;
        }
        // 获取告知单号
        List<String> applyNoList = iCreateCodeService.createApplicationFormCode(ApplicationFormTypeEnum.WXGZ.getCode(), deviceList.size());
        if (CollectionUtils.isEmpty(applyNoList)) {
            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<JgMaintainNotice> list = new ArrayList<>();
        List<JgMaintainNoticeEq> equipList = new ArrayList<>();
        deviceList.forEach(obj -> {
            JgMaintainNoticeEq jgRelationEquip = new JgMaintainNoticeEq();
            JgMaintainNotice dto = new JgMaintainNotice();
            BeanUtils.copyProperties(model, dto);
            int i = deviceList.indexOf(obj);
            String applyNo = applyNoList.get(i);
            dto.setApplyNo(applyNo);
            dto.setNoticeDate(new Date());
            dto.setEquCategory(String.valueOf(obj.get("EQU_CATEGORY")));
            dto.setEquListCode(String.valueOf(obj.get("EQU_LIST_CODE")));
            if (SUBMIT_TYPE_FLOW.equals(submitType)) {
                dto.setNextExecuteIds(String.join(",", roleListSecond));
                dto.setInstanceStatus(String.join(",", roleListFirst));
                dto.setPromoter(reginParams.getUserModel().getUserId());
                dto.setStatus(taskName[0]);
            }
            dto.setInstallUnitName(reginParams.getCompany().getCompanyName());
            dto.setInstallUnitCreditCode(reginParams.getCompany().getCompanyCode());
            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()));
            }
            dto.setCreateUserId(reginParams.getUserModel().getUserId());
            list.add(dto);
            equipList.add(jgRelationEquip);
        });

        jgMaintainNoticeMapper.insertBatchSomeColumn(list);

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

        jgMaintainNoticeEqMapper.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");
            AjaxResult taskGroupName = Workflow.taskClient.getTaskGroupName(nextTaskId);
            taskName[0] = taskNoAuth.getString("name");
            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(JgMaintainNoticeDto model) {
        if (null == model)
            return;
        // 处理附件
        if (!ValidationUtil.isEmpty(model.getPowerOfAttorneyList())) {
            model.setPowerOfAttorney(JSON.toJSONString(model.getPowerOfAttorneyList()));
        }
        if (!ValidationUtil.isEmpty(model.getConstructionContractList())) {
            model.setConstructionContract(JSON.toJSONString(model.getConstructionContractList()));
        }
        // 分割省市区街道字段
        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 street = model.getStreet();
        if (!ObjectUtils.isEmpty(street)) {
            String[] streetList = street.split("_");
            if (streetList.length > 1) {
                model.setStreet(streetList[0]);
                model.setStreetName(streetList[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.getReceiveOrgCode();
        if (!ObjectUtils.isEmpty(receiveOrgId)) {
            String[] receiveOrgIdList = receiveOrgId.split("_");
            if (receiveOrgIdList.length > 1) {
                model.setReceiveOrgCode(receiveOrgIdList[0]);
                model.setReceiveOrgName(receiveOrgIdList[1]);
            }
        }

        String constructionManager = model.getConstructionManagerId();
        if (!ObjectUtils.isEmpty(constructionManager)) {
            String[] constructionManagerList = constructionManager.split("_");
            if (constructionManagerList.length > 1) {
                model.setConstructionManagerId(constructionManagerList[0]);
                model.setConstructionManager(constructionManagerList[1]);
            }
        }

        String inspectUnitId = model.getInspectionUnitCreditCode();
        if (!ObjectUtils.isEmpty(inspectUnitId)) {
            String[] inspectUnitIdList = inspectUnitId.split("_");
            if (inspectUnitIdList.length > 1) {
                model.setInspectionUnitCreditCode(inspectUnitIdList[0]);
                model.setInspectionUnitName(inspectUnitIdList[1]);
            }
        }
    }

    public boolean submit(JgMaintainNotice 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("JgMaintainNoticeServiceImpl.submit提交失败：{}", e);
            return false;
        }
    }

    public void cancel(JgMaintainNoticeDto noticeDto) {
        String[] taskName = new String[]{"流程结束"};
        FeignClientResult ajaxResult = Workflow.taskV2Client.rollBack(noticeDto.getInstanceId());
        JgMaintainNotice jgInstallationNotice = this.baseMapper.selectById(noticeDto.getSequenceNbr());
        ArrayList<String> roleList = new ArrayList<>();
        if (ajaxResult.getStatus() == 200) {
            getNext(roleList, noticeDto.getInstanceId(), taskName);
            jgInstallationNotice.setStatus(taskName[0]);
            jgInstallationNotice.setPromoter("");
            jgInstallationNotice.setNextExecuteIds(String.join(",", roleList));
            jgInstallationNotice.setNoticeStatus(String.valueOf(FlowStatusEnum.ROLLBACK.getCode()));
            updateById(jgInstallationNotice);
        }
    }

    @Transactional
    public void accept(JgMaintainNoticeDto dto, String op) {
        String[] taskName = new String[]{"流程结束"};
        String userId = RequestContext.getExeUserId();
        JgMaintainNotice jgMaintainNotice = this.jgMaintainNoticeMapper.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);
        }
        ArrayList<String> roleList = new ArrayList<>();
        boolean submit = submit(jgMaintainNotice, op);
        if (submit) {
            getNext(roleList, dto.getInstanceId(), taskName);
            jgMaintainNotice.setStatus(taskName[0]);
            if ("0".equals(op)) {
                if (roleList.size() == 0) {
                    LambdaQueryWrapper<JgMaintainNoticeEq> queryWrapper = new LambdaQueryWrapper<>();
                    queryWrapper.eq(JgMaintainNoticeEq::getEquipTransferId, dto.getSequenceNbr());
                    JgMaintainNoticeEq jgRelationEquip = jgMaintainNoticeEqMapper.selectOne(queryWrapper);
                    LambdaQueryWrapper<RegistrationInfo> queryWrapper2 = new LambdaQueryWrapper<>();
                    queryWrapper2.eq(RegistrationInfo::getRecord, jgRelationEquip.getEquId());
                    RegistrationInfo tzsJgRegistrationInfo = tzsJgRegistrationInfoMapper.selectOne(queryWrapper2);
                    stringBuffer.append(tzsJgRegistrationInfo.getEquCategory()).append(jgMaintainNotice.getCity()).append(ym);
                    Map<String, Object> map = new HashMap<>();
                    map.put("cityCode", jgMaintainNotice.getCity());
                    map.put("countyCode", jgMaintainNotice.getCounty());
                    map.put("equCategory", tzsJgRegistrationInfo.getEquCategory());
                    jgMaintainNotice.setAcceptDate(new Date());
                    jgMaintainNotice.setNoticeStatus(String.valueOf(FlowStatusEnum.TO_BE_FINISHED.getCode()));
                    generateMaintainNoticeReport(jgMaintainNotice.getSequenceNbr());
                    jgMaintainNotice.setPromoter("");
                } else {
                    jgMaintainNotice.setNextExecuteIds(String.join(",", roleList));
                    if (!ObjectUtils.isEmpty(jgMaintainNotice.getInstanceStatus())) {
                        jgMaintainNotice.setInstanceStatus(jgMaintainNotice.getInstanceStatus() + "," + String.join(",", roleList));
                    } else {
                        jgMaintainNotice.setInstanceStatus(String.join(",", roleList));
                    }
                    jgMaintainNotice.setPromoter(userId);
                    jgMaintainNotice.setNoticeStatus(String.valueOf(FlowStatusEnum.TO_BE_PROCESSED.getCode()));
                }
            } else {
                jgMaintainNotice.setPromoter("");
                jgMaintainNotice.setNoticeStatus(String.valueOf(FlowStatusEnum.REJECTED.getCode()));
            }
            jgMaintainNoticeMapper.updateById(jgMaintainNotice);
        }
    }
}