/*
 * Author: wangjian
 * 生成ServiceImpl
 */
package com.tofly.xrtymis.custom.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tofly.api.*;
import com.tofly.api.audit.AuditClient;
import com.tofly.api.message.MessageClient;
import com.tofly.api.message.MessageStateClient;
import com.tofly.api.mssage.SendMessageFeign;
import com.tofly.api.order.OrderClient;
import com.tofly.baseapi.mapper.ToflyCodeCommonMapper;
import com.tofly.common.core.entity.ResultRespone;
import com.tofly.common.core.util.Date8Util;
import com.tofly.common.core.util.StringUtil;
import com.tofly.common.ftp.config.FtpUtil;
import com.tofly.common.oauth.exception.ToflyDeniedException;
import com.tofly.common.oauth.util.SecurityUtils;
import com.tofly.pojo.Department;
import com.tofly.pojo.User;
import com.tofly.pojo.comm.Audit;
import com.tofly.pojo.maintain.dto.RepairorderDto;
import com.tofly.pojo.maintain.dto.RepairuserChildDto;
import com.tofly.pojo.maintain.vo.AuxiliarySingleVo;
import com.tofly.pojo.maintain.vo.datail.RepairOrderDetailVo;
import com.tofly.pojo.message.Messagepush;
import com.tofly.pojo.message.Messagerecipient;
import com.tofly.pojo.message.Usertask;
import com.tofly.pojo.note.SendMessage;
import com.tofly.pojo.note.SendNoteEn;
import com.tofly.pojo.plan.Checkhistory;
import com.tofly.xrtymis.config.FilePathBean;
import com.tofly.xrtymis.custom.commons.CommonConstants;
import com.tofly.xrtymis.custom.commons.Constate;
import com.tofly.xrtymis.custom.dto.*;
import com.tofly.xrtymis.custom.em.*;
import com.tofly.xrtymis.custom.entity.LngLats;
import com.tofly.xrtymis.custom.entity.ReadEntity;
import com.tofly.xrtymis.custom.service.*;
import com.tofly.xrtymis.custom.utils.DateTimeUtil;
import com.tofly.xrtymis.custom.utils.DateUtils;
import com.tofly.xrtymis.custom.utils.ForeignHttpUtils;
import com.tofly.xrtymis.custom.vo.*;
import com.tofly.xrtymis.em.Constant;
import com.tofly.xrtymis.em.ExcelExportFileTypeEnum;
import com.tofly.xrtymis.entity.*;
import com.tofly.xrtymis.exception.BusinessException;
import com.tofly.xrtymis.mapper.GdglinfoMapper;
import com.tofly.xrtymis.strategy.ExcelStrategyContext;
import com.tofly.xrtymis.util.ExcelUtil;
import com.tofly.xrtymis.util.HttpClientUtil;
import feign.FeignException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

/**
 * 业务工单详情表
 *
 * @author fu
 * @date Fri Mar 19 00:00:00 CST 2021
 */
@Service("gdglinfoService")
@Slf4j
public class GdglinfoServiceImpl extends ServiceImpl<GdglinfoMapper, Gdglinfo> implements GdglinfoService {

    @Value("${xrty.ftp.ywgdfile}")
    private String avatarPath;

    /**
     * 路由地址
     */
    /*工单登记*/
    @Value("${mis-gd.route.gdrul}")
    public String GD_URL;
    /*工单登记app*/
    @Value("${mis-gd.route.gdrulapp}")
    public String GD_URLAPP;
    /*认证处置*/
    @Value("${mis-gd.route.rzrul}")
    public String RZ_URL;
    /*认证处置app*/
    @Value("${mis-gd.route.rzrulapp}")
    public String RZ_URLAPP;
    /*认证审核*/
    @Value("${mis-gd.route.rzshurl}")
    public String RZSH_URL;
    /*认证审核app*/
    @Value("${mis-gd.route.rzshurlapp}")
    public String RZSH_URLAPP;
    /*认证质检*/
    @Value("${mis-gd.route.zjurl}")
    public String ZJ_URL;
    /*认证质检app*/
    @Value("${mis-gd.route.zjurlapp}")
    public String ZJ_URLAPP;
    /*结果处置*/
    @Value("${mis-gd.route.czurl}")
    public String CZ_URL;
    /*结果处置app*/
    @Value("${mis-gd.route.czurlapp}")
    public String CZ_URLAPP;
    /*结果审核*/
    @Value("${mis-gd.route.jgshurl}")
    public String JGSH_URL;
    /*结果审核app*/
    @Value("${mis-gd.route.jgshurlapp}")
    public String JGSH_URLAPP;

    /*即将超时百分比配置*/
    @Value("${mis-gd.upcoming}")
    public Integer ratio;
    /*网厅url*/
    @Value("${mis-gd.foreign.wturl}")
    public String wturl;
    /*网厅回调接口路径*/
    @Value("${mis-gd.foreign.wtpath}")
    public String wtpath;
    /*网厅回调key*/
    @Value("${mis-gd.foreign.wtkey}")
    public String wtkey;
    /**
     * 营销奖励水量工单回调URL
     */
    @Value("${mis-gd.yxJLSLUrl}")
    public String yxJLSLUrl;

    @Autowired
    private FileService fileService;
    @Autowired
    private GdglinfoService gdglinfoService;

    @Autowired
    private GdglflowService gdglflowService;

    @Autowired
    private FilePathBean filePathBean;

    @Autowired
    private CodeClient codeClient;

    @Autowired
    private MessageClient messageClient;
    @Autowired
    private UserTaskClient userTaskClient;
    @Autowired
    private MessageStateClient messageStateClient;
    @Autowired
    private GdflowconfigService gdflowconfigService;
    @Autowired
    private RedeployService redeployService;
    @Autowired
    private ResultdispService resultdispService;

    @Autowired
    private AuditClient auditClient;

    @Autowired
    private UserClent userClent;

    @Autowired
    private DepartmentClient departmentClient;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    private OrderClient orderClient;

    @Autowired
    private GdglCirculationService gdglCirculationService;
    @Autowired
    private GdgltypebmService gdgltypebmService;
    @Autowired
    private ExcelStrategyContext excelStrategyContext;
    @Autowired
    private ToflyCodeCommonMapper toflyCodeCommonMapper;
    @Autowired
    private GdpersonService gdpersonService;
    @Autowired
    private DutyrosterService dutyrosterService;
    @Autowired
    private LeakInfoService leakInfoService;
    @Autowired
    private NoiseLoggerInfoService noiseUploadService;
    @Value("${xrty.isRxgd}")
    private String isRxgd;
    @Autowired
    private SendMessageFeign sendMessageFeign;

    /**
     * 工单详情查询
     *
     * @param response
     * @param page
     * @param dto
     * @param export
     */
    @Override
    public Page<Map> gdInfoQuery(HttpServletResponse response, Page page, GdInfoQueryDto dto, Integer export) {

        if (export == 0) {
            Page<Map> mapPage = baseMapper.gdInfoQuery(page, dto);
            List<Map> infoList = mapPage.getRecords();

            if (infoList.isEmpty()) {
                return mapPage;
            }
//            List<Gdflowconfig> list = gdflowconfigService.list();
            //拿出工单流程id
            List<Object> lcidList = infoList.stream().distinct().map(map -> map.get("lcid")).collect(Collectors.toList());
            //配置流程id查询
            List<Gdflowconfig> congigList = gdflowconfigService.list(Wrappers.<Gdflowconfig>lambdaQuery().in(Gdflowconfig::getId, lcidList));

            Map<Long, List<Gdflowconfig>> collect = null;
            if (!congigList.isEmpty()) {
                collect = congigList.stream().collect(Collectors.groupingBy(Gdflowconfig::getId));
            }


            List<Gdgltypebm> gdgltypeList = gdgltypebmService.list();

            Gdgltypebm gdgltypebm = null;

            for (Map map : infoList) {
                Long lcid = Long.valueOf(map.get("lcid").toString());
                if (collect == null || !collect.containsKey(lcid)) {
                    map.put("gdflowconfig", null);
                    map.put("allLcjd", null);
                } else {
                    Gdflowconfig gdflowconfig = collect.get(lcid).get(0);
                    map.put("gdflowconfig", gdflowconfig);
                    map.put("allLcjd", gdflowconfig.getAllLcjd());
                }
                Object gdTypeId = map.get("gdgzlx");
                //设置归档故障类型的值
                if (!gdgltypeList.isEmpty() && !StringUtils.isEmpty(gdTypeId)) {
                    gdgltypebm = gdgltypebmService.getById(gdTypeId.toString());
                    map.put("gdlxfl", (gdgltypebm == null ? "" : gdgltypebm.getGdlxMc()) + "/" + map.get("gdlxfl"));
                }

//                    Object lcid = map.get("lcid");
//
//                    if (lcid != null){
//                        Gdflowconfig byId = gdflowconfigService.getById(Long.valueOf(lcid.toString()));
////                        List<Gdflowconfig> collect = list.stream().filter(gd -> gd.getId().equals(Long.valueOf(lcid.toString()))).collect(Collectors.toList());
//                        if (byId == null){
//                            map.put("gdflowconfig",null);
//                            map.put("allLcjd",null);
//                        }else {
//
//                            map.put("gdflowconfig", byId);
//                            map.put("allLcjd",byId.getAllLcjd());
//                        }
//
//                    }
            }
            return mapPage;
        } else {
            List<Map> maps = baseMapper.gdInfoQuery(dto);
            // 根据templateServiceType,templateFlag获取对应模板数据
            ExcelExportFileTypeEnum excelExportFileTypeEnum = ExcelExportFileTypeEnum.getExcelExportFileTypeEnum("exportGdglService", "1");
            if (null == excelExportFileTypeEnum) {
                throw new ToflyDeniedException("导出失败");
            }
            //将查询的结果转json字符串的格式，因为导出的时候只能传一个字符串
            String resultListToString = JSONArray.toJSONStringWithDateFormat(maps, "yyyy-MM-dd HH:mm:ss");
            // 从模型类型枚举根据templateServiceType获取策略对应模板数据
            List<Map<String, Object>> dataList = excelStrategyContext.getExportData("exportGdglService", "1", resultListToString);
            ExcelUtil.export(dataList.get(0), excelExportFileTypeEnum, Constant.FILE_PATH_TEST_EXPORT_EXCEL, response);
            return null;
        }
    }

    @Override
    public List<Map> getUserByRole(String roleId) {
        if (StringUtils.isEmpty(roleId)) {
            throw new ToflyDeniedException("未选择角色信息");
        }
        return baseMapper.getUserByRole(Arrays.asList(roleId.split(",")));
    }

    /**
     * 创建工单
     *
     * @param extend
     * @return
     */
    @Override
    public ResultRespone saveGdglInfo(List<MultipartFile> fileList, GdglinfoExtendDto extend, List<Resultdisp> resultdispList) {
        //审批链
        Audit audit = extend.getAudit();
        Gdglinfo gdglinfo = new Gdglinfo();
        BeanUtils.copyProperties(extend, gdglinfo);
        if(StringUtil.isNotEmpty(isRxgd)){
            gdglinfo.setIsRxlx("1");
        }
        if (StringUtils.isEmpty(gdglinfo.getLcid())) {
            return ResultRespone.failed(false, "配置流程id为空");
        }

        //通过当前用户获取用户所在的部门
        ResultRespone<User> user = userClent.getById(SecurityUtils.getUserId());
        User us = user.getResult();
        Long departmentId = us.getDepartmentId();
        ResultRespone<Department> department = departmentClient.getById(departmentId);
        Gdglinfo gdglinfodb = null;
        if (gdglinfo.getId() == null) {
            String code = null;
            //如果是热线，前缀为 RXGD
            if ("1".equals(gdglinfo.getIsRxlx())) {
                code = "RXGD";
            } else if ("1".equals(gdglinfo.getIsLeak())) {
                code = "LDGD";
            } else {
                Department result = department.getResult();
                if (result == null) {
                    return ResultRespone.failed(false, "用户不属于任何部门");
                }
                code = result.getCode();
            }
            //生成工单号
            gdglinfo.setGdbh(generateBatchNo(code));
        } else {
            gdglinfodb = this.getById(gdglinfo.getId());
        }
        String tzry = null;
        String routeip = null;
        String routeipapp = null;
        Date endDate = null;
        String topicName = null;
        //通过工单类型来获取配置状态
        Gdflowconfig gdflowconfig = gdflowconfigService.getById(gdglinfo.getLcid());
        if (gdflowconfig == null) {
            return ResultRespone.failed(false, "配置流程id无效");
        }
        //汪截流：登记后没有提交的或者工单还是登记状态的却是本环节的工单，不用计算超时时间等字段信息（个人打断点走流程测试出的观点，因为之前整片代码没有注释说明）
        if ((gdglinfodb == null || Long.valueOf(GdglinfoEM.GDDJ.getType()).equals(gdglinfodb.getLcjd()))
                && Long.valueOf(GdglinfoEM.BHJ.getType()).equals(gdglinfo.getGddjZt())) {
            gdglinfo.setDjsj(new Date());
            gdglinfo.setGddjFssj(new Date());
            gdglinfo.setJdzt(GdglinfoEM.NOTENABLE.getType());
            gdglinfo.setLcjd(Long.valueOf(GdglinfoEM.GDDJ.getType()));
            gdglinfo.setDjry(SecurityUtils.getUserId());
            gdglinfo.setDjbm(SecurityUtils.getUserDeptId());
            gdglinfo.setProcessInfo("1");
            jdSaveFile(fileList, gdglinfo);
        }
        //汪截流：登记后没有提交的或者工单还是登记状态的却是走下一流程环节的；需要计算超时时间等字段
        else if ((gdglinfodb == null || Long.valueOf(GdglinfoEM.GDDJ.getType()).equals(gdglinfodb.getLcjd()))
                && Long.valueOf(GdglinfoEM.XYGHJ.getType()).equals(gdglinfo.getGddjZt())) {
            gdglinfo.setProcessDeposit("1");
            gdglinfo.setDjsj(new Date());
            gdglinfo.setGddjFssj(new Date());
            if (gdflowconfig.getGddjJdsx() != null && gdglinfo.getJdsx() == null) {
                //工单接单时限
                gdglinfo.setJdsx(DateTimeUtil.dateTimeDifference(gdflowconfig.getGddjJdsx(), Calendar.MINUTE));
            }
            gdglinfo.setJdzt(GdglinfoEM.ISENABLE.getType());
            gdglinfo.setDjry(SecurityUtils.getUserId());
            gdglinfo.setDjbm(SecurityUtils.getUserDeptId());

            jdSaveFile(fileList, gdglinfo);
            //设置认证处置超时时间
            if (GdglinfoEM.ISENABLE.getType().equals(gdflowconfig.getRzczSfqy())) {
                gdglinfo.setProcessInfo("1,2");
                gdglinfo.setLcjd(Long.valueOf(GdglinfoEM.RZCZ.getType()));
                tzry = gdglinfo.getSlry();
                routeip = RZ_URL;
                routeipapp = RZ_URLAPP;
                topicName = CommonConstants.RZCL;
                if (gdflowconfig.getRzczCzsx() != null) {
                    gdglinfo.setRzsx(DateTimeUtil.dateTimeDifference(gdflowconfig.getRzczCzsx(), Calendar.HOUR_OF_DAY));
                    endDate = gdglinfo.getRzsx();
                }
            }

            //结果审核
            else if (GdglinfoEM.NOTENABLE.getType().equals(gdflowconfig.getRzshSfqy()) && GdglinfoEM.NOTENABLE.getType().equals(gdflowconfig.getRzczSfqy())
                    && GdglinfoEM.NOTENABLE.getType().equals(gdflowconfig.getRzzjSfqy()) && GdglinfoEM.NOTENABLE.getType().equals(gdflowconfig.getJgczSfqy())
                    && GdglinfoEM.ISENABLE.getType().equals(gdflowconfig.getJgshSfqy())) {
                gdglinfo.setProcessInfo("1,6");
                //工单登记添加审批链
                if (StringUtil.isNotNull(audit)) {
                    audit.setAuditType(AuditEnum.GD_TYPE.getCode());
                    gdglinfo.setJgczry(audit.getAuditUser());
                    gdglinfo.setShrdj(1);
                    audit.setAuditLevel(1);
                    audit.setAuditState("0");

                } else {
                    throw new ToflyDeniedException("请添加审批人信息");
                }

                gdglinfo.setLcjd(Long.valueOf(GdglinfoEM.JGSH.getType()));
                routeip = JGSH_URL;
                routeipapp = JGSH_URLAPP;
                topicName = CommonConstants.JGSH;
                tzry = String.valueOf(audit.getAuditUser());
                if (gdflowconfig.getJgshShsx() != null) {
                    gdglinfo.setShsx(DateTimeUtil.dateTimeDifference(gdflowconfig.getJgshShsx(), Calendar.HOUR_OF_DAY));
                    endDate = gdglinfo.getShsx();
                }

            }

            //设置整个工单时限时间
            Long gdsxNum = gdflowconfig.getGdzsx();
            if (StringUtil.isNotNull(gdsxNum)) {
                //计算整个工单时限时间
                Date gdsx = DateTimeUtil.dateTimeDifference(gdsxNum, Calendar.HOUR_OF_DAY);
                gdglinfo.setGdsx(gdsx);
            }
        }
        //已经保存了工单，并且是终止工单
        else if (gdglinfodb != null && Long.valueOf(GdglinfoEM.ZZ.getType()).equals(gdglinfo.getGddjZt())) {
            gdglinfo.setZzry(SecurityUtils.getUserId());
            gdglinfo.setZzsj(new Date());
            gdglinfo.setJdzt("1");
            gdglinfo.setLcjd(Long.valueOf(GdglinfoEM.GDGD.getType()));
            gdglinfo.setProcessDeposit(sub1(gdglinfodb.getProcessDeposit() + ",7"));
            gdglinfo.setProcessInfo(sub1(gdglinfodb.getProcessInfo() + ",7"));
            gdglinfo.setFinishTime(new Date());
            gdglinfo.setGdzzzt("1");
            gdglinfo.setId(gdglinfo.getId());
            gdglinfo.setLczzyy(gdglinfo.getLczzyy());
        }


        if (gdglinfo.getId() == null) {
            gdglinfoService.save(gdglinfo);
        } else {
            gdglinfoService.updateById(gdglinfo);
        }
        // 判断是否为漏点
        if ("1".equals(gdglinfo.getIsLeak())) {
            LeakInfo leakInfo = extend.getLeakInfo();
            if (null != leakInfo) {
                leakInfo.setGdinfoId(gdglinfo.getId());
                if (Long.valueOf(GdglinfoEM.XYGHJ.getType()).equals(gdglinfo.getGddjZt())) {
                    leakInfo.setDisposeState(LeakStateEnum.ZZCL.getCode());
                }
                leakInfoService.saveOrUpdate(leakInfo);
            }
            if (Long.valueOf(GdglinfoEM.ZZ.getType()).equals(gdglinfo.getGddjZt())) {
                leakInfoService.update(new UpdateWrapper<LeakInfo>().lambda()
                        .eq(LeakInfo::getGdinfoId, gdglinfo.getId())
                        .set(LeakInfo::getDisposeState, LeakStateEnum.ZZ.getCode()));
            }

        }
        // 判断是否为奖励水量
        if("1".equals(gdglinfo.getIsRewardWater())){
            BigDecimal rewardWaterVolume = gdglinfo.getRewardWaterVolume()==null?BigDecimal.ZERO:BigDecimal.valueOf(Double.parseDouble(gdglinfo.getRewardWaterVolume()));
            // 同步到公众参与对象 奖励水量工单id及奖励水量
            leakInfoService.updatePublicRewardWaterVolume(gdglinfo.getId(),String.valueOf(rewardWaterVolume));
        }
        // 判断是否为噪音
        if ("1".equals(gdglinfo.getIsNoise())) {
            String noises = extend.getNoises();
            if (null != noises) {
                List<Long> noiseIdList = Arrays.stream(noises.split(Constant.CSV)).map(s -> Long.parseLong(s.trim()))
                        .collect(Collectors.toList());
                if (Long.valueOf(GdglinfoEM.BHJ.getType()).equals(gdglinfo.getGddjZt())) {
                    noiseUploadService.update(new UpdateWrapper<NoiseLoggerInfo>().lambda()
                            .in(NoiseLoggerInfo::getId, noiseIdList)
                            .set(NoiseLoggerInfo::getDisposeState, NoiseStateEnum.YFGD.getCode())
                            .set(NoiseLoggerInfo::getGdinfoId, gdglinfo.getId())
                    );
                }
                if (Long.valueOf(GdglinfoEM.XYGHJ.getType()).equals(gdglinfo.getGddjZt())) {
                    noiseUploadService.update(new UpdateWrapper<NoiseLoggerInfo>().lambda()
                            .in(NoiseLoggerInfo::getId, noiseIdList)
                            .set(NoiseLoggerInfo::getDisposeState, NoiseStateEnum.ZZCL.getCode())
                            .set(NoiseLoggerInfo::getGdinfoId, gdglinfo.getId())
                    );
                }
            }
            if (Long.valueOf(GdglinfoEM.ZZ.getType()).equals(gdglinfo.getGddjZt())) {
                noiseUploadService.update(new UpdateWrapper<NoiseLoggerInfo>().lambda()
                        .eq(NoiseLoggerInfo::getGdinfoId, gdglinfo.getId())
                        .set(NoiseLoggerInfo::getDisposeState, NoiseStateEnum.ZZ.getCode())
                );
            }
        }
        if (tzry != null) {
            List<Long> tzrys = Arrays.stream(tzry.split(Constant.CSV)).map(s -> Long.parseLong(s.trim())).distinct().collect(Collectors.toList());
            String finalTopicName = topicName;
            String finalRouteip = routeip;
            Date finalEndDate = endDate;
            String finalRouteipapp = routeipapp;
            tzrys.forEach(i->{
                gdglinfoMassage(gdglinfo, "6", finalTopicName, i, gdglinfo.getDjsj(), finalRouteip, finalEndDate, finalRouteipapp);
            });
            if (GdglinfoEM.ISENABLE.getType().equals(gdflowconfig.getRzczSfqy())) {
                ResultRespone<User> byId = userClent.getById(Long.valueOf(tzry));
                String phone = byId.getResult().getPhone();
                // 发送短信给处置人员
//                SendMessage sendMessage = new SendMessage();
//                sendMessage.setLxdh(phone);
//                sendMessage.setTxlx("2");
//                String sjdh = gdglinfo.getSjdh()==null?"无":gdglinfo.getSjdh();
//                String gdms = gdglinfo.getGdms() == null ? "无" : gdglinfo.getGdms();
//                sendMessage.setTxnr("工单地址: "+gdglinfo.getAddress()+",工单说明: "+gdms+",联系电话: "+sjdh+",请前往'掌上统一办公APP'处理");
//                SendNoteEn sendNoteEn = new SendNoteEn();
//                List<SendMessage> sendMessageList = new ArrayList<>();
//                sendMessageList.add(sendMessage);
//                sendNoteEn.setSendMessageList(sendMessageList);
//                sendMessageFeign.sendMessage(sendNoteEn);
            }
        }
        // 本环节不消除待办
        if (!Long.valueOf(GdglinfoEM.BHJ.getType()).equals(gdglinfo.getGddjZt())) {
            removeDB(gdglinfo.getId(), CommonConstants.GDDJ);
        }
        Long gdid = gdglinfo.getId();

        if (GdglinfoEM.NOTENABLE.getType().equals(gdflowconfig.getRzshSfqy()) && GdglinfoEM.NOTENABLE.getType().equals(gdflowconfig.getRzczSfqy())
                && GdglinfoEM.NOTENABLE.getType().equals(gdflowconfig.getRzzjSfqy()) && GdglinfoEM.NOTENABLE.getType().equals(gdflowconfig.getJgczSfqy())
                && GdglinfoEM.ISENABLE.getType().equals(gdflowconfig.getJgshSfqy())) {
            audit.setAuditPlanId(gdid);
            List<Audit> auditList = new ArrayList<>();
            auditList.add(audit);
            boolean flag = saveAuditChain(auditList);
            if (!flag) {
                throw new ToflyDeniedException("添加审批人失败");
            }
        }


        return ResultRespone.success(gdid);
    }

    /**
     * 终止抢维修工单
     *
     * @param gdglinfo
     * @param gdglinfodb
     */
    private boolean stopQWX(Gdglinfo gdglinfo, Gdglinfo gdglinfodb) {
        GdglCirculation gdglCirculations = gdglCirculationService.getOne(new QueryWrapper<GdglCirculation>().lambda().eq(GdglCirculation::getGdbh, gdglinfodb.getGdbh()).eq(GdglCirculation::getGdstate, 0));
        if (gdglCirculations != null && !StringUtils.isEmpty(gdglCirculations.getOtherBh())) {
            String otherbh = gdglCirculations.getOtherBh();
            //TODO 终止抢维修工单
            return orderClient.terminationRepairOrder(otherbh).getResult();
        }
        return true;
    }

    private void jdSaveFile(List<MultipartFile> fileList, Gdglinfo gdglinfo) {
        if (fileList == null || fileList.isEmpty()) {
            if (gdglinfo != null && StringUtils.isEmpty(gdglinfo.getGddjFileid()) && gdglinfo.getId() != null) {
                this.update(new UpdateWrapper<Gdglinfo>().lambda().set(Gdglinfo::getGddjFileid, "").eq(Gdglinfo::getId, gdglinfo.getId()));
            }
            return;
        }
        String fileIdsdb = null;
        if (gdglinfo.getId() != null) {
            fileIdsdb = getById(gdglinfo.getId()).getGddjFileid();
        }
        String fileIds = gdglinfo.getGddjFileid();
        StringBuilder files = saveFiles(fileList, fileIdsdb, fileIds);
        if (gdglinfo.getId() != null && StringUtils.isEmpty(files)) {
            this.update(new UpdateWrapper<Gdglinfo>().lambda().set(Gdglinfo::getGddjFileid, "").eq(Gdglinfo::getId, gdglinfo.getId()));
        }
        gdglinfo.setGddjFileid(files.toString());
    }


    private void gdglinfoMassage(Gdglinfo gdglinfo, String s, String topicName, Long slry, Date djsj, String routeip, Date endDate, String routeipapp) {
        //存入消息(只有转部门才会推送到下一个环节审核的消息)
        gdglBHMessage(gdglinfo, s, topicName, slry, routeip, routeipapp);
        //添加消息代办
        Usertask usertask = new Usertask();
        usertask.setTkty(s);
        usertask.setTknm(topicName);
        usertask.setCreateUser(SecurityUtils.getUserId());
        usertask.setHandleTime(djsj);


        usertask.setEndTime(endDate);
        usertask.setStartTime(new Date());
        usertask.setTableName("TF_YWPN_GDINFO_W");
        usertask.setTableId(gdglinfo.getId());
        usertask.setIshandle("0");
        usertask.setRouteIp(routeip);
        usertask.setRouteAppIp(routeipapp);
        usertask.setHandleUser(slry);
        userTaskClient.save(usertask);
    }


    /**
     * 消除待办
     *
     * @param gdglinfoId 工单id
     * @param topicName  流程名称
     */
    private void removeDB(Long gdglinfoId, String topicName) {
        // 待办事项处理状态置为完成
        // 待办事项处理
        Usertask usertask = new Usertask();
        usertask.setTableName(AuditEnum.MESSAGE_TABLE.getCode());
        //工单登记后直接终止工单的情况，需要将该工单的代办全部消除
//        if (StringUtil.isNotEmpty(topicName)) {
//            usertask.setHandleUser(SecurityUtils.getUserId());
//
//        }
        usertask.setTknm(topicName);
        usertask.setTableId(gdglinfoId);
        // 一个是代处理消除 一个是超时消除
//        usertask.setIshandle("0");
        List<Usertask> result = userTaskClient.getUserTaskInfo(usertask).getResult();
        if (null != result && result.size() > 0) {
            result.forEach(task -> {
                task.setHandleTime(DateTimeUtil.convertLDTToDate(LocalDateTime.now()));
                task.setHandleUser(SecurityUtils.getUserId());
                task.setIshandle("1");
                userTaskClient.updateById(task);
            });

        }
    }


    /**
     * 获取工单号
     */
    private String generateBatchNo(String code) {
        //批次前缀
        String prefix = DateUtils.fastDateTime(new Date());
        String pre = prefix.substring(0, 8);
        //使用redis生成唯一流水号
        Long sequence = redisTemplate.opsForValue().increment(CommonConstants.MESSAGE_BATCH_SEQUENCE + "_" + pre, 1);
        if (sequence == 1) {
            redisTemplate.delete(redisTemplate.keys(CommonConstants.MESSAGE_BATCH_SEQUENCE + "_" + "*"));
            sequence = redisTemplate.opsForValue().increment(CommonConstants.MESSAGE_BATCH_SEQUENCE + "_" + pre, 1);
        }
        //批次后缀 取流水号最后5位 如果不足5位前面补0
        String suffix = String.format("%05d", sequence % 100000);
        return code + "-" + pre + suffix;
    }


    /**
     * 修改工单
     *
     * @param extend
     * @return
     */
    @Override
    public ResultRespone updateGdglInfo(List<MultipartFile> fileList, GdglinfoExtendDto extend) {
        if (extend.getId() == null) {
            return ResultRespone.failed("工单id不能为空!");
        }
        //审批链
        Audit audit = extend.getAudit();
        //结果处置
        List<Resultdisp> resultdispList = extend.getResultdispList();
        Gdglinfo gdglinfo = new Gdglinfo();
        BeanUtils.copyProperties(extend, gdglinfo);
        //通过工单类型来获取配置状态
        Gdglinfo info = gdglinfoService.getById(gdglinfo.getId());
        Gdflowconfig gdflowconfig = gdflowconfigService.getById(info.getLcid());
        //汪截流：本环节
        if (Long.valueOf(GdglinfoEM.BHJ.getType()).equals(gdglinfo.getGddjZt())) {
            gdglinfo.setLcjd(Long.valueOf(GdglinfoEM.GDDJ.getType()));
            jdSaveFile(fileList, gdglinfo);
        }
        //汪截流：转下一环节
        else if (Long.valueOf(GdglinfoEM.XYGHJ.getType()).equals(gdglinfo.getGddjZt())) {
            //汪截流：工单已经走过的流程
            gdglinfo.setProcessDeposit("1");
            if (gdflowconfig.getGddjJdsx() != null && gdglinfo.getJdsx() == null) {
                gdglinfo.setJdsx(DateTimeUtil.dateTimeDifference(gdflowconfig.getGddjJdsx(), Calendar.MINUTE));
            }
            gdglinfo.setDjsj(new Date());
            jdSaveFile(fileList, gdglinfo);
            if (GdglinfoEM.ISENABLE.getType().equals(gdflowconfig.getRzczSfqy())) {
                gdglinfo.setProcessInfo("1,2");
                gdglinfo.setLcjd(Long.valueOf(GdglinfoEM.RZCZ.getType()));
                if (gdflowconfig.getRzczCzsx() != null) {
                    gdglinfo.setRzsx(DateTimeUtil.dateTimeDifference(gdflowconfig.getRzczCzsx(), Calendar.HOUR_OF_DAY));
                }
            } else if (GdglinfoEM.ISENABLE.getType().equals(gdflowconfig.getRzshSfqy()) && GdglinfoEM.NOTENABLE.getType().equals(gdflowconfig.getRzczSfqy())) {
                gdglinfo.setProcessInfo("1,3");
                gdglinfo.setLcjd(Long.valueOf(GdglinfoEM.GDSH.getType()));
                if (gdflowconfig.getRzshShsx() != null) {
                    gdglinfo.setShsx(DateTimeUtil.dateTimeDifference(gdflowconfig.getRzshShsx(), Calendar.HOUR_OF_DAY));
                }
            } else if (GdglinfoEM.NOTENABLE.getType().equals(gdflowconfig.getRzshSfqy()) && GdglinfoEM.NOTENABLE.getType().equals(gdflowconfig.getRzczSfqy())
                    && GdglinfoEM.ISENABLE.getType().equals(gdflowconfig.getRzzjSfqy())) {
                gdglinfo.setProcessInfo("1,4");
                gdglinfo.setLcjd(Long.valueOf(GdglinfoEM.GDZJ.getType()));
                if (gdflowconfig.getRzzjZjsx() != null) {
                    gdglinfo.setZjsx(DateTimeUtil.dateTimeDifference(gdflowconfig.getRzzjZjsx(), Calendar.HOUR_OF_DAY));
                }
            }
            //结果处置
            else if (GdglinfoEM.NOTENABLE.getType().equals(gdflowconfig.getRzshSfqy()) && GdglinfoEM.NOTENABLE.getType().equals(gdflowconfig.getRzczSfqy())
                    && GdglinfoEM.NOTENABLE.getType().equals(gdflowconfig.getRzzjSfqy()) && GdglinfoEM.ISENABLE.getType().equals(gdflowconfig.getJgczSfqy())) {
                gdglinfo.setProcessInfo("1,5");
                gdglinfo.setLcjd(Long.valueOf(GdglinfoEM.JGCZ.getType()));
                if (gdflowconfig.getJgczCzsx() != null) {
                    gdglinfo.setCzsx(DateTimeUtil.dateTimeDifference(gdflowconfig.getJgczCzsx(), Calendar.HOUR_OF_DAY));
                }
                if (StringUtil.isNull(resultdispList) || resultdispList.size() == 0) {
                    throw new ToflyDeniedException("请选择结果处置人员信息");
                }
                //上一流程选择的多人处置的情况
                Long maxId = resultdispService.getMaxId();
                String jgczPerson = "";
                Date time = new Date();
                for (Resultdisp resultdisp : resultdispList) {
                    resultdisp.setId(maxId++);
                    resultdisp.setGdbh(info.getGdbh());
                    resultdisp.setImportLcjd(39L);
                    resultdisp.setLcjdName(CommonConstants.GDDJ);
                    resultdisp.setIsFinish("0");
                    resultdisp.setImportDate(time);
                    if ("1".equals(resultdisp.getIsCollect())) {
                        gdglinfo.setZjczry(resultdisp.getPersonId());
                        gdglinfo.setZjbm(resultdisp.getDepartId());
                    } else {
                        resultdisp.setIsCollect("0");
                    }
                    //给处置人员发送消息
//                    gdglinfoMassage(gdglinfo, "6", CommonConstants.JGCZ, resultdisp.getPersonId(), gdglinfo.getDjsj(), CZ_URL, endDate, CZ_URLAPP);
                    jgczPerson = jgczPerson + resultdisp.getPersonId() + ",";
                }
                gdglinfo.setJgczPerson(jgczPerson);
                //插入之前需要删除该工单可能已有配置了结果处置的人员信息
                resultdispService.remove(Wrappers.<Resultdisp>lambdaQuery().eq(Resultdisp::getGdbh, info.getGdbh()));
                resultdispService.insertBatch(resultdispList);
            }
            //结果审核
            else if (GdglinfoEM.NOTENABLE.getType().equals(gdflowconfig.getRzshSfqy()) && GdglinfoEM.NOTENABLE.getType().equals(gdflowconfig.getRzczSfqy())
                    && GdglinfoEM.NOTENABLE.getType().equals(gdflowconfig.getRzzjSfqy()) && GdglinfoEM.NOTENABLE.getType().equals(gdflowconfig.getJgczSfqy())
                    && GdglinfoEM.ISENABLE.getType().equals(gdflowconfig.getJgshSfqy())) {
                gdglinfo.setProcessInfo("1,6");
                //工单登记添加审批链
                if (StringUtil.isNotNull(audit)) {
                    audit.setAuditPlanId(info.getId());
                    audit.setAuditState("0");
                    audit.setAuditType(AuditEnum.GD_TYPE.getCode());
                    Integer shrdj = info.getShrdj();
                    //比较审核人
                    if (StringUtil.isNotNull(shrdj)) {
                        Integer shjb = Integer.parseInt(gdflowconfig.getJgshCcjb());
                        if (shrdj < shjb) {
                            gdglinfo.setShrdj(shrdj + 1);
                            audit.setAuditLevel(shrdj + 1);
                        } else {
                            throw new ToflyDeniedException("添加审批人信息失败：已经达到最高审核级别");
                        }
                    } else {
                        gdglinfo.setShrdj(1);
                        audit.setAuditLevel(1);
                    }
                    gdglinfo.setJgczry(audit.getAuditUser());
                    List<Audit> auditList = new ArrayList<>();
                    auditList.add(audit);
                    boolean flag = saveAuditChain(auditList);
                    if (!flag) {
                        throw new ToflyDeniedException("添加审批人信息失败");
                    }
                } else {
                    throw new ToflyDeniedException("请添加审批人信息");
                }

                gdglinfo.setLcjd(Long.valueOf(GdglinfoEM.JGSH.getType()));
                if (gdflowconfig.getJgshShsx() != null) {
                    gdglinfo.setShsx(DateTimeUtil.dateTimeDifference(gdflowconfig.getJgshShsx(), Calendar.HOUR_OF_DAY));
                }
            } else if (!StringUtils.isEmpty(gdflowconfig.getAllLcjd()) && gdflowconfig.getAllLcjd().replace(",7", "").endsWith("1")) {
                gdglinfo.setJdsx(null);
                if (gdflowconfig.getTransferOutType() != null && Long.valueOf(GdglinfoEM.QWX.getType()).equals(gdflowconfig.getTransferOutType())) {
                    //工单标记挂起
                    gdglinfo.setHangUp("1");
                    gdglinfo.setLcjd(Long.valueOf(GdglinfoEM.GDDJ.getType()));
                    //转入抢维修，调用抢维修接口
                    String number = getQWX(extend, info);
                    if (!StringUtils.isEmpty(number)) {
                        GdglCirculation gdglCirculation = GdglCirculation.builder()
                                .gdbh(info.getGdbh())
                                .otherBh(number)
                                .createTime(new Date())
                                .type(gdflowconfig.getTransferOutType())
                                .build();
                        gdglCirculationService.save(gdglCirculation);
                    } else {
                        return ResultRespone.failed(false, "维修工单创建异常，工单保存失败！");
                    }

                } else {
                    gdglinfo.setProcessInfo("1,7");
                    gdglinfo.setLcjd(Long.valueOf(GdglinfoEM.GDGD.getType()));
                    gdglinfo.setFinishTime(new Date());
                    gdglinfo.setProcessDeposit("1,7");
                }
            }
            //设置整个工单时限时间
            Long gdsxNum = gdflowconfig.getGdzsx();
            if (StringUtil.isNotNull(gdsxNum)) {
                //计算整个工单时限时间
                Date gdsx = DateTimeUtil.dateTimeDifference(gdsxNum, Calendar.HOUR_OF_DAY);
                gdglinfo.setGdsx(gdsx);
            }
        }
        //汪截流：终止工单
        else if (Long.valueOf(GdglinfoEM.ZZ.getType()).equals(gdglinfo.getGddjZt())) {
            Gdglinfo uplinfo = new Gdglinfo();
            uplinfo.setZzry(SecurityUtils.getUserId());
            uplinfo.setZzsj(new Date());
            uplinfo.setJdzt("1");
            uplinfo.setLcjd(Long.valueOf(GdglinfoEM.GDGD.getType()));
            uplinfo.setFinishTime(new Date());
            uplinfo.setProcessDeposit(sub1(info.getProcessDeposit() + ",7"));
            uplinfo.setProcessInfo(sub1(info.getProcessInfo() + ",7"));
            uplinfo.setGdzzzt("1");
            uplinfo.setId(gdglinfo.getId());
            uplinfo.setLczzyy(gdglinfo.getLczzyy());

            if (!stopQWX(gdglinfo, info)) {
                return ResultRespone.failed("工单终止抢维修失败！");
            }
            return ResultRespone.success(gdglinfoService.updateById(uplinfo));
        }
        removeDB(gdglinfo.getId(), CommonConstants.GDDJ);
        //抄表历史用户里更改故障抄表状态，并保存工单ID(可能多个的情况，用逗号隔开)
        //由于是修改工单，所以注意是否有修改后的用户编号
        String yhbh = gdglinfo.getKhbh();
        if (StringUtil.isEmpty(yhbh)) {
            yhbh = info.getKhbh();
        }
        if (StringUtil.isNotEmpty(gdflowconfig.getViewType())) {
            //判断是否抄表故障工单
            if (StringUtil.isNotEmpty(yhbh) && gdflowconfig.getViewType().contains("991")) {
                //获取当前年月
                String yearMonth = Date8Util.getYearMonth();
                ReadEntity readEntity = baseMapper.getReadYhbh(yhbh, yearMonth);
                if (StringUtil.isNotNull(readEntity)) {
                    //是否已经抄表，抄了表才可以上报工单
                    if ("1".equals(readEntity.getCbbz())) {
                        String orderIds = readEntity.getOrderIds();
                        if (StringUtil.isNotEmpty(orderIds)) {
                            orderIds = info.getId() + ",";
                        } else {
                            orderIds = orderIds + info.getId() + ",";
                        }
                        boolean updateReadFlag = baseMapper.updateRead(yhbh, yearMonth, orderIds);
                    }
                }
            }
        }
        boolean update = gdglinfoService.updateById(gdglinfo);
        callbackForeign(gdglinfo, info);
        return ResultRespone.success(update);
    }


    private String getQWX(GdglinfoExtendDto extend, Gdglinfo info) {
        RepairorderDto repairorderDto = new RepairorderDto();
        BeanUtils.copyProperties(extend, repairorderDto);
        repairorderDto.setOrderSource("2");
        repairorderDto.setNum(1L);
        repairorderDto.setNotes(info.getGdms());
        repairorderDto.setPercent(100f);
        repairorderDto.setDispatchingId(SecurityUtils.getUserId());
        repairorderDto.setIsDispatching("1");
        repairorderDto.setAddress(extend.getAddress());
        repairorderDto.setLgtd(extend.getLgtd());
        repairorderDto.setLttd(extend.getLttd());
        RepairuserChildDto rc = new RepairuserChildDto();
        rc.setRespUser(extend.getRespUser());
        rc.setRatifyTime(1d);
        rc.setPlanNum(1L);
        rc.setPhone(extend.getPhone());
        LngLats lngLats = new LngLats();
        lngLats.setX(extend.getLgtd());
        lngLats.setY(extend.getLttd());
        lngLats.setAddress(extend.getAddress());
        List<LngLats> lngLatsList = new ArrayList<>();
        lngLatsList.add(lngLats);
        rc.setLngLats(JSON.toJSONString(lngLatsList));
        repairorderDto.setRepairUserChildDtoList(Arrays.asList(rc));
        String address = extend.getAddress();
        Double lgtd = extend.getLgtd();
        Double lttd = extend.getLttd();
        if (StringUtil.isNotEmpty(address)) {
            repairorderDto.setAddress(address);
        } else {
            repairorderDto.setAddress(info.getAddress());
        }
        if (StringUtil.isNotNull(lgtd) && StringUtil.isNotNull(lttd)) {
            repairorderDto.setLgtd(lgtd);
            repairorderDto.setLttd(lttd);
        } else {
            repairorderDto.setLgtd(info.getLgtd());
            repairorderDto.setLttd(info.getLttd());
        }
        ResultRespone r = orderClient.saveRepairOrderFeign(repairorderDto);
        Object obj = r.getResult();
        return String.valueOf(obj);
    }


    @Override
    public boolean gdglToPwxPlaceOrder(GdglinfoExtendDto extend) {
        Gdglinfo info = this.getById(extend.getId());
        if (info == null) {
            return false;
        }
        String number = getQWX(extend, info);
        if (!StringUtils.isEmpty(number)) {
            GdglCirculation gdglCirculation = GdglCirculation.builder()
                    .gdbh(info.getGdbh())
                    .otherBh(number)
                    .createTime(new Date())
                    .type(Long.valueOf(GdglinfoEM.QWX.getType()))
                    .build();
            gdglCirculationService.save(gdglCirculation);
            return this.update(new UpdateWrapper<Gdglinfo>().lambda().set(Gdglinfo::getHangUp, "1").eq(Gdglinfo::getId, info.getId()));
        }
        return false;
    }

    @Override
    public ResultRespone updateGDGDLxInfo(Long id, Long lxid, String remarks) {
        Gdglinfo gdglinfo = this.getById(id);
        if (gdglinfo == null) {
            ResultRespone.failed("工单不存在!");
        }
        if (!gdglinfo.getLcjd().equals(Long.valueOf(GdglinfoEM.GDGD.getType()))) {
            ResultRespone.failed("工单未归档!");
        }
        Gdgltypebm gdgltypebm = gdgltypebmService.getOne(new QueryWrapper<Gdgltypebm>().lambda().eq(Gdgltypebm::getStatusFlag, "1")
                .eq(Gdgltypebm::getId, lxid).eq(Gdgltypebm::getDataType, "1").eq(Gdgltypebm::getYxbz, "1"));
        if (gdgltypebm == null) {
            ResultRespone.failed("类型不存在或无效!");
        }
        return ResultRespone.success(this.update(new UpdateWrapper<Gdglinfo>().lambda()
                .set(Gdglinfo::getGdgzlx, lxid)
                .set(Gdglinfo::getGdgzyy, remarks)
                .set(Gdglinfo::getGzszry, SecurityUtils.getUserId()).eq(Gdglinfo::getId, id)));

    }

    /**
     * 外部调用创建工单
     *
     * @param dto      参数
     * @param fileList 文件集合
     * @return
     */
    @Override
    public ResultRespone foreignSaveOrder(ForeignOrderDto dto, List<MultipartFile> fileList) {
        GdglinfoExtendDto gdinfo = new GdglinfoExtendDto();
        List<Resultdisp> resultdispList = null;
        BeanUtils.copyProperties(dto, gdinfo);
        gdinfo.setLcid(Long.valueOf(dto.getGdlxid()));
        gdinfo.setForeignId(dto.getGdid());
        gdinfo.setJjcd(82L);
        gdinfo.setDjry(SecurityUtils.getUserId());
        gdinfo.setDjbm(SecurityUtils.getUserDeptId());
        gdinfo.setDjsj(new Date());
        gdinfo.setGddjZt(Long.valueOf(GdglinfoEM.XYGHJ.getType()));
        gdinfo.setForeignType(CommonConstants.WT.equals(dto.getTpname()) ? "0" : "9");
        gdinfo.setForeignState("0");
        Long gdlcid = Long.parseLong(dto.getGdlxid());
        Gdflowconfig gdflowconfig = gdflowconfigService.getById(gdlcid);
        gdinfo.setGdlx(gdflowconfig.getGdlx());
        gdinfo.setGdxf1(gdflowconfig.getGdxf1());
        gdinfo.setGdxf2(gdflowconfig.getGdxf2());
        if (GdglinfoEM.ISENABLE.getType().equals(gdflowconfig.getRzczSfqy())) {
            Gdperson gdperson = gdpersonService.getGdperson(gdlcid, 2);
            gdinfo.setSlry(String.valueOf(gdperson.getPersonId()));
            gdinfo.setSlbm(String.valueOf(gdperson.getDepartId()));
        } else if (GdglinfoEM.ISENABLE.getType().equals(gdflowconfig.getRzshSfqy())) {
            Gdperson gdperson = gdpersonService.getGdperson(gdlcid, 3);
            gdinfo.setRzslry(gdperson.getPersonId());
            gdinfo.setRzbm(gdperson.getDepartId());
        } else if (GdglinfoEM.ISENABLE.getType().equals(gdflowconfig.getRzzjSfqy())) {
            Gdperson gdperson = gdpersonService.getGdperson(gdlcid, 4);
            gdinfo.setShslry(gdperson.getPersonId());
            gdinfo.setShbm(gdperson.getDepartId());
        } else if (GdglinfoEM.ISENABLE.getType().equals(gdflowconfig.getJgczSfqy())) {
            resultdispList = new ArrayList<>();
            Gdperson gdperson = gdpersonService.getGdperson(gdlcid, 5);
            Resultdisp resultdisp = new Resultdisp();
            resultdispList.add(resultdisp);
            resultdisp.setDepartId(gdperson.getDepartId());
            resultdisp.setDepartName(gdperson.getDepartName());
            resultdisp.setPersonId(gdperson.getPersonId());
            resultdisp.setPersonName(gdperson.getPersonName());
            resultdisp.setIsCollect(Constate.YES);
        } else if (GdglinfoEM.ISENABLE.getType().equals(gdflowconfig.getJgshSfqy())) {
            Gdperson gdperson = gdpersonService.getGdperson(gdlcid, 6);
            Audit audit = new Audit();
            audit.setAuditUser(gdperson.getPersonId());
            gdinfo.setAudit(audit);
        }
        return saveGdglInfo(fileList, gdinfo, resultdispList);
    }

    /**
     * 回调三方接口返回处理结果
     */
    @Override
    public void foreignOrderCallback() {
        List<Gdglinfo> gdglinfos = this.list(new QueryWrapper<Gdglinfo>().lambda().eq(Gdglinfo::getLcjd, Long.parseLong(GdglinfoEM.GDGD.getType()))
                .eq(Gdglinfo::getForeignState, Constate.NO).isNotNull(Gdglinfo::getForeignId).isNotNull(Gdglinfo::getForeignType));
        for (Gdglinfo gdglinfo : gdglinfos) {
            sendForeignOrder(gdglinfo);
        }


    }

    private void sendForeignOrder(Gdglinfo gdglinfo) {
        if (Constate.NO.equals(gdglinfo.getForeignType())) {
            try {
                TreeMap<String, Object> map = new TreeMap<>();
                map.put("gdid", gdglinfo.getForeignId());
                map.put("cltime", DateUtil.formatDateTime(gdglinfo.getFinishTime()));
                if (!StringUtils.isEmpty(gdglinfo.getShyj())) {
                    map.put("gdzt", gdglinfo.getShyj());
                }
                if (!StringUtils.isEmpty(gdglinfo.getCzyj())) {
                    map.put("cljg", gdglinfo.getCzyj());
                }
                String zzjl = null;
                String pd = gdglinfo.getProcessDeposit().trim().replace(",", "").replace("7", "");
                String jd = pd.substring(pd.length() - 1);
                if (jd.equals("6")) {
                    Audit audit = new Audit();
                    audit.setAuditType(AuditEnum.GD_TYPE.getCode());
                    audit.setAuditPlanId(gdglinfo.getId());
                    List<Audit> audits = auditClient.getAuditInfo(audit).getResult();
                    int auditLevel = 0;
                    for (Audit ad : audits) {
                        if (ad.getAuditLevel() >= auditLevel) {
                            zzjl = ad.getAuditNote();
                        }
                    }
                } else if (jd.equals("5")) {
                    zzjl = gdglinfo.getCzyj();
                } else if (jd.equals("4")) {
                    zzjl = gdglinfo.getZjyj();
                } else if (jd.equals("3")) {
                    zzjl = gdglinfo.getShyj();
                } else if (jd.equals("2")) {
                    zzjl = gdglinfo.getRzyj();
                } else {
                    zzjl = gdglinfo.getGdms();
                }
                map.put("zzjl", zzjl);
                map.put("timestamp", System.currentTimeMillis() / 1000);
                map.put("nonce", RandomUtil.randomString(10));
                String rStr = ForeignHttpUtils.sendPost(wturl, wtpath, wtkey, map);
                if ("9999".equals(rStr)) {
                    this.update(new UpdateWrapper<Gdglinfo>().lambda().set(Gdglinfo::getForeignState, Constate.NO)
                            .eq(Gdglinfo::getId, gdglinfo.getId()));
                }
            } catch (Exception e) {
                log.error("异常：", e);

            }
        }
    }


    /**
     * 认证处置
     *
     * @param fileList
     * @param extend
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultRespone saveCertification(List<MultipartFile> fileList, GdglinfoExtendDto extend, List<Resultdisp> resultdispList) {
        //审批链
        Audit audit = extend.getAudit();
        Gdglinfo gdglinfo = new Gdglinfo();
        BeanUtils.copyProperties(extend, gdglinfo);
        //通过工单类型来获取配置状态
        Gdglinfo info = gdglinfoService.getById(gdglinfo.getId());
        if ("0".equals(info.getJdzt())) {
            gdglinfo.setJdzt("1");
        }
        if (!info.getLcjd().equals(Long.valueOf(GdglinfoEM.RZCZ.getType()))) {
            ResultRespone.failed("工单不存在或工单不是认证处置节点");
        }
        Gdflowconfig gdflowconfig = gdflowconfigService.getById(info.getLcid());
        Long tzry = null;
        String routeip = null;
        String routeipapp = null;
        Date endDate = null;
        String topicName = null;

        if (Long.valueOf(GdglinfoEM.BHJ.getType()).equals(gdglinfo.getLczt())) {
            fileUploadAmend(fileList, gdglinfo);
            gdglinfo.setRzry(SecurityUtils.getUserId());
            // 判断是否为漏点
            if ("1".equals(gdglinfo.getIsLeak())) {
                BigDecimal estimatedWaterLoss = BigDecimal.ZERO;
                String isReal = "0";
                LeakInfo leakInfo = extend.getLeakInfo();
                if(null!=leakInfo){
                    estimatedWaterLoss = leakInfo.getEstimatedWaterLoss();
                    isReal = leakInfo.getIsReal();
                }
                leakInfoService.update(new UpdateWrapper<LeakInfo>().lambda()
                        .eq(LeakInfo::getGdinfoId, gdglinfo.getId())
                        .set(LeakInfo::getEstimatedWaterLoss,estimatedWaterLoss)
                        .set(LeakInfo::getIsReal,isReal));
            }
        } else if (Long.valueOf(GdglinfoEM.XYGHJ.getType()).equals(gdglinfo.getLczt())) {
            //如果跳转环节需要判断该环节是否有权限
            fileUploadAmend(fileList, gdglinfo);
            gdglinfo.setRzry(SecurityUtils.getUserId());
            gdglinfo.setRzsj(new Date());
            //计算认证超时时间
            double dt = dateBetweenHour(new Date(), info.getRzsx());
            if (dt > 0) {
                gdglinfo.setRzczCszt("1");
                gdglinfo.setRzczCssj(String.valueOf(dt));
            }
            //去重
            StringBuilder str = new StringBuilder(gdglinfo.getProcessDeposit());
            str.append(",2");
            gdglinfo.setProcessDeposit(sub1(String.valueOf(str)));
            gdglinfo.setRzczFssj(new Date());

            if (GdglinfoEM.NOTENABLE.getType().equals(gdflowconfig.getRzshSfqy())
                    && GdglinfoEM.NOTENABLE.getType().equals(gdflowconfig.getRzzjSfqy()) && GdglinfoEM.NOTENABLE.getType().equals(gdflowconfig.getJgczSfqy())
                    && GdglinfoEM.ISENABLE.getType().equals(gdflowconfig.getJgshSfqy())) {
                gdglinfo.setProcessInfo("1,2,6");
                //工单登记添加审批链
                if (StringUtil.isNotNull(audit)) {
                    audit.setAuditState("0");
                    audit.setAuditPlanId(info.getId());
                    audit.setAuditType(AuditEnum.GD_TYPE.getCode());
                    gdglinfo.setLcjd(Long.valueOf(GdglinfoEM.JGSH.getType()));
                    tzry = gdglinfo.getJgczry();
                    routeip = JGSH_URL;
                    routeipapp = JGSH_URLAPP;
                    topicName = CommonConstants.JGSH;
                    if (gdflowconfig.getJgshShsx() != null) {
                        gdglinfo.setShsx(DateTimeUtil.dateTimeDifference(gdflowconfig.getJgshShsx(), Calendar.HOUR_OF_DAY));
                        endDate = gdglinfo.getShsx();
                    }
                    gdglinfo.setShrdj(1);
                    audit.setAuditLevel(1);
                    gdglinfo.setJgczry(audit.getAuditUser());
                    List<Audit> auditList = new ArrayList<>();
                    auditList.add(audit);
                    boolean flag = saveAuditChain(auditList);
                    if (!flag) {
                        throw new ToflyDeniedException("添加审批人信息失败");
                    }
                } else {
                    throw new ToflyDeniedException("请添加审批人信息");
                }
                // 判断是否为漏点
                if ("1".equals(gdglinfo.getIsLeak())) {
                    BigDecimal estimatedWaterLoss = BigDecimal.ZERO;
                    String isReal = "0";
                    LeakInfo leakInfo = extend.getLeakInfo();
                    if(null!=leakInfo){
                        estimatedWaterLoss = leakInfo.getEstimatedWaterLoss();
                        isReal = leakInfo.getIsReal();
                    }
                    leakInfoService.update(new UpdateWrapper<LeakInfo>().lambda()
                            .eq(LeakInfo::getGdinfoId, gdglinfo.getId())
                            .set(LeakInfo::getEstimatedWaterLoss,estimatedWaterLoss)
                            .set(LeakInfo::getIsReal,isReal)
                            .set(LeakInfo::getDisposeState, LeakStateEnum.DSH.getCode()));
                }
                // 判断是否为噪音
                if ("1".equals(gdglinfo.getIsNoise())) {
                    noiseUploadService.update(new UpdateWrapper<NoiseLoggerInfo>().lambda()
                            .eq(NoiseLoggerInfo::getGdinfoId, gdglinfo.getId())
                            .set(NoiseLoggerInfo::getDisposeState, NoiseStateEnum.DSH.getCode())
                    );

                }


            }
//             else if (!StringUtils.isEmpty(gdflowconfig.getAllLcjd()) && gdflowconfig.getAllLcjd().replace(",7", "").endsWith("2")) {
//                if (gdflowconfig.getTransferOutType() != null && Long.valueOf(GdglinfoEM.QWX.getType()).equals(gdflowconfig.getTransferOutType())) {
//                    //工单标记挂起
//                    gdglinfo.setHangUp("1");
//                    if (callSwitchToInterface(extend, info, gdflowconfig)) {
//                        return ResultRespone.failed(false, "维修工单创建异常，工单保存失败！");
//                    }
//                } else {
//                    gdglinfo.setLcjd(Long.valueOf(GdglinfoEM.GDGD.getType()));
//                    gdglinfo.setFinishTime(new Date());
//                    gdglinfo.setProcessDeposit(sub1(gdglinfo.getProcessDeposit().concat(",7")));
//                    gdglinfo.setProcessInfo("1,2,7");
//                }
//            }
        } else if (Long.valueOf(GdglinfoEM.BH.getType()).equals(gdglinfo.getLczt())) {
            gdglinfo.setProcessDeposit(null);
            gdglinfo.setProcessInfo("1");
            gdglinfo.setLcjd(Long.valueOf(GdglinfoEM.GDDJ.getType()));
            gdglinfo.setBhzt("1");
            gdglinfo.setJdzt("0");
            gdglinfo.setJdsx(null);
            Gdglflow gdglflow = new Gdglflow();
            gdglflow.setGdbh(gdglinfo.getGdbh());
            gdglflow.setClry(SecurityUtils.getUser().getRealName());
            gdglflow.setClsj(gdglinfo.getRzsj());
            gdglflow.setClyj(gdglinfo.getBhyy());
            gdglflow.setLcjd(codeClient.getname(Long.valueOf(GdglinfoEM.RZCZ.getType())));
            gdglflow.setBbhLcjd(codeClient.getname(gdglinfo.getLcjd()));
            //新增被驳回的信息及时间
            gdglflow.setBbhYj(info.getGdms());
            gdglflow.setBbhClsj(info.getJdsx());
            gdglflowService.save(gdglflow);
            gdglinfoMassage(gdglinfo, "6", CommonConstants.GDDJ, gdglinfo.getDjry(), null, GD_URL, null, GD_URLAPP);
        } else if (Long.valueOf(GdglinfoEM.ZP.getType()).equals(gdglinfo.getLczt())) {
            gdglinfo.setZpzt("1");
            tzry = Long.valueOf(gdglinfo.getSlry());
            routeip = RZ_URL;
            routeipapp = RZ_URLAPP;
            topicName = CommonConstants.RZCL;
            Redeploy redeploy = new Redeploy();
            redeploy.setClbm(SecurityUtils.getUser().getDepartmentId());
            redeploy.setZpry(SecurityUtils.getUser().getRealName());
            redeploy.setLcjd(codeClient.getname(gdglinfo.getLcjd()));
            redeploy.setGdbh(gdglinfo.getGdbh());
            redeploy.setZpyj(gdglinfo.getZpyj());
            //增加接收人
            redeploy.setJsry(tzry);
            redeployService.save(redeploy);
            // 给转派人发送短信
//            ResultRespone<User> byId = userClent.getById(tzry);
//            String phone = byId.getResult().getPhone();
//            // 发送短信给处置人员
//            SendMessage sendMessage = new SendMessage();
//            sendMessage.setLxdh(phone);
//            sendMessage.setTxlx("2");
//            String sjdh = gdglinfo.getSjdh()==null?"无":gdglinfo.getSjdh();
//            String gdms = gdglinfo.getGdms() == null ? "无" : gdglinfo.getGdms();
//            sendMessage.setTxnr("工单地址: "+gdglinfo.getAddress()+",工单说明: "+gdms+",联系电话: "+sjdh+",请前往'掌上统一办公APP'处理");
//            SendNoteEn sendNoteEn = new SendNoteEn();
//            List<SendMessage> sendMessageList = new ArrayList<>();
//            sendMessageList.add(sendMessage);
//            sendNoteEn.setSendMessageList(sendMessageList);
//            sendMessageFeign.sendMessage(sendNoteEn);

        }
        //添加消息
        if (tzry != null) {
            gdglinfoMassage(gdglinfo, "6", topicName, tzry, gdglinfo.getRzsj(), routeip, endDate, routeipapp);
        }
        gdglinfo.setBhyy(null);
        gdglinfo.setZpyj(null);
        // 本环节不消除待办
        if (!Long.valueOf(GdglinfoEM.BHJ.getType()).equals(gdglinfo.getLczt())) {
            removeDB(gdglinfo.getId(), CommonConstants.RZCL);
        }
        boolean update = gdglinfoService.updateById(gdglinfo);
//        callbackForeign(gdglinfo, info);
        return ResultRespone.success(update);
    }

    /**
     * 判断回调网厅、抄表
     *
     * @param gdglinfo
     * @param info
     */
    private void callbackForeign(Gdglinfo gdglinfo, Gdglinfo info) {
        if (!StringUtils.isEmpty(info.getForeignId()) && "0".equals(info.getForeignState())
                && Long.valueOf(GdglinfoEM.GDGD.getType()).equals(gdglinfo.getLcjd())) {
            sendForeignOrder(this.getById(gdglinfo.getId()));
        }
    }

    private boolean gdglBHMessage(Gdglinfo gdglinfo, String s, String topic, Long slry, String routeip, String routeipapp) {
        //驳回消息添加
        Messagepush messagepush = new Messagepush();
        messagepush.setRouteIp(routeip);
        messagepush.setRouteIpApp(routeipapp);
        messagepush.setMessage(gdglinfo.getGdms());
        messagepush.setType(s);
        messagepush.setTopic(topic);
        ResultRespone<Long> rl = messageClient.save(messagepush);
        if (rl != null) {
            Long result1 = rl.getResult();
            //添加指派人
            Messagerecipient messagerecipient = new Messagerecipient();

            messagerecipient.setMessageId(result1);
            messagerecipient.setRecipient(slry);
            messageStateClient.save(messagerecipient);
            return true;
        } else {
            return false;
        }
    }


    @Override
    public ResultRespone orderReview(GdglinfoExtendDto extend, List<Resultdisp> resultdispList) {
        //审批链
        Audit audit = extend.getAudit();
        //通过工单类型来获取配置状态
        Gdglinfo gdglinfo = new Gdglinfo();
        BeanUtils.copyProperties(extend, gdglinfo);
        //认证审核超时
        Gdglinfo info = gdglinfoService.getById(gdglinfo.getId());
        if ("0".equals(info.getJdzt())) {
            gdglinfo.setJdzt("1");
        }
        if (info == null || !info.getLcjd().equals(Long.valueOf(GdglinfoEM.GDSH.getType()))) {
            ResultRespone.failed("工单不存在或工单流程节点不是认证审核");
        }
        Gdflowconfig gdflowconfig = gdflowconfigService.getById(info.getLcid());
        double dt = dateBetweenHour(new Date(), info.getShsx());
        Long tzry = null;
        String routeip = null;
        String routeipapp = null;
        String topicName = null;
        Date endDate = null;
        //本环节
        if (Long.valueOf(GdglinfoEM.BHJ.getType()).equals(gdglinfo.getShzt())) {
            gdglinfo.setShry(SecurityUtils.getUserId());
        }
        //下一环节
        else if (Long.valueOf(GdglinfoEM.XYGHJ.getType()).equals(gdglinfo.getShzt())) {
            //当前处理环节是否超时
            if (dt > 0) {
                gdglinfo.setReshCszt("1");
                gdglinfo.setReshCssj(String.valueOf(dt));
            }
            //添加每个流程节点标识
            StringBuilder str = new StringBuilder(gdglinfo.getProcessDeposit());
            str.append(",3");
            gdglinfo.setProcessDeposit(sub1(String.valueOf(str)));
            //根据流程配置判断需要跳往那一节点
            if (GdglinfoEM.ISENABLE.getType().equals(gdflowconfig.getRzzjSfqy())) {
                //下一流程节点
                StringBuilder process = new StringBuilder(info.getProcessInfo());
                process.append(",4");
                gdglinfo.setProcessInfo(sub1(String.valueOf(process)));
                gdglinfo.setLcjd(Long.valueOf(GdglinfoEM.GDZJ.getType()));
                tzry = gdglinfo.getShslry();
                routeip = ZJ_URL;
                routeipapp = ZJ_URLAPP;
                topicName = CommonConstants.RZZJ;
                if (gdflowconfig.getRzzjZjsx() != null) {
                    gdglinfo.setZjsx(DateTimeUtil.dateTimeDifference(gdflowconfig.getRzzjZjsx(), Calendar.HOUR_OF_DAY));
                    endDate = gdglinfo.getZjsx();
                }
            } else if (GdglinfoEM.NOTENABLE.getType().equals(gdflowconfig.getRzzjSfqy()) && GdglinfoEM.ISENABLE.getType().equals(gdflowconfig.getJgczSfqy())) {
                //下一流程节点
                StringBuilder process = new StringBuilder(info.getProcessInfo());
                process.append(",5");
                gdglinfo.setProcessInfo(sub1(String.valueOf(process)));
                if (StringUtil.isNull(resultdispList) || resultdispList.size() == 0) {
                    throw new ToflyDeniedException("请选择结果处置人员信息");
                }
                gdglinfo.setLcjd(Long.valueOf(GdglinfoEM.JGCZ.getType()));
//                tzry = gdglinfo.getZjczry();
//                routeip = CZ_URL;
//                routeipapp = CZ_URLAPP;
//                topicName = CommonConstants.JGCZ;
                if (gdflowconfig.getJgczCzsx() != null) {
                    gdglinfo.setCzsx(DateTimeUtil.dateTimeDifference(gdflowconfig.getJgczCzsx(), Calendar.HOUR_OF_DAY));
                    endDate = gdglinfo.getCzsx();
                }
                //上一流程选择的多人处置的情况
                Long maxId = resultdispService.getMaxId();
                String jgczPerson = "";
                Date time = new Date();
                for (Resultdisp resultdisp : resultdispList) {
                    resultdisp.setId(maxId++);
                    resultdisp.setGdbh(info.getGdbh());
                    resultdisp.setImportLcjd(41L);
                    resultdisp.setLcjdName(CommonConstants.RZSH);
                    resultdisp.setIsFinish("0");
                    resultdisp.setImportDate(time);
                    if ("1".equals(resultdisp.getIsCollect())) {
                        //设置汇集人是认证质检的处理人员
                        gdglinfo.setZjczry(resultdisp.getPersonId());
                        gdglinfo.setZjbm(resultdisp.getDepartId());
                    } else {
                        resultdisp.setIsCollect("0");
                    }
                    //给处置人员发送消息
                    gdglinfoMassage(gdglinfo, "6", CommonConstants.JGCZ, resultdisp.getPersonId(), gdglinfo.getDjsj(), CZ_URL, endDate, CZ_URLAPP);
                    jgczPerson = jgczPerson + resultdisp.getPersonId() + ",";
                }
                gdglinfo.setJgczPerson(jgczPerson);
                //插入之前需要删除该工单可能已有配置了结果处置的人员信息
                resultdispService.remove(Wrappers.<Resultdisp>lambdaQuery().eq(Resultdisp::getGdbh, info.getGdbh()));
                resultdispService.insertBatch(resultdispList);
            } else if (GdglinfoEM.NOTENABLE.getType().equals(gdflowconfig.getRzzjSfqy()) && GdglinfoEM.NOTENABLE.getType().equals(gdflowconfig.getJgczSfqy())
                    && GdglinfoEM.ISENABLE.getType().equals(gdflowconfig.getJgshSfqy())) {
                //下一流程节点
                StringBuilder process = new StringBuilder(info.getProcessInfo());
                process.append(",6");
                gdglinfo.setProcessInfo(sub1(String.valueOf(process)));
                //工单登记添加审批链
                if (StringUtil.isNotNull(audit)) {
                    audit.setAuditPlanId(info.getId());
                    audit.setAuditState("0");
                    audit.setAuditType(AuditEnum.GD_TYPE.getCode());
                    Integer shrdj = info.getShrdj();
                    //比较审核人
                    if (StringUtil.isNotNull(shrdj)) {
                        Integer shjb = Integer.parseInt(gdflowconfig.getJgshCcjb());
                        if (shrdj < shjb) {
                            gdglinfo.setShrdj(shrdj + 1);
                            audit.setAuditLevel(shrdj + 1);
                        } else {
                            throw new ToflyDeniedException("添加审批人信息失败：已经达到最高审核级别");
                        }
                    } else {
                        gdglinfo.setShrdj(1);
                        audit.setAuditLevel(1);
                    }
                    gdglinfo.setJgczry(audit.getAuditUser());
                    List<Audit> auditList = new ArrayList<>();
                    auditList.add(audit);
                    boolean flag = saveAuditChain(auditList);
                    if (!flag) {
                        throw new ToflyDeniedException("添加审批人信息失败");
                    }
                } else {
                    throw new ToflyDeniedException("请添加审批人信息");
                }
                gdglinfo.setLcjd(Long.valueOf(GdglinfoEM.JGSH.getType()));
                tzry = gdglinfo.getJgczry();
                routeip = JGSH_URL;
                routeipapp = JGSH_URLAPP;
                topicName = CommonConstants.JGSH;
                if (gdflowconfig.getJgshShsx() != null) {
                    gdglinfo.setShsx(DateTimeUtil.dateTimeDifference(gdflowconfig.getJgshShsx(), Calendar.HOUR_OF_DAY));
                    endDate = gdglinfo.getShsx();
                }
            } else if (!StringUtils.isEmpty(gdflowconfig.getAllLcjd()) && gdflowconfig.getAllLcjd().replace(",7", "").endsWith("3")) {
                if (gdflowconfig.getTransferOutType() != null && Long.valueOf(GdglinfoEM.QWX.getType()).equals(gdflowconfig.getTransferOutType())) {
                    //工单标记挂起
                    gdglinfo.setHangUp("1");
                    if (callSwitchToInterface(extend, info, gdflowconfig)) {
                        return ResultRespone.failed(false, "维修工单创建异常，工单保存失败！");
                    }
                } else {
                    //下一流程节点
                    StringBuilder process = new StringBuilder(info.getProcessInfo());
                    process.append(",7");
                    gdglinfo.setProcessInfo(sub1(String.valueOf(process)));
                    gdglinfo.setLcjd(Long.valueOf(GdglinfoEM.GDGD.getType()));
                    gdglinfo.setFinishTime(new Date());
                    gdglinfo.setProcessDeposit(sub1(gdglinfo.getProcessDeposit().concat(",7")));
                }
            }
            gdglinfo.setShry(SecurityUtils.getUserId());
            gdglinfo.setShsj(new Date());
        } else if (Long.valueOf(GdglinfoEM.BH.getType()).equals(gdglinfo.getShzt())) {
            if (!StringUtils.isEmpty(gdglinfo.getProcessDeposit()) && gdglinfo.getProcessDeposit().contains("3")) {
                gdglinfo.setProcessDeposit(sub2(gdglinfo.getProcessDeposit()));
            }
            if (!StringUtils.isEmpty(gdglinfo.getProcessDeposit()) && gdglinfo.getProcessDeposit().length() > 2) {
                gdglinfo.setProcessDeposit(sub2(gdglinfo.getProcessDeposit()));
            }
            //驳回设置上一流程的节点过程
            gdglinfo.setProcessInfo(sub2(info.getProcessInfo()));
            gdglinfo.setBhzt("1");
            Gdglflow gdglflow = new Gdglflow();
            gdglflow.setGdbh(gdglinfo.getGdbh());
            gdglflow.setClry(SecurityUtils.getUser().getRealName());
            gdglflow.setClsj(gdglinfo.getShsj());
            gdglflow.setClyj(gdglinfo.getBhyy());
            gdglflow.setLcjd(codeClient.getname(Long.valueOf(GdglinfoEM.GDSH.getType())));
            gdglflow.setBbhLcjd(codeClient.getname(gdglinfo.getLcjd()));
            //添加保存驳回的信息
            if (!StringUtils.isEmpty(gdglinfo.getProcessDeposit()) && gdglinfo.getProcessDeposit().contains("2")) {
                gdglflow.setBbhYj(info.getRzyj());
                gdglflow.setBbhClsj(info.getRzsj());
                gdglflow.setBbhFileid(info.getRzFileid());
            } else {
                gdglflow.setBbhYj(info.getGdms());
                gdglflow.setBbhClsj(info.getJdsx());
            }
            Long bhtzry = null;
            String bhrouteip = null;
            String bhrouteipapp = null;
            String bhTopicName = null;
            if (GdglinfoEM.ISENABLE.getType().equals(gdflowconfig.getRzczSfqy())) {
                gdglinfo.setLcjd(Long.valueOf(GdglinfoEM.RZCZ.getType()));
                bhtzry = Long.valueOf(gdglinfo.getSlry());
                bhrouteip = RZ_URL;
                bhrouteipapp = RZ_URLAPP;
                bhTopicName = CommonConstants.RZCL;
            } else {
                bhtzry = gdglinfo.getDjry();
                bhrouteip = GD_URL;
                bhrouteipapp = GD_URLAPP;
                bhTopicName = CommonConstants.GDDJ;
                gdglinfo.setProcessDeposit(null);
                gdglinfo.setLcjd(Long.valueOf(GdglinfoEM.GDDJ.getType()));
                gdglinfo.setJdzt("0");
                baseMapper.update(null, new UpdateWrapper<Gdglinfo>().setSql("JDSX = NULL,PROCESS_DEPOSIT = NULL ").lambda().eq(Gdglinfo::getId, gdglinfo.getId()));
            }
            gdglflowService.save(gdglflow);
            //驳回消息添加
            //gdglBHMessage(gdglinfo, "6", "工单审核驳回", bhtzry,bhrouteip);
            gdglinfoMassage(gdglinfo, "6", bhTopicName, bhtzry, null, bhrouteip, null, bhrouteipapp);
        } else if (Long.valueOf(GdglinfoEM.ZP.getType()).equals(gdglinfo.getShzt())) {
            gdglinfo.setZpzt("1");
            Redeploy redeploy = new Redeploy();
            redeploy.setClbm(SecurityUtils.getUser().getDepartmentId());
            redeploy.setZpry(SecurityUtils.getUser().getRealName());
            redeploy.setLcjd(codeClient.getname(gdglinfo.getLcjd()));
            redeploy.setGdbh(gdglinfo.getGdbh());
            redeploy.setZpyj(gdglinfo.getZpyj());
            redeploy.setJsry(gdglinfo.getRzslry());
            redeployService.save(redeploy);
            tzry = gdglinfo.getRzslry();
            routeip = RZSH_URL;
            routeipapp = RZSH_URLAPP;
            topicName = CommonConstants.RZSH;
        }
        if (tzry != null) {
            gdglinfoMassage(gdglinfo, "6", topicName, tzry, gdglinfo.getShsj(), routeip, endDate, routeipapp);
        }
        gdglinfo.setBhyy(null);
        gdglinfo.setZpyj(null);
        removeDB(gdglinfo.getId(), CommonConstants.RZSH);
        boolean update = gdglinfoService.updateById(gdglinfo);
        callbackForeign(gdglinfo, info);
        return ResultRespone.success(update);
    }

    @Override
    public ResultRespone qcCheck(GdglinfoExtendDto extend, List<Resultdisp> resultdispList) {
        //审批链
        Audit audit = extend.getAudit();
        Gdglinfo gdglinfo = new Gdglinfo();
        BeanUtils.copyProperties(extend, gdglinfo);
        //通过工单类型来获取配置状态
        //质检超时计算
        Gdglinfo info = gdglinfoService.getById(gdglinfo.getId());
        if ("0".equals(info.getJdzt())) {
            gdglinfo.setJdzt("1");
        }
        if (info == null || info.getLcjd().equals(Long.valueOf(GdglinfoEM.GDZJ.getType()))) {
            ResultRespone.failed("工单不存在或工单流程节点不是认证质检");
        }
        Gdflowconfig gdflowconfig = gdflowconfigService.getById(info.getLcid());
        double dt = dateBetweenHour(new Date(), info.getZjsx());
        Long tzry = null;
        String routeip = null;
        String routeipapp = null;
        Date endDate = null;
        String topicName = null;
        if (Long.valueOf(GdglinfoEM.BHJ.getType()).equals(gdglinfo.getZjzt())) {
            gdglinfo.setZjry(SecurityUtils.getUserId());
        } else if (Long.valueOf(GdglinfoEM.XYGHJ.getType()).equals(gdglinfo.getZjzt())) {
            if (dt > 0) {
                gdglinfo.setRzzjCszt("1");
                gdglinfo.setRzzjCssj(String.valueOf(dt));
            }
            //去重
            StringBuilder str = new StringBuilder(gdglinfo.getProcessDeposit());
            str.append(",4");
            gdglinfo.setProcessDeposit(sub1(String.valueOf(str)));
            if (GdglinfoEM.ISENABLE.getType().equals(gdflowconfig.getJgczSfqy())) {
                //下一流程节点
                StringBuilder process = new StringBuilder(info.getProcessInfo());
                process.append(",5");
                gdglinfo.setProcessInfo(sub1(String.valueOf(process)));
                if (StringUtil.isNull(resultdispList) || resultdispList.size() == 0) {
                    throw new ToflyDeniedException("请选择结果处置人员信息");
                }
                gdglinfo.setLcjd(Long.valueOf(GdglinfoEM.JGCZ.getType()));
//                tzry = gdglinfo.getZjczry();
//                routeip = CZ_URL;
//                routeipapp = CZ_URLAPP;
//                topicName = CommonConstants.JGCZ;
                if (gdflowconfig.getJgczCzsx() != null) {
                    gdglinfo.setCzsx(DateTimeUtil.dateTimeDifference(gdflowconfig.getJgczCzsx(), Calendar.HOUR_OF_DAY));
                    endDate = gdglinfo.getCzsx();
                }
                //上一流程选择的多人处置的情况
                Long maxId = resultdispService.getMaxId();
                String jgczPerson = "";
                Date time = new Date();
                for (Resultdisp resultdisp : resultdispList) {
                    resultdisp.setId(maxId++);
                    resultdisp.setGdbh(info.getGdbh());
                    resultdisp.setImportLcjd(42L);
                    resultdisp.setLcjdName(CommonConstants.RZZJ);
                    resultdisp.setIsFinish("0");
                    resultdisp.setImportDate(time);
                    if ("1".equals(resultdisp.getIsCollect())) {
                        //设置汇集人是认证质检的处理人员
                        gdglinfo.setZjczry(resultdisp.getPersonId());
                        gdglinfo.setZjbm(resultdisp.getDepartId());
                    } else {
                        resultdisp.setIsCollect("0");
                    }
                    //给处置人员发送消息
                    gdglinfoMassage(gdglinfo, "6", CommonConstants.JGCZ, resultdisp.getPersonId(), gdglinfo.getDjsj(), CZ_URL, endDate, CZ_URLAPP);
                    jgczPerson = jgczPerson + resultdisp.getPersonId() + ",";
                }
                gdglinfo.setJgczPerson(jgczPerson);
                //插入之前需要删除该工单可能已有配置了结果处置的人员信息
                resultdispService.remove(Wrappers.<Resultdisp>lambdaQuery().eq(Resultdisp::getGdbh, info.getGdbh()));
                resultdispService.insertBatch(resultdispList);
            } else if (GdglinfoEM.NOTENABLE.getType().equals(gdflowconfig.getJgczSfqy())
                    && GdglinfoEM.ISENABLE.getType().equals(gdflowconfig.getJgshSfqy())) {
                //下一流程节点
                StringBuilder process = new StringBuilder(info.getProcessInfo());
                process.append(",6");
                gdglinfo.setProcessInfo(sub1(String.valueOf(process)));
                //工单登记添加审批链
                if (StringUtil.isNotNull(audit)) {
                    audit.setAuditState("0");
                    audit.setAuditPlanId(info.getId());
                    audit.setAuditType(AuditEnum.GD_TYPE.getCode());
                    Integer shrdj = info.getShrdj();

                    //比较审核人
                    if (StringUtil.isNotNull(shrdj)) {
                        Integer shjb = Integer.parseInt(gdflowconfig.getJgshCcjb());
                        if (shrdj < shjb) {
                            gdglinfo.setShrdj(shrdj + 1);
                            audit.setAuditLevel(shrdj + 1);
                        } else {
                            throw new ToflyDeniedException("添加审批人信息失败：已经达到最高审核级别");
                        }
                    } else {
                        gdglinfo.setShrdj(1);
                        audit.setAuditLevel(1);
                    }

                    gdglinfo.setJgczry(audit.getAuditUser());
                    List<Audit> auditList = new ArrayList<>();
                    auditList.add(audit);
                    boolean flag = saveAuditChain(auditList);
                    if (!flag) {
                        throw new ToflyDeniedException("添加审批人信息失败");
                    }
                } else {
                    throw new ToflyDeniedException("请添加审批人信息");
                }


                gdglinfo.setLcjd(Long.valueOf(GdglinfoEM.JGSH.getType()));
                tzry = gdglinfo.getJgczry();
                routeip = JGSH_URL;
                routeipapp = JGSH_URLAPP;
                topicName = CommonConstants.JGSH;
                if (gdflowconfig.getJgshShsx() != null) {
                    gdglinfo.setShsx(DateTimeUtil.dateTimeDifference(gdflowconfig.getJgshShsx(), Calendar.HOUR_OF_DAY));
                    endDate = gdglinfo.getShsx();
                }
            } else if (!StringUtils.isEmpty(gdflowconfig.getAllLcjd()) && gdflowconfig.getAllLcjd().replace(",7", "").endsWith("4")) {
                if (gdflowconfig.getTransferOutType() != null && Long.valueOf(GdglinfoEM.QWX.getType()).equals(gdflowconfig.getTransferOutType())) {
                    //工单标记挂起
                    gdglinfo.setHangUp("1");
                    if (callSwitchToInterface(extend, info, gdflowconfig)) {
                        return ResultRespone.failed(false, "维修工单创建异常，工单保存失败！");
                    }
                } else {
                    gdglinfo.setLcjd(Long.valueOf(GdglinfoEM.GDGD.getType()));
                    gdglinfo.setFinishTime(new Date());
                    gdglinfo.setProcessDeposit(sub1(gdglinfo.getProcessDeposit().concat(",7")));
                    //下一流程节点
                    StringBuilder process = new StringBuilder(info.getProcessInfo());
                    process.append(",7");
                    gdglinfo.setProcessInfo(sub1(String.valueOf(process)));
                }
            }
            gdglinfo.setZjry(SecurityUtils.getUserId());
            gdglinfo.setZjsj(new Date());
        } else if (Long.valueOf(GdglinfoEM.BH.getType()).equals(gdglinfo.getZjzt())) {
            if (!StringUtils.isEmpty(gdglinfo.getProcessDeposit()) && gdglinfo.getProcessDeposit().contains("4")) {
                gdglinfo.setProcessDeposit(sub2(gdglinfo.getProcessDeposit()));
            }
            if (!StringUtils.isEmpty(gdglinfo.getProcessDeposit()) && gdglinfo.getProcessDeposit().length() > 2) {
                gdglinfo.setProcessDeposit(sub2(gdglinfo.getProcessDeposit()));
            }
            //驳回设置上一流程的节点过程
            gdglinfo.setProcessInfo(sub2(info.getProcessInfo()));
            gdglinfo.setBhzt("1");
            Gdglflow gdglflow = new Gdglflow();
            gdglflow.setGdbh(gdglinfo.getGdbh());
            gdglflow.setClry(SecurityUtils.getUser().getRealName());
            gdglflow.setClsj(gdglinfo.getZjsj());
            gdglflow.setClyj(gdglinfo.getBhyy());
            gdglflow.setLcjd(codeClient.getname(Long.valueOf(GdglinfoEM.GDZJ.getType())));
            gdglflow.setBbhLcjd(codeClient.getname(gdglinfo.getLcjd()));
            //新增被驳回信息
            if (!StringUtils.isEmpty(gdglinfo.getProcessDeposit()) && gdglinfo.getProcessDeposit().contains("3")) {
                gdglflow.setBbhYj(info.getShyj());
                gdglflow.setBbhClsj(info.getShsj());
            } else if (!StringUtils.isEmpty(gdglinfo.getProcessDeposit()) && gdglinfo.getProcessDeposit().contains("2")) {
                gdglflow.setBbhYj(info.getRzyj());
                gdglflow.setBbhClsj(info.getRzsj());
                gdglflow.setBbhFileid(info.getRzFileid());
            } else {
                gdglflow.setBbhYj(info.getGdms());
                gdglflow.setBbhClsj(info.getJdsx());
            }
            Long bhtzry = null;
            String bhrouteip = null;
            String bhrouteipapp = null;
            String bhTopciName = null;
            if (GdglinfoEM.ISENABLE.getType().equals(gdflowconfig.getRzshSfqy())) {
                bhtzry = gdglinfo.getRzslry();
                bhrouteip = RZSH_URL;
                bhrouteipapp = RZSH_URLAPP;
                bhTopciName = CommonConstants.RZSH;
                gdglinfo.setLcjd(Long.valueOf(GdglinfoEM.GDSH.getType()));
            } else if (GdglinfoEM.NOTENABLE.getType().equals(gdflowconfig.getRzshSfqy()) && GdglinfoEM.ISENABLE.getType().equals(gdflowconfig.getRzczSfqy())) {
                gdglinfo.setLcjd(Long.valueOf(GdglinfoEM.RZCZ.getType()));
                bhtzry = Long.valueOf(gdglinfo.getSlry());
                bhrouteip = RZ_URL;
                bhrouteipapp = RZ_URLAPP;
                bhTopciName = CommonConstants.RZCL;
            } else {
                gdglinfo.setProcessDeposit(null);
                gdglinfo.setJdzt("0");
                gdglinfo.setLcjd(Long.valueOf(GdglinfoEM.GDDJ.getType()));
                bhtzry = gdglinfo.getDjry();
                bhrouteip = GD_URL;
                bhrouteipapp = GD_URLAPP;
                bhTopciName = CommonConstants.GDDJ;
                baseMapper.update(null, new UpdateWrapper<Gdglinfo>().setSql("JDSX = NULL,PROCESS_DEPOSIT = NULL ").lambda().eq(Gdglinfo::getId, gdglinfo.getId()));
            }
            gdglflowService.save(gdglflow);
            //驳回消息添加
            //gdglBHMessage(gdglinfo, "6", "工单质检驳回", bhtzry,bhrouteip);
            gdglinfoMassage(gdglinfo, "6", bhTopciName, bhtzry, null, bhrouteip, null, bhrouteipapp);
        } else if (Long.valueOf(GdglinfoEM.ZP.getType()).equals(gdglinfo.getZjzt())) {
            gdglinfo.setZpzt("1");
            Redeploy redeploy = new Redeploy();
            redeploy.setClbm(SecurityUtils.getUser().getDepartmentId());
            redeploy.setZpry(SecurityUtils.getUser().getRealName());
            redeploy.setLcjd(codeClient.getname(gdglinfo.getLcjd()));
            redeploy.setGdbh(gdglinfo.getGdbh());
            redeploy.setZpyj(gdglinfo.getZpyj());
            redeploy.setJsry(gdglinfo.getShslry());
            redeployService.save(redeploy);
            tzry = gdglinfo.getShslry();
            routeip = ZJ_URL;
            routeipapp = ZJ_URLAPP;
            topicName = CommonConstants.RZZJ;
        }
        //添加消息
        if (tzry != null) {
            gdglinfoMassage(gdglinfo, "6", topicName, tzry, gdglinfo.getZjsj(), routeip, endDate, routeipapp);
        }
        gdglinfo.setBhyy(null);
        gdglinfo.setZpyj(null);
        removeDB(gdglinfo.getId(), CommonConstants.RZZJ);
        boolean update = gdglinfoService.updateById(gdglinfo);
        callbackForeign(gdglinfo, info);
        return ResultRespone.success(update);
    }

    @Override
    public ResultRespone actionResults(List<MultipartFile> fileList, GdglinfoExtendDto extend) {
        //审批链
        Audit audit = extend.getAudit();
        Gdglinfo gdglinfo = new Gdglinfo();
        BeanUtils.copyProperties(extend, gdglinfo);
        //获取工单信息
        Gdglinfo info = gdglinfoService.getById(gdglinfo.getId());
        if ("0".equals(info.getJdzt())) {
            gdglinfo.setJdzt("1");
        }
        if (info == null || info.getLcjd().equals(Long.valueOf(GdglinfoEM.JGCZ.getType()))) {
            ResultRespone.failed("工单不存在或工单流程节点不是结果处置");
        }
        //获取配置状态
        Gdflowconfig gdflowconfig = gdflowconfigService.getById(info.getLcid());
        //超时
        double dt = dateBetweenHour(new Date(), info.getCzsx());
        if (dt > 0) {
            gdglinfo.setJgczCszt("1");
            gdglinfo.setJgczCssj(String.valueOf(dt));
        }
        Long tzry = null;
        String routeip = null;
        String routeipapp = null;
        Date endDate = null;
        String topicName = null;
        //获取结果处置的处置人信息；只有汇集人才可以进行工单流程控制(驳回、下一环节、本环节操作)
        Resultdisp resultdisp = resultdispService.getOne(Wrappers.<Resultdisp>lambdaQuery()
                .eq(Resultdisp::getGdbh, info.getGdbh()).eq(Resultdisp::getPersonId, SecurityUtils.getUserId()));
        if (StringUtil.isNull(resultdisp)) {
            return ResultRespone.failed(false, "你不是该工单的处置人员");
        }
        //不是汇集人的情况，只是修改当前处置人员的处置信息
        if ("0".equals(resultdisp.getIsCollect())) {
            return ResultRespone.success(resultdispService.update(Wrappers.<Resultdisp>lambdaUpdate().eq(Resultdisp::getId, resultdisp.getId())
                    .set(Resultdisp::getIsFinish, "1").set(StringUtil.isNotEmpty(extend.getCzyj()), Resultdisp::getCzyj, extend.getCzyj())
                    .set(Resultdisp::getCzsj, Date8Util.getCurrentDate())));
        } else {
            //如果是汇集人，那么需要判断是否还有存在没有处置的人员信息，如果有，则汇集人不能走流程控制
            int count = resultdispService.count(Wrappers.<Resultdisp>lambdaQuery()
                    .eq(Resultdisp::getGdbh, info.getGdbh()).eq(Resultdisp::getIsFinish, "0")
                    .ne(Resultdisp::getPersonId, SecurityUtils.getUserId()));
            if (count > 0) {
                //只有是本环节，才可以进行处置数据保存的，其他操作(下一环节、转派)是不能进行的
                if (!Long.valueOf(GdglinfoEM.BHJ.getType()).equals(gdglinfo.getCzzt())) {
                    throw new ToflyDeniedException("还有其他处置人员没有处置该工单，不能进入其他流程控制");
                }
            }
            resultdispService.update(Wrappers.<Resultdisp>lambdaUpdate().eq(Resultdisp::getId, resultdisp.getId())
                    .set(!Long.valueOf(GdglinfoEM.BHJ.getType()).equals(gdglinfo.getCzzt()), Resultdisp::getIsFinish, "1")
                    .set(StringUtil.isNotEmpty(extend.getCzyj()), Resultdisp::getCzyj, extend.getCzyj())
                    .set(Resultdisp::getCzsj, Date8Util.getCurrentDate())
                    //如果是由转派的情况，则还需要取消汇集人这一选项
                    .set(Long.valueOf(GdglinfoEM.ZP.getType()).equals(gdglinfo.getCzzt()), Resultdisp::getIsCollect, "0")
                    .set(Long.valueOf(GdglinfoEM.ZP.getType()).equals(gdglinfo.getCzzt()), Resultdisp::getIsDeploy, "1"));
        }
        //本环节
        if (Long.valueOf(GdglinfoEM.BHJ.getType()).equals(gdglinfo.getCzzt())) {
            jgczFileUploadAmend(fileList, gdglinfo);
            gdglinfo.setCzry(SecurityUtils.getUserId());
        }
        //下一环节
        else if (Long.valueOf(GdglinfoEM.XYGHJ.getType()).equals(gdglinfo.getCzzt())) {
            jgczFileUploadAmend(fileList, gdglinfo);
            gdglinfo.setCzry(SecurityUtils.getUserId());
            gdglinfo.setCzsj(new Date());
            //去重
            String deposit = sub1(gdglinfo.getProcessDeposit());
            StringBuilder str = new StringBuilder(deposit);
            str.append(",5");
            gdglinfo.setProcessDeposit(sub1(String.valueOf(str)));
            if (GdglinfoEM.ISENABLE.getType().equals(gdflowconfig.getJgshSfqy())) {
                //下一流程节点
                StringBuilder process = new StringBuilder(info.getProcessInfo());
                process.append(",6");
                gdglinfo.setProcessInfo(sub1(String.valueOf(process)));
                //工单登记添加审批链
                if (StringUtil.isNotNull(audit)) {
                    audit.setAuditState("0");
                    audit.setAuditPlanId(info.getId());
                    audit.setAuditType(AuditEnum.GD_TYPE.getCode());
                    Integer shrdj = info.getShrdj();
                    //比较审核人
                    if (StringUtil.isNotNull(shrdj)) {
                        Integer shjb = Integer.parseInt(gdflowconfig.getJgshCcjb());
                        if (shrdj < shjb) {
                            gdglinfo.setShrdj(shrdj + 1);
                            audit.setAuditLevel(shrdj + 1);
                        } else {
                            throw new ToflyDeniedException("添加审批人信息失败：已经达到最高审核级别");
                        }
                    } else {
                        gdglinfo.setShrdj(1);
                        audit.setAuditLevel(1);
                    }
                    gdglinfo.setJgczry(audit.getAuditUser());
                    List<Audit> auditList = new ArrayList<>();
                    auditList.add(audit);
                    boolean flag = saveAuditChain(auditList);
                    if (!flag) {
                        throw new ToflyDeniedException("添加审批人信息失败");
                    }
                } else {
                    throw new ToflyDeniedException("请添加审批人信息");
                }

                gdglinfo.setLcjd(Long.valueOf(GdglinfoEM.JGSH.getType()));
                tzry = gdglinfo.getJgczry();
                routeip = JGSH_URL;
                routeipapp = JGSH_URLAPP;
                topicName = CommonConstants.JGSH;
                if (gdflowconfig.getJgshShsx() != null) {
                    gdglinfo.setShsx(DateTimeUtil.dateTimeDifference(gdflowconfig.getJgshShsx(), Calendar.HOUR_OF_DAY));
                    endDate = gdglinfo.getShsx();
                }
            } else if (!StringUtils.isEmpty(gdflowconfig.getAllLcjd()) && gdflowconfig.getAllLcjd().replace(",7", "").endsWith("5")) {
                if (gdflowconfig.getTransferOutType() != null && Long.valueOf(GdglinfoEM.QWX.getType()).equals(gdflowconfig.getTransferOutType())) {
                    //工单标记挂起
                    gdglinfo.setHangUp("1");
                    if (callSwitchToInterface(extend, info, gdflowconfig)) {
                        return ResultRespone.failed(false, "维修工单创建异常，工单保存失败！");
                    }
                } else {
                    //下一流程节点
                    StringBuilder process = new StringBuilder(info.getProcessInfo());
                    process.append(",7");
                    gdglinfo.setProcessInfo(sub1(String.valueOf(process)));
                    gdglinfo.setLcjd(Long.valueOf(GdglinfoEM.GDGD.getType()));
                    gdglinfo.setFinishTime(new Date());
                    gdglinfo.setProcessDeposit(sub1(gdglinfo.getProcessDeposit().concat(",7")));
                }
            }
        }
        //转派
        else if (Long.valueOf(GdglinfoEM.ZP.getType()).equals(gdglinfo.getCzzt())) {
            gdglinfo.setZpzt("1");
            Redeploy redeploy = new Redeploy();
            redeploy.setZpry(SecurityUtils.getUser().getRealName());
            redeploy.setLcjd(codeClient.getname(gdglinfo.getLcjd()));
            redeploy.setGdbh(gdglinfo.getGdbh());
            redeploy.setZpyj(gdglinfo.getZpyj());
            redeploy.setJsry(gdglinfo.getZjczry());
            redeployService.save(redeploy);
            tzry = gdglinfo.getZjczry();
            routeip = CZ_URL;
            routeipapp = CZ_URLAPP;
            topicName = CommonConstants.JGCZ;
            //转派需要改变人员
            int count = resultdispService.count(Wrappers.<Resultdisp>lambdaQuery()
                    .eq(Resultdisp::getGdbh, info.getGdbh()).eq(Resultdisp::getPersonId, tzry));
            if (count > 0) {
                throw new ToflyDeniedException("该转派人员与结果处置人员重复");
            }
            Date time = new Date();
            Resultdisp resultdispZp = new Resultdisp();
            resultdispZp.setGdbh(info.getGdbh());
            resultdispZp.setImportLcjd(43L);
            resultdispZp.setLcjdName(CommonConstants.JGCZ);
            resultdispZp.setIsFinish("0");
            resultdispZp.setImportDate(time);
            resultdispZp.setPersonId(tzry);
            resultdispZp.setIsCollect("1");
            resultdispZp.setDepartId(resultdisp.getDepartId());
            resultdispZp.setDepartName(resultdisp.getDepartName());
            resultdispZp.setPersonName(toflyCodeCommonMapper.getUserName(tzry));
            resultdispService.save(resultdispZp);
            gdglinfo.setJgczPerson(info.getJgczPerson() + tzry + ",");
        }
        //添加消息
        if (tzry != null) {
            gdglinfoMassage(gdglinfo, "6", topicName, tzry, gdglinfo.getCzsj(), routeip, endDate, routeipapp);
        }
        gdglinfo.setBhyy(null);
        gdglinfo.setZpyj(null);
        removeDB(gdglinfo.getId(), CommonConstants.JGCZ);
        boolean update = gdglinfoService.updateById(gdglinfo);
        callbackForeign(gdglinfo, info);

        return ResultRespone.success(update);
    }

    /**
     * 调用抢维修接口
     *
     * @param extend
     * @param gdglinfo
     * @param gdflowconfig
     * @return
     */
    private boolean callSwitchToInterface(GdglinfoExtendDto extend, Gdglinfo gdglinfo, Gdflowconfig gdflowconfig) {

        //转入抢维修，调用抢维修接口
        String number = getQWX(extend, gdglinfo);
        if (!StringUtils.isEmpty(number)) {
            GdglCirculation gdglCirculation = GdglCirculation.builder()
                    .gdbh(gdglinfo.getGdbh())
                    .otherBh(number)
                    .createTime(new Date())
                    .type(gdflowconfig.getTransferOutType())
                    .build();
            gdglCirculationService.save(gdglCirculation);
        } else {
            return true;
        }
        return false;
    }

    @Override
    public ResultRespone orderReturnVisit(Gdglinfo gdglinfo) {

        return null;
    }

    @Override
    public List<File> getFileInformation(String ids) {
        List<File> files;
        if (ids == null) {
            files = new ArrayList<>();
            return files;
        } else {
            String[] idss = ids.split(",");
            List<Long> list = new ArrayList();
            for (String id : idss) {
                list.add(Long.valueOf(id));
            }
            files = fileService.listByIds(list);
            return files;
        }
    }

    @Override
    public GdglinfoFileInformationVO getAllInformation(Long id) {
        GdglinfoFileInformationVO g = new GdglinfoFileInformationVO();
        Gdglinfo gdglinfo = gdglinfoService.getById(id);
        List<File> files = gdglinfoService.getFileInformation(gdglinfo.getRzFileid());
        g.setFiles(files);
        g.setGdglinfo(gdglinfo);
        return g;
    }

    @Override
    public Page<Gdglinfo> getListWater(Page page, Long id, Long type, String status, Date stTime, Date enTime) {
        Map<String, Long> map = new HashMap<>();
        map.put("gdlx", id);
        map.put("lcjd", Long.valueOf(GdglinfoEM.GDGD.getType()));
        if (type == null){
            map.put("tabtype", Long.valueOf(GdglinfoEM.SBCQ.getType()));
        } else{
            map.put("tabtype", type);
        }

        List<Gdglinfo> list = baseMapper.loadTabTypeInfo(page, map, status, stTime, enTime);
        if (!CollectionUtils.isEmpty(list)) {
            List<Long> ids = list.stream().map(Gdglinfo::getId).collect(Collectors.toList());
            return page.setRecords(gdglinfoService.list(Wrappers.<Gdglinfo>lambdaQuery()
                    .in(Gdglinfo::getId, ids)
                    .orderByAsc(Gdglinfo::getIsWatermeterStatus, Gdglinfo::getDjsj)));
        }
        return null;
    }

    @Override
    public Page<Gdglinfo> orderMonitoringDetails(Page page, String state, Date stTime, Date enTime) {

        return this.page(page, new QueryWrapper<Gdglinfo>().lambda().eq("1".equals(state), Gdglinfo::getLcjd, Long.valueOf(GdglinfoEM.GDGD.getType()))
                .ne("0".equals(state), Gdglinfo::getLcjd, Long.valueOf(GdglinfoEM.GDGD.getType()))
                .between(stTime != null && enTime != null, Gdglinfo::getDjsj, stTime, enTime)
                .orderByDesc(Gdglinfo::getDjsj));
    }

    @Override
    public ResultRespone reminder(Gdglinfo gdglinfo) {

        List<Long> tzrys = Arrays.stream(gdglinfo.getSlry().split(Constant.CSV)).map(s -> Long.parseLong(s.trim())).distinct().collect(Collectors.toList());
        tzrys.forEach(i->{
            //存入消息
            gdglBHMessage(gdglinfo, "6", gdglinfo.getGdbh() + "超时",i, GD_URL, GD_URLAPP);
        });

        return ResultRespone.success();
    }

    @Override
    public Map monthCount() {
        return baseMapper.monthCount();
    }

    @Override
    public OrderStatisticalVO statistical() {
        OrderStatisticalVO vo = new OrderStatisticalVO();
        QueryWrapper<Gdglinfo> wrapper = new QueryWrapper<>();
        wrapper.eq("ORDER_STATUS", 1);
        wrapper.ne("LCJD", 45);
        List<Gdglinfo> pend = baseMapper.selectList(wrapper);
        vo.setPending(pend.size());
        QueryWrapper<Gdglinfo> wra = new QueryWrapper<>();
        wra.eq("ORDER_STATUS", 1);
        wra.eq("LCJD", 45);
        List<Gdglinfo> over = baseMapper.selectList(wra);
        vo.setComplete(over.size());
        //统计当前月份的数据条数
        String deta = getTimeAndDate();
        vo.setMonthComplete(baseMapper.count(deta));
        return vo;
    }

    /**
     * 计算时间相差小时数
     *
     * @param date1 当前系统时间
     * @param date2 时限时间
     * @return
     */
    private double dateBetweenHour(Date date1, Date date2) {
        return (double) (date1.getTime() - date2.getTime()) / (double) (1000 * 60 * 60);
    }


    @Override
    public ClassificationStatisticsVO classificationStatistics() {
        ClassificationStatisticsVO statisticsVO = new ClassificationStatisticsVO();
        Long userId = SecurityUtils.getUserId();
        List<Gdglinfo> gddj = gdglinfoService.list(new QueryWrapper<Gdglinfo>().lambda().eq(Gdglinfo::getLcjd, 39L).eq(Gdglinfo::getDjry, userId).ne(Gdglinfo::getHangUp, 1));
        List<Gdglinfo> recz = gdglinfoService.list(new QueryWrapper<Gdglinfo>().lambda().eq(Gdglinfo::getLcjd, 40L).like(Gdglinfo::getSlry, userId).ne(Gdglinfo::getHangUp, 1));
        List<Gdglinfo> gdsh = gdglinfoService.list(new QueryWrapper<Gdglinfo>().lambda().eq(Gdglinfo::getLcjd, 41L).eq(Gdglinfo::getRzslry, userId).ne(Gdglinfo::getHangUp, 1));
        List<Gdglinfo> gdzj = gdglinfoService.list(new QueryWrapper<Gdglinfo>().lambda().eq(Gdglinfo::getLcjd, 42L).eq(Gdglinfo::getShslry, userId).ne(Gdglinfo::getHangUp, 1));
        List<Gdglinfo> jgcz = gdglinfoService.list(new QueryWrapper<Gdglinfo>().lambda().eq(Gdglinfo::getLcjd, 43L).eq(Gdglinfo::getZjczry, userId).ne(Gdglinfo::getHangUp, 1));
        // 由于结果审核是多审核人
        // 查询审核表符合条件的数据id列表
        // 1.工单类型 11 2.当前对象 3.待审核状态
        Audit audit = new Audit();
        audit.setAuditType(AuditEnum.GD_TYPE.getCode());
        audit.setAuditUser(userId);
        audit.setAuditState(AuditEnum.AUDIT_UNCOMMITTED.getCode());
        List<Audit> result = auditClient.getAuditInfo(audit).getResult();
        Set<Long> collect = new HashSet<>();
        if (null != result && result.size() > 0) {
            collect = result.stream().map(Audit::getAuditPlanId).collect(Collectors.toSet());
        }
        // 未新增审批链的数据,也满足条件
//        Set<Long> collect1 = gdglinfoService.list(new QueryWrapper<Gdglinfo>().lambda().eq(Gdglinfo::getJgczry, userId).ne(Gdglinfo::getHangUp, 1).eq(Gdglinfo::getLcjd, RejectedNodeEnum.JGSH.getCode())).stream().map(Gdglinfo::getId).collect(Collectors.toSet());
//        collect.addAll(collect1);
        statisticsVO.setGddj(gddj.size());
        statisticsVO.setRzcz(recz.size());
        statisticsVO.setGdsh(gdsh.size());
        statisticsVO.setGdzj(gdzj.size());
        statisticsVO.setJgcz(jgcz.size());
        statisticsVO.setGdhf(collect.size());
        return statisticsVO;
    }

    @Override
    public void timeoutAnalysis() {
        //接单超时提醒的逻辑
        List<Gdglinfo> gdglinfos = gdglinfoService.list(new QueryWrapper<Gdglinfo>().lambda().eq(Gdglinfo::getJdzt, "0").eq(Gdglinfo::getLcjd, Long.valueOf(GdglinfoEM.GDDJ.getType())));
        if (!CollectionUtil.isEmpty(gdglinfos)) {
            for (Gdglinfo g : gdglinfos) {
                //最终时限
                Date endDate = g.getJdsx();
                //目前是提前十分钟，如果后面需要自定义，需要将变量提出来处理
                Date overDate = new Date(endDate.getTime() - 10 * 60 * 1000);
                if (overDate.before(new Date())) {
                    List<Long> tzrys = Arrays.stream(g.getSlry().split(Constant.CSV)).map(s -> Long.parseLong(s.trim())).distinct().collect(Collectors.toList());
                    tzrys.forEach(i->{
                        //添加消息
                        gdglinfoMassage(g, "8", "工单接单即将超时",i, g.getRzsj(), GD_URL, endDate, GD_URLAPP);
                    });

                }
            }
        }
    }

    @Override
    public void rzczTimeout() {
        //认证处置超时提醒的逻辑
        List<Gdglinfo> gdglinfos = gdglinfoService.list(new QueryWrapper<Gdglinfo>().lambda().isNull(Gdglinfo::getRzsj).isNotNull(Gdglinfo::getRzsx)
                .eq(Gdglinfo::getLcjd, Long.valueOf(GdglinfoEM.RZCZ.getType())));
        if (!CollectionUtil.isEmpty(gdglinfos)) {
            for (Gdglinfo g : gdglinfos) {
                //最终时限
                Date endDate = g.getRzsx();
                //目前是提前十分钟，如果后面需要自定义，需要将变量提出来处理
                Date overDate = new Date(endDate.getTime() - 10 * 60 * 1000);
                if (overDate.before(new Date()) && overDate.before(endDate)) {
                    List<Long> tzrys = Arrays.stream(g.getSlry().split(Constant.CSV)).map(s -> Long.parseLong(s.trim())).distinct().collect(Collectors.toList());
                    tzrys.forEach(i->{
                        //添加消息
                        gdglinfoMassage(g, "8", "认证处置即将超时", i, g.getRzsj(), RZ_URL, endDate, RZ_URLAPP);
                    });

                }
            }
        }
    }

    @Override
    public void rzshTimeout() {
        //认证审核超时提醒的逻辑
        List<Gdglinfo> gdglinfos = gdglinfoService.list(new QueryWrapper<Gdglinfo>().lambda().isNull(Gdglinfo::getShsj).isNotNull(Gdglinfo::getShsx)
                .eq(Gdglinfo::getLcjd, Long.valueOf(GdglinfoEM.GDSH.getType())));
        if (!CollectionUtil.isEmpty(gdglinfos)) {
            for (Gdglinfo g : gdglinfos) {
                //最终时限
                Date endDate = g.getShsx();
                //目前是提前十分钟，如果后面需要自定义，需要将变量提出来处理
                Date overDate = new Date(endDate.getTime() - 10 * 60 * 1000);
                if (overDate.before(new Date()) && overDate.before(endDate)) {
                    //添加消息
                    gdglBHMessage(g, "8", "认证审核即将超时", g.getRzry(), RZSH_URL, RZSH_URLAPP);
                    //代办事项任务
                    Usertask usertask = new Usertask();
                    usertask.setTlevel(String.valueOf(g.getJjcd()));
                    usertask.setTkty("8");
                    usertask.setTknm(g.getGdms());
                    usertask.setCreateUser(SecurityUtils.getUserId());
                    userTaskClient.save(usertask);
                }
            }
        }
    }

    @Override
    public void rzzjTimeout() {
        //认证质检超时提醒的逻辑
        List<Gdglinfo> gdglinfos = gdglinfoService.list(new QueryWrapper<Gdglinfo>().lambda().isNull(Gdglinfo::getZjsj).isNotNull(Gdglinfo::getZjsx)
                .eq(Gdglinfo::getLcjd, Long.valueOf(GdglinfoEM.GDZJ.getType())));
        if (!CollectionUtil.isEmpty(gdglinfos)) {
            for (Gdglinfo g : gdglinfos) {
                //最终时限
                Date endDate = g.getZjsx();
                //目前是提前十分钟，如果后面需要自定义，需要将变量提出来处理
                Date overDate = new Date(endDate.getTime() - 10 * 60 * 1000);
                if (overDate.before(new Date()) && overDate.before(endDate)) {
                    //添加消息
                    gdglBHMessage(g, "8", "认证质检即将超时", g.getShslry(), ZJ_URL, ZJ_URLAPP);
                    //代办事项任务
                    Usertask usertask = new Usertask();
                    usertask.setTlevel(String.valueOf(g.getJjcd()));
                    usertask.setTkty("8");
                    usertask.setTknm(g.getGdms());
                    usertask.setCreateUser(SecurityUtils.getUserId());
                    userTaskClient.save(usertask);
                }
            }
        }
    }

    @Override
    public void jgczTimeout() {
        //结果处置超时提醒的逻辑
        List<Gdglinfo> gdglinfos = gdglinfoService.list(new QueryWrapper<Gdglinfo>().lambda().isNull(Gdglinfo::getCzsj).isNotNull(Gdglinfo::getCzsx)
                .eq(Gdglinfo::getLcjd, Long.valueOf(GdglinfoEM.JGCZ.getType())));
        if (!CollectionUtil.isEmpty(gdglinfos)) {
            for (Gdglinfo g : gdglinfos) {
                //最终时限
                Date endDate = g.getCzsx();
                //目前是提前十分钟，如果后面需要自定义，需要将变量提出来处理
                Date overDate = new Date(endDate.getTime() - 10 * 60 * 1000);
                if (overDate.before(new Date()) && overDate.before(endDate)) {
                    //添加消息
                    gdglBHMessage(g, "8", "结果处置即将超时", g.getZjczry(), CZ_URL, CZ_URLAPP);
                    //代办事项任务
                    Usertask usertask = new Usertask();
                    usertask.setTlevel(String.valueOf(g.getJjcd()));
                    usertask.setTkty("8");
                    usertask.setTknm(g.getGdms());
                    usertask.setCreateUser(SecurityUtils.getUserId());
                    userTaskClient.save(usertask);
                }
            }
        }
    }

    @Override
    public void gdcsTimeout() {
        //结果处置超时提醒的逻辑
//        List<Gdglinfo> gdglinfos = gdglinfoService.list(new QueryWrapper<Gdglinfo>().lambda().isNotNull(Gdglinfo::getGdsx).ne(Gdglinfo::getGdcsFlag , "1"));
//        if (!CollectionUtil.isEmpty(gdglinfos)) {
//            for (Gdglinfo g : gdglinfos) {
//                //最终时限
//                Date endDate = g.getGdsx();
//                //目前是提前十分钟，如果后面需要自定义，需要将变量提出来处理
//                Date overDate = new Date(endDate.getTime() - 10 * 60 * 1000);
//                if (overDate.before(new Date()) && overDate.before(endDate)) {
//                    //添加消息
//                    gdglBHMessage(g, "8", "工单即将超时", "人员"  , "url"  , "APP-URL" );
//                    //代办事项任务
//                    Usertask usertask = new Usertask();
//                    usertask.setTlevel(String.valueOf(g.getJjcd()));
//                    usertask.setTkty("8");
//                    usertask.setTknm(g.getGdms());
//                    usertask.setCreateUser(SecurityUtils.getUserId());
//                    userTaskClient.save(usertask);
//                }
//            }
//        }
    }


    /**
     * 存储文件
     *
     * @param fileList
     * @param fileIdsdb
     * @param fileIds
     * @return
     */
    private StringBuilder saveFiles(List<MultipartFile> fileList, String fileIdsdb, String fileIds) {
        StringBuilder fileIdList = null;
        if (org.apache.commons.collections.CollectionUtils.isNotEmpty(fileList)) {
            fileIdList = saveFileList(fileList, filePathBean.getGdrzcl(), "TF_YWPN_GDINFO_W");
        }

        if (!StringUtils.isEmpty(fileIdsdb)) {
            List<Long> removeFileId = new ArrayList<>();
            if (StringUtils.isEmpty(fileIds)) {
                removeFileId = Arrays.stream(fileIdsdb.split(Constate.CSV)).map(s -> Long.parseLong(s.trim()))
                        .collect(Collectors.toList());
            } else {
                removeFileId = Arrays.stream(fileIdsdb.split(Constate.CSV)).filter(st -> !fileIds.contains(st)).map(st -> Long.parseLong(st.trim())).collect(Collectors.toList());
            }
            // 删除对应文件数据
            if (!removeFileId.isEmpty()) {
                // 删除远程文件
                fileService.removeFileList(removeFileId);
            }
        }
        StringBuilder files = new StringBuilder();

        if (StringUtils.isEmpty(fileIds) || StringUtils.isEmpty(fileIdList)) {
            if (!StringUtils.isEmpty(fileIds)) {
                files.append(fileIds);
            } else if (!StringUtils.isEmpty(fileIdList)) {
                files.append(fileIdList);
            }
        } else {
            files.append(fileIds).append(Constate.CSV).append(fileIdList);
        }
        return files;
    }


    public void fileUploadAmend(List<MultipartFile> fileList, Gdglinfo gdglinfo) {
        if (fileList == null || fileList.isEmpty()) {
            if (gdglinfo != null && StringUtils.isEmpty(gdglinfo.getRzFileid()) && gdglinfo.getId() != null) {
                this.update(new UpdateWrapper<Gdglinfo>().lambda().set(Gdglinfo::getRzFileid, "").eq(Gdglinfo::getId, gdglinfo.getId()));
            }
            return;
        }
        String fileIdsdb = null;
        if (gdglinfo.getId() != null) {
            fileIdsdb = getById(gdglinfo.getId()).getRzFileid();
        }
        String fileIds = gdglinfo.getRzFileid();
        StringBuilder files = saveFiles(fileList, fileIdsdb, fileIds);
        if (gdglinfo.getId() != null && StringUtils.isEmpty(files)) {
            this.update(new UpdateWrapper<Gdglinfo>().lambda().set(Gdglinfo::getRzFileid, "").eq(Gdglinfo::getId, gdglinfo.getId()));
        }
        gdglinfo.setRzFileid(files.toString());
    }


    @Override
    public Page<Gdglinfo> pageTypeSelect(Page page, String gdlx, Long lcjd, Date stTime, Date enTime) {

        return this.page(page, new QueryWrapper<Gdglinfo>().lambda().eq(!StringUtils.isEmpty(gdlx), Gdglinfo::getGdlx, gdlx)
                .eq(lcjd != null, Gdglinfo::getLcjd, lcjd).between(stTime != null && enTime != null, Gdglinfo::getDjsj, stTime, enTime)
                .orderByDesc(Gdglinfo::getDjsj));
    }

    @Override
    public Page<Gdglinfo> fieldPersonnel(Page page, String slbm, String slry, Date stTime, Date enTime) {
        return this.page(page, new QueryWrapper<Gdglinfo>().lambda().eq(!StringUtils.isEmpty(slbm), Gdglinfo::getSlbm, slbm)
                .like(!StringUtils.isEmpty(slry), Gdglinfo::getSlry, slry).between(stTime != null && enTime != null, Gdglinfo::getDjsj, stTime, enTime)
                .orderByDesc(Gdglinfo::getDjsj));
    }

    @Override
    public Page<Map> orderMonitoring(Page page, Map map) {
        return page.setRecords(baseMapper.orderMonitoring(page, map));
    }

    @Override
    public Page<Map> summarizeNumber(Page page, Gdglinfo gdglinfo) {
        return page.setRecords(baseMapper.summarizeNumber(page, gdglinfo));
    }

    @Override
    public Page<Map> orderAnalysis(Page page, Map map) {
        return page.setRecords(baseMapper.orderAnalysis(page, map));
    }

    @Override
    public ResultRespone orderAnalysisDetails(Map map) {
        return ResultRespone.success(baseMapper.orderAnalysisDetails(map));
    }

    @Override
    public Page<Map> orderAnalysisByTimeAndType(Page page, Map map) {
        return page.setRecords(baseMapper.orderAnalysisByTimeAndType(page, map));
    }

    @Override
    public Page<Map> collectionManagementTwo(Page page, Map map) {
        return page.setRecords(baseMapper.collectionManagementTwo(page, map));
    }

    @Override
    public Page<Map> collectionManagementThree(Page page, Map map) {
        return page.setRecords(baseMapper.collectionManagementThree(page, map));
    }


    //获取文件大小的封装类
    public static String getStorageSpaceM(long size) {
        String G = size / 1024 / 1024 / 1024 + "G";
        String M = size / 1024 / 1024 + "M";
        String KB = size / 1024 + "KB";
        if (size / 1024 / 1024 / 1024 >= 1) {
            return G;
        } else if (size / 1024 / 1024 >= 1) {
            return M;
        } else if (size / 1024 >= 1) {
            return KB;
        } else {
            return (size + "Byte");
        }
    }


    /**
     * 文件上传管理
     *
     * @param tableName
     * @return
     */
    public StringBuilder saveFileList(List<MultipartFile> fileList, String filePathBean, String tableName) {
        StringBuilder fileIds = new StringBuilder("");

        //保存照片
        fileList.forEach(file -> {
            //文件名
            String fileName = file.getOriginalFilename();
            if (!"".equals(fileName)) {
                //文件路径
                assert fileName != null;
                String filePath = filePathBean + IdWorker.getIdStr() + fileName.substring(fileName.lastIndexOf(Constate.POINT));
                FtpUtil.uploadFile2Ftp(file, filePath);
                File localFile = new File();
                localFile.setFilePath(filePath);
                localFile.setFileName(fileName);
                localFile.setOtherName(IdWorker.getIdStr() + fileName.substring(fileName.lastIndexOf(Constate.POINT)));
                //关联表名称
                localFile.setTableName(tableName);
                //获取后缀
                String suffix = fileName.substring(fileName.lastIndexOf(Constate.POINT));
                localFile.setFileFormat(suffix);
                localFile.setFileSize(file.getSize() + Constate.KB);
                fileService.save(localFile);
                //获得文件ID
                fileIds.append(localFile.getId()).append(Constate.CSV);
            }
        });

        return fileIds;
    }

    //获取当前日期和时间
    public String getTimeAndDate() {
        SimpleDateFormat td = new SimpleDateFormat("yyyy-MM");
        return td.format(new Date());
    }

    //字符串去重方法
    static String sub1(String str) {
        List list = new ArrayList();
        StringBuffer sb = new StringBuffer(str);
        int j = 0;
        for (int i = 0; i < str.length(); i++) {
            if (list.contains(str.charAt(i)) && ',' != (str.charAt(i))) {
                sb.deleteCharAt(i - j);     //String 是没有delete方法的
                sb.deleteCharAt(i - j - 1);
                j++; //因为删除了sb中的字符，有一个偏移
                j++;
            } else {
                list.add(str.charAt(i));
            }
        }
        return sb.toString();
    }

    static String sub2(String str) {
        if (str.length() > 2) {
            return str.substring(0, str.length() - 2);
        }
        return str;
    }


    public void jgczFileUploadAmend(List<MultipartFile> fileList, Gdglinfo gdglinfo) {
        List<Long> fileIdLongList = new ArrayList<>();
        if (null != fileList && fileList.size() > 0) {
            StringBuilder fileIds = saveFileList(fileList, filePathBean.getJgczcl(), "TF_YWPN_GDINFO_W");
            fileIdLongList = Arrays.stream(fileIds.toString().split(Constate.CSV)).map(s -> Long.parseLong(s.trim()))
                    .collect(Collectors.toList());
        }
        Gdglinfo record = this.getById(gdglinfo.getId());
        String lostFileIds = record.getJgczFileid();
        String fileIds = gdglinfo.getJgczFileid();
        List<Long> removeFileId = new ArrayList<>();
        List<Long> fileIdLongs = new ArrayList<>();
        if (lostFileIds != fileIds) {
            List<Long> lostFileIdLongs = new ArrayList<>();
            if (!StringUtils.isEmpty(lostFileIds)) {
                lostFileIdLongs = Arrays.stream(lostFileIds.split(Constate.CSV)).map(s -> Long.parseLong(s.trim()))
                        .collect(Collectors.toList());
            }

            if (!StringUtils.isEmpty(fileIds)) {
                fileIdLongs = Arrays.stream(fileIds.split(Constate.CSV)).map(s -> Long.parseLong(s.trim()))
                        .collect(Collectors.toList());
            }
            List<Long> finalFileIdLongs = fileIdLongs;
            lostFileIdLongs.forEach(lost -> {
                if (!finalFileIdLongs.contains(lost)) {
                    removeFileId.add(lost);
                }
                if (StringUtils.isEmpty(finalFileIdLongs)) {
                    removeFileId.add(lost);
                }
            });
            // 删除对应文件数据
            if (removeFileId.size() > 0) {
                // 删除远程文件
                fileService.removeFileList(removeFileId);
            }
        }
        // 更新数据信息
        fileIdLongList.addAll(fileIdLongs);
        if (fileIdLongList.size() > 0) {
            StringBuilder stringBuilder = new StringBuilder("");
            fileIdLongList.forEach(info -> {
                stringBuilder.append(info).append(Constate.CSV);
            });
            gdglinfo.setJgczFileid(stringBuilder.deleteCharAt(stringBuilder.length() - 1).toString());
            this.updateById(gdglinfo);
        } else {
            gdglinfo.setJgczFileid("");
            this.update(new UpdateWrapper<Gdglinfo>().lambda().set(Gdglinfo::getJgczFileid, "").eq(Gdglinfo::getId, gdglinfo.getId()));
        }
        this.updateById(gdglinfo);
    }

    @Override
    public void jdTimeout() {
        gdglinfoService.update(new UpdateWrapper<Gdglinfo>().lambda().set(Gdglinfo::getJdCszt, "1")
                .eq(Gdglinfo::getJdzt, '0').ne(Gdglinfo::getLcjd, Long.valueOf(GdglinfoEM.GDGD.getType())).ne(Gdglinfo::getJdCszt, "1").lt(Gdglinfo::getJdsx, new Date()));
    }


    /**
     * 认证处理超时
     */
    @Override
    public void rzcsTimeout() {
        gdglinfoService.update(new UpdateWrapper<Gdglinfo>().lambda().set(Gdglinfo::getRzczCszt, "1")
                .eq(Gdglinfo::getLcjd, Long.valueOf(GdglinfoEM.RZCZ.getType())).ne(Gdglinfo::getRzczCszt, "1").lt(Gdglinfo::getRzsx, new Date()));

    }

    /**
     * 认证审核超时
     */
    @Override
    public void shcsTimeout() {
        gdglinfoService.update(new UpdateWrapper<Gdglinfo>().lambda().set(Gdglinfo::getReshCszt, "1")
                .eq(Gdglinfo::getLcjd, Long.valueOf(GdglinfoEM.GDSH.getType())).ne(Gdglinfo::getReshCszt, "1").lt(Gdglinfo::getShsx, new Date()));
    }

    /**
     * 认证质检超时
     */
    @Override
    public void zjcsTimeout() {
        gdglinfoService.update(new UpdateWrapper<Gdglinfo>().lambda().set(Gdglinfo::getRzzjCszt, "1")
                .eq(Gdglinfo::getLcjd, Long.valueOf(GdglinfoEM.GDZJ.getType())).ne(Gdglinfo::getRzzjCszt, "1").lt(Gdglinfo::getZjsx, new Date()));
    }

    /**
     * 结果处置超时
     */
    @Override
    public void czcsTimeout() {
        gdglinfoService.update(new UpdateWrapper<Gdglinfo>().lambda().set(Gdglinfo::getJgczCszt, "1")
                .eq(Gdglinfo::getLcjd, Long.valueOf(GdglinfoEM.JGCZ.getType())).ne(Gdglinfo::getJgczCszt, "1").lt(Gdglinfo::getCzsx, new Date()));
    }

    @Override
    public void allcsTimeout() {
        gdglinfoService.update(new UpdateWrapper<Gdglinfo>().lambda().set(Gdglinfo::getGdcsFlag, "1")
                .ne(Gdglinfo::getLcjd, Long.valueOf(GdglinfoEM.GDGD.getType()))
                .ne(Gdglinfo::getGdcsFlag, "1").lt(Gdglinfo::getGdsx, new Date()));
    }

    /**
     * 修改接单状态
     *
     * @param id 工单id
     * @return
     */
    @Override
    public boolean updateJdZT(long id) {
        Gdglinfo gdglinfo = baseMapper.selectOne(new QueryWrapper<Gdglinfo>().lambda().eq(Gdglinfo::getId, id).and(wp -> wp.eq(Gdglinfo::getJdzt, '0').or().isNull(Gdglinfo::getJdzt)));
        if (gdglinfo != null && gdglinfo.getGddjZt().equals(Long.valueOf(GdglinfoEM.XYGHJ.getType()) ) && !gdglinfo.getJdzt().equals("1")) {
            Gdglinfo info = new Gdglinfo();
            info.setId(id);
            info.setJdzt("1");
            int row = baseMapper.updateById(info);
            if (row == 1) {
                return true;
            }
        }

        return false;
    }

    @Override
    public Object collectGDComplete(GdglinfoTjDTO gdglinfoTjDTO, String isExport, String isDetails, HttpServletResponse response) {

        if (gdglinfoTjDTO.getEndTime() == null && gdglinfoTjDTO.getStartTime() == null) {
            gdglinfoTjDTO.setEndTime(new Date());
            gdglinfoTjDTO.setStartTime(DateTimeUtil.dateTimeDifference(-1, Calendar.MONTH));
        } else if (gdglinfoTjDTO.getEndTime() == null) {
            gdglinfoTjDTO.setEndTime(DateTimeUtil.dateTimeDifference(gdglinfoTjDTO.getStartTime(), 1, Calendar.MONTH));
        } else if (gdglinfoTjDTO.getStartTime() == null) {
            gdglinfoTjDTO.setStartTime(DateTimeUtil.dateTimeDifference(gdglinfoTjDTO.getEndTime(), -1, Calendar.MONTH));
        }
        if (gdglinfoTjDTO.getType() == null || gdglinfoTjDTO.getType() == 0) {
            GdPercentStaticReturnVO vo = new GdPercentStaticReturnVO();
            List<GdPercentStatic> list;
            // 求和
            GdPercentStaticAll all = new GdPercentStaticAll();
            if ("1".equals(isDetails)) {
                list = baseMapper.collectGDCompleteDetailsInfo(gdglinfoTjDTO);
            } else {
                String isDept = gdglinfoTjDTO.getIsDept();
                if ("1".equals(isDept)) {
                    list = baseMapper.collectDeptGDCompleteInfo(gdglinfoTjDTO);
                } else {
                    list = baseMapper.collectGDCompleteInfo(gdglinfoTjDTO);
                }

            }
            list.forEach(info -> {
                // 是否拼接类型
                if ("1".equals(isDetails)) {
                    String gdlxName = info.getGdlxName();
                    String gdxf1Name = info.getGdxf1Name();
                    String gdxf2Name = info.getGdxf2Name();
                    if (StringUtil.isNotEmpty(gdxf1Name)) {
                        gdlxName = gdlxName + "-" + gdxf1Name;
                        if (StringUtil.isNotEmpty(gdxf2Name)) {
                            gdlxName = gdlxName + "-" + gdxf2Name;
                        }
                    }
                    info.setTypeJoint(gdlxName);
                }
                all.setGddjNumAll(info.getGddjNum() + all.getGddjNumAll());
                all.setRzczNumAll(info.getRzczNum() + all.getRzczNumAll());
                all.setRzczTotalNumAll(info.getRzczTotalNum() + all.getRzczTotalNumAll());
                all.setRzshNumAll(info.getRzshNum() + all.getRzshNumAll());
                all.setRzshTotalNumAll(info.getRzshTotalNum() + all.getRzshTotalNumAll());
                all.setRzzjNumAll(info.getRzzjNum() + all.getRzzjTotalNumAll());
                all.setRzzjTotalNumAll(info.getRzzjTotalNum() + all.getRzzjTotalNumAll());
                all.setJgczNumAll(info.getJgczNum() + all.getJgczNumAll());
                all.setJgczTotalNumAll(info.getJgczTotalNum() + all.getJgczTotalNumAll());
                all.setJgshNumAll(info.getJgshNum() + all.getJgshNumAll());
                all.setJgshTotalNumAll(info.getJgshTotalNum() + all.getJgshTotalNumAll());
                all.setQwxNumAll(info.getQwxNum() + all.getQwxNumAll());
                all.setGdNumAll(info.getGdNum() + all.getGdNumAll());
                all.setGdgdNumAll(info.getGdgdNum() + all.getGdgdNumAll());
                all.setNotGdgdNumAll(info.getNotGdgdNum() + all.getNotGdgdNumAll());
            });
            long gdNumAll = all.getGdNumAll();
            if (0L != gdNumAll) {
                all.setGdOverRateAll(BigDecimal.valueOf(all.getGdgdNumAll())
                        .divide(BigDecimal.valueOf(gdNumAll), 4, BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(100)).setScale(2, BigDecimal.ROUND_HALF_UP) + "%");
            } else {
                all.setGdOverRateAll(BigDecimal.ZERO + "%");
            }
            vo.setStaticList(list);
            vo.setAll(all);
            if ("1".equals(isExport)) {
                //找到枚举中的文件名
                String templateServiceType = "";
                if ("1".equals(isDetails)) {
                    templateServiceType = "exportGdOverDetailsRateService";
                } else {
                    String isDept = gdglinfoTjDTO.getIsDept();
                    if ("1".equals(isDept)) {
                        templateServiceType = "exportDeptGdOverRateService";
                    } else {
                        templateServiceType = "exportGdOverRateService";
                    }

                }
                ExcelExportFileTypeEnum excelExportFileTypeEnum = ExcelExportFileTypeEnum.getExcelExportFileTypeEnum(templateServiceType, "1");
                if (null == excelExportFileTypeEnum) {
                    return null;
                }
                Map<String, Object> dataMap = new HashMap<>();
                dataMap.put("list", list);
                List<GdPercentStaticAll> allList = new ArrayList<>();
                allList.add(all);
                dataMap.put("all", allList);
                ExcelUtil.export(dataMap, excelExportFileTypeEnum, Constant.FILE_PATH_TEST_EXPORT_EXCEL, response);
                return null;
            }
            return vo;
        } else if (gdglinfoTjDTO.getType() == 1) {
            GdAbnormalPercentStaticReturnVO vo1 = new GdAbnormalPercentStaticReturnVO();
            List<GdAbnormalPercentStatic> list;
            // 求和
            GdAbnormalPercentStaticAll all = new GdAbnormalPercentStaticAll();
            if ("1".equals(isDetails)) {
                list = baseMapper.collectGDCompleteErrorDetailsInfo(gdglinfoTjDTO);
            } else {
                String isDept = gdglinfoTjDTO.getIsDept();
                if ("1".equals(isDept)) {
                    list = baseMapper.collectDeptGDCompleteErrorInfo(gdglinfoTjDTO);
                } else {
                    list = baseMapper.collectGDCompleteErrorInfo(gdglinfoTjDTO);
                }

            }
            list.forEach(info -> {
                // 是否拼接类型
                if ("1".equals(isDetails)) {
                    String gdlxName = info.getGdlxName();
                    String gdxf1Name = info.getGdxf1Name();
                    String gdxf2Name = info.getGdxf2Name();
                    if (StringUtil.isNotEmpty(gdxf1Name)) {
                        gdlxName = gdlxName + "-" + gdxf1Name;
                        if (StringUtil.isNotEmpty(gdxf2Name)) {
                            gdlxName = gdlxName + "-" + gdxf2Name;
                        }
                    }
                    info.setTypeJoint(gdlxName);
                }

                all.setGdNumAll(info.getGdNum() + all.getGdNumAll());
                all.setBhNumAll(info.getBhNum() + all.getBhNumAll());
                all.setCsNumAll(info.getCsNum() + all.getCsNumAll());
                all.setZpNumAll(info.getZpNum() + all.getZpNumAll());
                all.setZzNumAll(info.getZzNum() + all.getZzNumAll());
            });
            long gdNumAll = all.getGdNumAll();
            if (0L != gdNumAll) {
                all.setBhRateAll(BigDecimal.valueOf(all.getBhNumAll())
                        .divide(BigDecimal.valueOf(gdNumAll), 4, BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(100)).setScale(2, BigDecimal.ROUND_HALF_UP) + "%");
                all.setCsRateAll(BigDecimal.valueOf(all.getCsNumAll())
                        .divide(BigDecimal.valueOf(gdNumAll), 4, BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(100)).setScale(2, BigDecimal.ROUND_HALF_UP) + "%");
                all.setZpRateAll(BigDecimal.valueOf(all.getZpNumAll())
                        .divide(BigDecimal.valueOf(gdNumAll), 4, BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(100)).setScale(2, BigDecimal.ROUND_HALF_UP) + "%");
                all.setZzRateAll(BigDecimal.valueOf(all.getZzNumAll())
                        .divide(BigDecimal.valueOf(gdNumAll), 4, BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(100)).setScale(2, BigDecimal.ROUND_HALF_UP) + "%");
            } else {
                String rate = BigDecimal.ZERO + "%";
                all.setBhRateAll(rate);
                all.setCsRateAll(rate);
                all.setZpRateAll(rate);
                all.setZzRateAll(rate);
            }
            vo1.setStaticList(list);
            vo1.setAll(all);
            if ("1".equals(isExport)) {
                //找到枚举中的文件名
                String templateServiceType = "";
                if ("1".equals(isDetails)) {
                    templateServiceType = "exportGdAbnormalDetailsRateService";
                } else {
                    String isDept = gdglinfoTjDTO.getIsDept();
                    if ("1".equals(isDept)) {
                        templateServiceType = "exportDeptGdAbnormalRateService";
                    } else {
                        templateServiceType = "exportGdAbnormalRateService";
                    }

                }
                ExcelExportFileTypeEnum excelExportFileTypeEnum = ExcelExportFileTypeEnum.getExcelExportFileTypeEnum(templateServiceType, "1");
                if (null == excelExportFileTypeEnum) {
                    return null;
                }
                Map<String, Object> dataMap = new HashMap<>();
                dataMap.put("list", list);
                List<GdAbnormalPercentStaticAll> allList = new ArrayList<>();
                allList.add(all);
                dataMap.put("all", allList);
                ExcelUtil.export(dataMap, excelExportFileTypeEnum, Constant.FILE_PATH_TEST_EXPORT_EXCEL, response);
                return null;
            }
            return vo1;
        } else if (gdglinfoTjDTO.getType() == 2) {
            return baseMapper.collectRXGDCompleteErrorInfo(gdglinfoTjDTO);
        }
        return null;
    }

    /**
     * 工单汇总数据
     *
     * @param gdglinfoTjDTO
     * @return
     */
    @Override
    public Object collectGdIndex(GdglinfoTjDTO gdglinfoTjDTO) {
        //时间默认当月或一个月
        if (gdglinfoTjDTO.getEndTime() == null && gdglinfoTjDTO.getStartTime() == null) {
            gdglinfoTjDTO.setEndTime(new Date());
            gdglinfoTjDTO.setStartTime(DateTimeUtil.dateTimeDifference(-1, Calendar.MONTH));
        } else if (gdglinfoTjDTO.getEndTime() == null) {
            gdglinfoTjDTO.setEndTime(DateTimeUtil.dateTimeDifference(gdglinfoTjDTO.getStartTime(), 1, Calendar.MONTH));
        } else if (gdglinfoTjDTO.getStartTime() == null) {
            gdglinfoTjDTO.setStartTime(DateTimeUtil.dateTimeDifference(gdglinfoTjDTO.getEndTime(), -1, Calendar.MONTH));
        }
        Long userId = SecurityUtils.getUserId();
        return baseMapper.collectGdIndex(gdglinfoTjDTO, userId);
    }

    @Override
    public IPage<Gdglinfo> collectGdAll(Page page, GdglinfoDTO gdglinfoTjDTO) {
        Long userId = SecurityUtils.getUserId();
        Long lcjd = gdglinfoTjDTO.getLcjdid();
        String lcjdName = gdglinfoTjDTO.getLcjdName();
        if (lcjd.equals(39L)) {
            //工单登记汇总
            return baseMapper.collectGdAllBygddj(page, userId, gdglinfoTjDTO);
        } else if (lcjd.equals(40L)) {
            //认证处置
            return baseMapper.collectGdAllByRzcz(page, userId, gdglinfoTjDTO);
        } else if (lcjd.equals(41L)) {
            //认证审核
            return baseMapper.collectGdAllByRzsh(page, userId, gdglinfoTjDTO);
        } else if (lcjd.equals(42L)) {
            //认证质检
            return baseMapper.collectGdAllByRzzj(page, userId, gdglinfoTjDTO);
        } else if (lcjd.equals(43L)) {
            //结果处置
            return baseMapper.collectGdAllByJgcz(page, userId, gdglinfoTjDTO);
        } else if (lcjd.equals(44L)) {
            //结果审核
            return baseMapper.collectGdAllByJgsh(page, userId, gdglinfoTjDTO);
        } else {
            throw new ToflyDeniedException("请正确操作");
        }

    }

    @Override
    public List<Map> collectGdInfoDetail(GdglinfoDTO gdglinfoDTO) {
        Long gdlx = gdglinfoDTO.getGdlx();
        Long lcjd = gdglinfoDTO.getLcjdid();
        String lcjdName = gdglinfoDTO.getLcjdName();

        if (StringUtil.isNull(lcjd) || StringUtil.isEmpty(lcjdName)) {
            throw new ToflyDeniedException("请传递流程节点");
        }
        if (lcjd.equals(39L)) {
            //工单登记汇总
            return baseMapper.collectGdInfoDetailByGddj(gdglinfoDTO, ratio, SecurityUtils.getUserId());
        } else if (lcjd.equals(40L)) {
            //认证处置
            return baseMapper.collectGdInfoDetailByRzcz(gdglinfoDTO, ratio, SecurityUtils.getUserId());
        } else if (lcjd.equals(41L)) {
            //认证审核
            return baseMapper.collectGdInfoDetailByRzsh(gdglinfoDTO, ratio, SecurityUtils.getUserId());
        } else if (lcjd.equals(42L)) {
            //认证质检
            return baseMapper.collectGdInfoDetailByRzzj(gdglinfoDTO, ratio, SecurityUtils.getUserId());
        } else {
            throw new ToflyDeniedException("请正确操作");
        }

//        return baseMapper.collectGdInfoDetail(gdglinfoDTO, ratio, SecurityUtils.getUserId());
    }

    @Override
    public List<Map> collectInfoByJgcz(GdglinfoDTO gdglinfoDTO) {
        Long gdlx = gdglinfoDTO.getGdlx();
        Long lcjd = gdglinfoDTO.getLcjdid();
        String lcjdName = gdglinfoDTO.getLcjdName();
//        if (StringUtil.isNull(gdlx)) {
//            throw new ToflyDeniedException("请传递工单类型");
//        }
        if (StringUtil.isNull(lcjd) || StringUtil.isEmpty(lcjdName)) {
            throw new ToflyDeniedException("请传递流程节点");
        }
        Long id = SecurityUtils.getUserId();
        return baseMapper.collectInfoByJgcz(gdglinfoDTO, ratio, id);
    }

    @Override
    public List<Map> collectInfoByJgsh(GdglinfoDTO gdglinfoDTO) {
        Long gdlx = gdglinfoDTO.getGdlx();
        Long lcjd = gdglinfoDTO.getLcjdid();
        String lcjdName = gdglinfoDTO.getLcjdName();
//        if (StringUtil.isNull(gdlx)) {
//            throw new ToflyDeniedException("请传递工单类型");
//        }
        if (StringUtil.isNull(lcjd) || StringUtil.isEmpty(lcjdName)) {
            throw new ToflyDeniedException("请传递流程节点");
        }
        return baseMapper.collectInfoByJgsh(gdglinfoDTO, SecurityUtils.getUserId());
    }

    @Override
    public IPage<Gdglinfo> gdCollectDetails(Page page, GdglinfoDTO gdglinfoDTO) {
        Long lcjdid = gdglinfoDTO.getLcjdid();
        String lcjdName = gdglinfoDTO.getLcjdName();
        Long gdlx = gdglinfoDTO.getGdlx();
        Long gdxf1 = gdglinfoDTO.getGdxf1();
        Long gdxf2 = gdglinfoDTO.getGdxf2();
        Date startTime = gdglinfoDTO.getStartTime();
        Date endTime = gdglinfoDTO.getEndTime();
        String queryState = gdglinfoDTO.getQueryState();
        String inputcontent = gdglinfoDTO.getInputcontent();
        Long userId = SecurityUtils.getUserId();
        if (StringUtil.isNull(lcjdid) || StringUtil.isEmpty(lcjdName)) {
            throw new ToflyDeniedException("请传递流程节点");
        }
        LambdaQueryWrapper<Gdglinfo> lqw = new LambdaQueryWrapper<Gdglinfo>();
        lqw.and(StringUtil.isNotEmpty(inputcontent), v -> v.like(Gdglinfo::getGdbh, inputcontent).or().like(Gdglinfo::getGdms, inputcontent));
        lqw.eq(StringUtil.isNotNull(gdlx), Gdglinfo::getGdlx, gdlx)
                .eq(StringUtil.isNotNull(gdxf1), Gdglinfo::getGdxf1, gdxf1)
                .eq(StringUtil.isNotNull(gdxf2), Gdglinfo::getGdxf2, gdxf2);
        lqw.between(StringUtil.isNotNull(startTime) && StringUtil.isNotNull(endTime), Gdglinfo::getDjsj, startTime, endTime);
        //工单登记
        if (lcjdid == 39) {
            lqw.eq(Gdglinfo::getDjry, userId);
            //代办
            if ("1".equals(queryState)) {
                lqw.eq(Gdglinfo::getLcjd, lcjdid);
            }
            //已办
            else if ("2".equals(queryState)) {
//                lqw.like(Gdglinfo::getProcessDeposit , lcjdid == 39 ? "1" : lcjdid == 40 ? "2" : lcjdid == 41 ? "3" : lcjdid == 42 ? "4" : lcjdid == 43 ? "5" : lcjdid == 44 ? "6" : 7);
                //如果已办的流程，会保存流程顺序标识1：工单登记，2：认证处置等；格式1,2,3...；最多就只有七个流程节点，所以可以使用like模糊查询出来
                lqw.like(Gdglinfo::getProcessDeposit, "1");
            }//超时
            else if ("3".equals(queryState)) {
                lqw.eq(Gdglinfo::getGdcsFlag, "1");
            }//驳回
            else if ("4".equals(queryState)) {
                //由于驳回比较特殊，需要单独写，因为驳回要求的是驳回到本流程的工单
                return baseMapper.getCollectDetailsByBh(page, gdglinfoDTO, userId);
            }//终止
            else if ("5".equals(queryState)) {
                lqw.eq(Gdglinfo::getGdzzzt, "1");
            } else {
                return null;
            }
            return this.page(page, lqw);
        }
        //认证处置
        else if (lcjdid == 40) {
            lqw.like(Gdglinfo::getSlry, String.valueOf(userId));
//            lqw.between(StringUtil.isNotNull(startTime) && StringUtil.isNotNull(endTime), Gdglinfo::getRzsj, startTime, endTime);
            //代办
            if ("1".equals(queryState)) {
                lqw.eq(Gdglinfo::getLcjd, lcjdid);
            }//已办
            else if ("2".equals(queryState)) {
                lqw.like(Gdglinfo::getProcessDeposit, "2");
            }//超时
            else if ("3".equals(queryState)) {
                lqw.eq(Gdglinfo::getRzczCszt, "1");
            }//驳回
            else if ("4".equals(queryState)) {
                //由于驳回比较特殊，需要单独写，因为驳回要求的是驳回到本流程的工单
                return baseMapper.getCollectDetailsByBh(page, gdglinfoDTO, userId);
            }
            //转派
            else if ("6".equals(queryState)) {
                //转派也是需要根据流程，需要单独写
                return baseMapper.getCollectDetailsByZp(page, gdglinfoDTO, userId);
            } else {
                return null;
            }
            return this.page(page, lqw);
        }
        //认证审核
        else if (lcjdid == 41) {
            lqw.eq(Gdglinfo::getRzslry, userId);
//            lqw.between(StringUtil.isNotNull(startTime) && StringUtil.isNotNull(endTime), Gdglinfo::getShsj, startTime, endTime);
            //代办
            if ("1".equals(queryState)) {
                lqw.eq(Gdglinfo::getLcjd, lcjdid);
            }//已办
            else if ("2".equals(queryState)) {
                lqw.like(Gdglinfo::getProcessDeposit, "3");
            }//超时
            else if ("3".equals(queryState)) {
                lqw.eq(Gdglinfo::getReshCszt, "1");
            }//驳回
            else if ("4".equals(queryState)) {
                //由于驳回比较特殊，需要单独写，因为驳回要求的是驳回到本流程的工单
                return baseMapper.getCollectDetailsByBh(page, gdglinfoDTO, userId);
            } else {
                return null;
            }
            IPage<Gdglinfo> gdglinfoIPage = this.page(page, lqw);
            for (Gdglinfo record : gdglinfoIPage.getRecords()) {
                //判断业务流程的上一环节是什么，注意存在已办和未办，所以需要找到本流程上一流程的
                String processDeposit = record.getProcessDeposit();
                if (StringUtil.isNotEmpty(processDeposit)) {
                    //1.工单登记，2.认证处置3.认证审核4.认证质检  5.结果处置6.结果审核7.工单归档
                    String lcjdStr = processDeposit.substring(processDeposit.length() - 1);
                    //如果最后一个等于当前流程，则已办，需要拿上一流程的 ，倒数第二个是都逗号
                    if (lcjdStr.equals("3")) {
                        lcjdStr = processDeposit.substring(processDeposit.length() - 3);
                    }
                    String lastLcName = lcjdStr.equals("1") ? "工单登记" : lcjdStr.equals("2") ? "认证处置" : lcjdStr.equals("3") ?
                            "认证审核" : lcjdStr.equals("4") ? "认证质检" : lcjdStr.equals("5") ? "结果处置" : "";
                    if (StringUtil.isNotEmpty(lastLcName)) {
                        record.setLastLcName(lastLcName);
                    }
                }
            }
            return gdglinfoIPage;
        }
        //认证质检
        else if (lcjdid == 42) {
            lqw.eq(Gdglinfo::getShslry, userId);
//            lqw.between(StringUtil.isNotNull(startTime) && StringUtil.isNotNull(endTime), Gdglinfo::getZjsj, startTime, endTime);
            //代办
            if ("1".equals(queryState)) {
                lqw.eq(Gdglinfo::getLcjd, lcjdid);
            }//已办
            else if ("2".equals(queryState)) {
                lqw.like(Gdglinfo::getProcessDeposit, "4");
            }//超时
            else if ("3".equals(queryState)) {
                lqw.eq(Gdglinfo::getRzzjCszt, "1");
            }//驳回
            else if ("4".equals(queryState)) {
                //由于驳回比较特殊，需要单独写，因为驳回要求的是驳回到本流程的工单
                return baseMapper.getCollectDetailsByBh(page, gdglinfoDTO, userId);
            }
            //转派
            else if ("6".equals(queryState)) {
                //转派也是需要根据流程，需要单独写
                return baseMapper.getCollectDetailsByZp(page, gdglinfoDTO, userId);
            } else {
                return null;
            }
            IPage<Gdglinfo> gdglinfoIPage = this.page(page, lqw);
            for (Gdglinfo record : gdglinfoIPage.getRecords()) {
                //判断业务流程的上一环节是什么，注意存在已办和未办，所以需要找到本流程上一流程的
                String processDeposit = record.getProcessDeposit();
                if (StringUtil.isNotEmpty(processDeposit)) {
                    //1.工单登记，2.认证处置3.认证审核4.认证质检  5.结果处置6.结果审核7.工单归档
                    String lcjdStr = processDeposit.substring(processDeposit.length() - 1);
                    //如果最后一个等于当前流程，则已办，需要拿上一流程的 ，倒数第二个是都逗号
                    if (lcjdStr.equals("4")) {
                        lcjdStr = processDeposit.substring(processDeposit.length() - 3);
                    }
                    String lastLcName = lcjdStr.equals("1") ? "工单登记" : lcjdStr.equals("2") ? "认证处置" : lcjdStr.equals("3") ?
                            "认证审核" : lcjdStr.equals("4") ? "认证质检" : lcjdStr.equals("5") ? "结果处置" : "";
                    if (StringUtil.isNotEmpty(lastLcName)) {
                        record.setLastLcName(lastLcName);
                    }
                }
            }
            return gdglinfoIPage;
        }
        //结果处置
        else if (lcjdid == 43) {
//            lqw.eq(Gdglinfo::getZjczry , userId);
//            lqw.between(StringUtil.isNotNull(startTime) && StringUtil.isNotNull(endTime), Gdglinfo::getCzsj, startTime, endTime);
            //代办
            if ("1".equals(queryState)) {
                //存放工单编号集合
                Set<String> collect = new HashSet<>();
                //查询结果处置中暂未处理的工单
                List<Resultdisp> resultdispList = resultdispService.list(Wrappers.<Resultdisp>lambdaQuery()
                        //代办就是上一个流程转入的时间
//                        .between(StringUtil.isNotNull(startTime) && StringUtil.isNotNull(endTime), Resultdisp::getImportDate, startTime, endTime)
                        .eq(Resultdisp::getPersonId, userId).eq(Resultdisp::getIsFinish, "0").select(Resultdisp::getGdbh).orderByAsc(Resultdisp::getGdbh));
                if (StringUtil.isNotNull(resultdispList) && resultdispList.size() > 0) {
                    collect.addAll(resultdispList.stream().map(Resultdisp::getGdbh).collect(Collectors.toList()));
                }
                if (collect.size() > 0) {
                    lqw.in(Gdglinfo::getGdbh, collect);
                } else {
                    //没有该用户结果处置的
                    return null;
                }
            }//已办
            else if ("2".equals(queryState)) {
                //存放工单编号集合
                Set<String> collect = new HashSet<>();
                //查询结果处置中已处理的工单
                List<Resultdisp> resultdispList = resultdispService.list(Wrappers.<Resultdisp>lambdaQuery()
                        //已办就是当前处置时间
//                        .between(StringUtil.isNotNull(startTime) && StringUtil.isNotNull(endTime), Resultdisp::getImportDate, startTime, endTime)
                        .eq(Resultdisp::getPersonId, userId).eq(Resultdisp::getIsFinish, "1").select(Resultdisp::getGdbh).orderByAsc(Resultdisp::getGdbh));
                if (StringUtil.isNotNull(resultdispList) && resultdispList.size() > 0) {
                    collect.addAll(resultdispList.stream().map(Resultdisp::getGdbh).collect(Collectors.toList()));
                }
                if (collect.size() > 0) {
                    lqw.in(Gdglinfo::getGdbh, collect);
                } else {
                    //没有该用户结果处置的
                    return null;
                }
            }//超时
            else if ("3".equals(queryState)) {
                //存放工单编号集合
                Set<String> collect = new HashSet<>();
                //查询当前人的结果处置工单
                List<Resultdisp> resultdispList = resultdispService.list(Wrappers.<Resultdisp>lambdaQuery()
//                        .between(StringUtil.isNotNull(startTime) && StringUtil.isNotNull(endTime), Resultdisp::getImportDate, startTime, endTime)
                        .eq(Resultdisp::getPersonId, userId).select(Resultdisp::getGdbh).orderByAsc(Resultdisp::getGdbh));
                if (StringUtil.isNotNull(resultdispList) && resultdispList.size() > 0) {
                    collect.addAll(resultdispList.stream().map(Resultdisp::getGdbh).collect(Collectors.toList()));
                }
                lqw.eq(Gdglinfo::getJgczCszt, "1");
                if (collect.size() > 0) {
                    lqw.in(Gdglinfo::getGdbh, collect);
                } else {
                    //没有该用户结果处置的
                    return null;
                }
            }//驳回
            else if ("4".equals(queryState)) {
                //由于驳回比较特殊，需要单独写，因为驳回要求的是驳回到本流程的工单
                return baseMapper.getCollectDetailsByBh(page, gdglinfoDTO, userId);
            }
            //转派
            else if ("6".equals(queryState)) {
                //转派也是需要根据流程，需要单独写
                return baseMapper.getCollectDetailsByZp(page, gdglinfoDTO, userId);
            } else {
                return null;
            }
            IPage<Gdglinfo> gdglinfoIPage = this.page(page, lqw);
            for (Gdglinfo record : gdglinfoIPage.getRecords()) {
                //判断业务流程的上一环节是什么，注意存在已办和未办，所以需要找到本流程上一流程的
                String processDeposit = record.getProcessDeposit();
                if (StringUtil.isNotEmpty(processDeposit)) {
                    //1.工单登记，2.认证处置3.认证审核4.认证质检  5.结果处置6.结果审核7.工单归档
                    String lcjdStr = processDeposit.substring(processDeposit.length() - 1);
                    //如果最后一个等于当前流程，则已办，需要拿上一流程的 ，倒数第二个是都逗号
                    if (lcjdStr.equals("5")) {
                        lcjdStr = processDeposit.substring(processDeposit.length() - 3);
                    }
                    String lastLcName = lcjdStr.equals("1") ? "工单登记" : lcjdStr.equals("2") ? "认证处置" : lcjdStr.equals("3") ?
                            "认证审核" : lcjdStr.equals("4") ? "认证质检" : lcjdStr.equals("5") ? "结果处置" : "";
                    if (StringUtil.isNotEmpty(lastLcName)) {
                        record.setLastLcName(lastLcName);
                    }
                }
            }
            return gdglinfoIPage;
        }
        //结果审核
        else if (lcjdid == 44) {
//            lqw.eq(Gdglinfo::getDjry , userId);
//            lqw.between(StringUtil.isNotNull(startTime)&&StringUtil.isNotNull(endTime) , Gdglinfo::get , startTime , endTime);
            //代办
            if ("1".equals(queryState)) {
                Audit audit = new Audit();
                audit.setAuditType(AuditEnum.GD_TYPE.getCode());
                audit.setAuditUser(userId);
                //未审核
                audit.setAuditState(AuditEnum.AUDIT_UNCOMMITTED.getCode());
                List<Audit> result = auditClient.getAuditInfo(audit).getResult();
                Set<Long> collect = new HashSet<>();
                if (null != result && result.size() > 0) {
                    collect.addAll(result.stream().map(Audit::getAuditPlanId).collect(Collectors.toSet()));
                }
                List<Gdglinfo> gdglinfoList = gdglinfoService.list(new QueryWrapper<Gdglinfo>().lambda().eq(Gdglinfo::getJgczry, userId)
                        .eq(Gdglinfo::getLcjd, RejectedNodeEnum.JGSH.getCode()).select(Gdglinfo::getId, Gdglinfo::getGdbh));
                if (gdglinfoList.size() > 0) {
                    // 未新增审批链的数据,也满足条件
                    Set<Long> collect1 = gdglinfoList.stream().map(Gdglinfo::getId).collect(Collectors.toSet());
                    collect.addAll(collect1);
                }
                if (collect.size() > 0) {
                    lqw.in(Gdglinfo::getId, collect);
                } else {
                    //没有该用户结果审核的
                    return null;
                }
            }//已办
            else if ("2".equals(queryState)) {
                Audit audit = new Audit();
                audit.setAuditType(AuditEnum.GD_TYPE.getCode());
                audit.setAuditUser(userId);
                audit.setAuditState(AuditEnum.AUDIT_YES.getCode());
                List<Audit> result = auditClient.getAuditInfo(audit).getResult();
                Set<Long> collect = new HashSet<>();
                if (null != result && result.size() > 0) {
                    collect.addAll(result.stream().map(Audit::getAuditPlanId).collect(Collectors.toSet()));
                }
                List<Gdglinfo> gdglinfoList = gdglinfoService.list(new QueryWrapper<Gdglinfo>().lambda().eq(Gdglinfo::getJgczry, userId)
                        .eq(Gdglinfo::getLcjd, RejectedNodeEnum.JGSH.getCode()).select(Gdglinfo::getId, Gdglinfo::getGdbh));
                if (gdglinfoList.size() > 0) {
                    // 未新增审批链的数据,也满足条件
                    Set<Long> collect1 = gdglinfoList.stream().map(Gdglinfo::getId).collect(Collectors.toSet());
                    collect.addAll(collect1);
                }
                if (collect.size() > 0) {
                    lqw.in(Gdglinfo::getId, collect);
                } else {
                    //没有该用户结果审核的
                    return null;
                }
            }
            IPage<Gdglinfo> gdglinfoIPage = this.page(page, lqw);
            for (Gdglinfo record : gdglinfoIPage.getRecords()) {
                //判断业务流程的上一环节是什么，注意存在已办和未办，所以需要找到本流程上一流程的
                String processDeposit = record.getProcessDeposit();
                if (StringUtil.isNotEmpty(processDeposit)) {
                    //1.工单登记，2.认证处置3.认证审核4.认证质检  5.结果处置6.结果审核7.工单归档
                    String lcjdStr = processDeposit.substring(processDeposit.length() - 1);
                    //如果最后一个等于当前流程，则已办，需要拿上一流程的 ，倒数第二个是都逗号
                    if (lcjdStr.equals("6")) {
                        lcjdStr = processDeposit.substring(processDeposit.length() - 3);
                    }
                    String lastLcName = lcjdStr.equals("1") ? "工单登记" : lcjdStr.equals("2") ? "认证处置" : lcjdStr.equals("3") ?
                            "认证审核" : lcjdStr.equals("4") ? "认证质检" : lcjdStr.equals("5") ? "结果处置" : "";
                    if (StringUtil.isNotEmpty(lastLcName)) {
                        record.setLastLcName(lastLcName);
                    }
                }
            }
            return gdglinfoIPage;
        } else {
            return null;
        }


    }


    @Override
    public Page<Gdglinfo> gdStatisticsInfo(Page page, GdglinfoDTO gdglinfoDTO, String templateFlag, HttpServletResponse response) {

        LambdaQueryWrapper<Gdglinfo> lqw = new LambdaQueryWrapper<Gdglinfo>();
        //终止
        lqw.eq(gdglinfoDTO.getZj() != null && gdglinfoDTO.getZj() == 1, Gdglinfo::getGddjZt, Long.valueOf(GdglinfoEM.ZZ.getType()));
        lqw.eq(gdglinfoDTO.getGdlx() != null, Gdglinfo::getGdlx, gdglinfoDTO.getGdlx());
        //转派
        lqw.eq(!StringUtils.isEmpty(gdglinfoDTO.getZpzt()), Gdglinfo::getZpzt, gdglinfoDTO.getZpzt());
        //驳回
        lqw.eq(!StringUtils.isEmpty(gdglinfoDTO.getBhzt()), Gdglinfo::getBhzt, gdglinfoDTO.getBhzt());
        //超时
        lqw.and(gdglinfoDTO.getCs() != null && gdglinfoDTO.getCs() == 1, wrapper -> wrapper.eq(Gdglinfo::getRzzjCszt, 1).or().eq(Gdglinfo::getRzczCszt, 1).or()
                .eq(Gdglinfo::getReshCszt, 1).or().eq(Gdglinfo::getJgczCszt, 1));

        if (gdglinfoDTO.getLcjdid() != null) {
            if ("1".equals(gdglinfoDTO.getJdstate())) {
                lqw.like(Gdglinfo::getProcessDeposit, gdglinfoDTO.getLcjdid() % 38);
            } else {
                lqw.eq(Gdglinfo::getLcjd, gdglinfoDTO.getLcjdid());
            }
        } else {
            if (gdglinfoDTO.getGdType() != null && gdglinfoDTO.getGdType() == 1) {
                lqw.eq(Gdglinfo::getLcjd, Long.valueOf(GdglinfoEM.GDGD.getType()));
            } else if (gdglinfoDTO.getGdType() != null && gdglinfoDTO.getGdType() == 0) {
                lqw.lt(Gdglinfo::getLcjd, Long.valueOf(GdglinfoEM.GDGD.getType()));
            }
        }

        if (gdglinfoDTO.getEndTime() == null && gdglinfoDTO.getStartTime() == null) {
            gdglinfoDTO.setEndTime(new Date());
            gdglinfoDTO.setStartTime(DateTimeUtil.dateTimeDifference(-1, Calendar.MONTH));
        } else if (gdglinfoDTO.getEndTime() == null) {
            gdglinfoDTO.setEndTime(DateTimeUtil.dateTimeDifference(gdglinfoDTO.getStartTime(), 1, Calendar.MONTH));
        } else if (gdglinfoDTO.getStartTime() == null) {
            gdglinfoDTO.setStartTime(DateTimeUtil.dateTimeDifference(gdglinfoDTO.getEndTime(), -1, Calendar.MONTH));
        }
        lqw.eq("1".equals(gdglinfoDTO.getHangUp()), Gdglinfo::getHangUp, gdglinfoDTO.getHangUp());

        lqw.ge(Gdglinfo::getDjsj, gdglinfoDTO.getStartTime()).le(Gdglinfo::getDjsj, gdglinfoDTO.getEndTime());
        lqw.orderByDesc(Gdglinfo::getId);
        Page<Gdglinfo> iPage = this.page(page, lqw);
//        //导出
//        if ("1".equals(templateFlag)) {
//            //数据
//            List<Gdglinfo> gdglinfoList = iPage.getRecords();
//            //转换时间和实体
//            List<GdPercentStatic> gdPercentStaticList =
//                    JSON.parseArray(JSONArray.toJSONStringWithDateFormat(gdglinfoList, "yyyy-MM-dd HH:mm:ss"), GdPercentStatic.class);
//            //找到枚举中的文件名
//            ExcelExportFileTypeEnum excelExportFileTypeEnum = ExcelExportFileTypeEnum.getExcelExportFileTypeEnum("gdPercentStatis", templateFlag);
//            if (null == excelExportFileTypeEnum) {
//                return null;
//            }
//            Map<String, Object> dataMap = new HashMap<>();
//            dataMap.put("dataMap", gdPercentStaticList);
//            ExcelUtil.export(dataMap, excelExportFileTypeEnum, Constant.FILE_PATH_TEST_EXPORT_EXCEL, response);
//            return null;
//        }

        return iPage;
    }

    @Override
    public Page<Gdglinfo> spotCheckInfo(Page page, DateTimeDTO timeDTO, Integer bl, Integer isRxlx) {
        Date day = DateUtils.getAllDay();
        if (timeDTO.getEndTime() == null && timeDTO.getStartTime() == null) {
            timeDTO.setEndTime(day);
            timeDTO.setStartTime(DateTimeUtil.dateTimeDifference(day, -7, Calendar.HOUR_OF_DAY));
        } else if (timeDTO.getEndTime() == null) {
            Date dt = DateTimeUtil.dateTimeDifference(timeDTO.getStartTime(), 7, Calendar.DAY_OF_MONTH);
            if (dt.getTime() > day.getTime()) {
                timeDTO.setEndTime(day);
            }
        } else if (timeDTO.getStartTime() == null) {
            timeDTO.setStartTime(DateTimeUtil.dateTimeDifference(timeDTO.getEndTime(), -7, Calendar.DAY_OF_MONTH));
        }
        int count = count(new QueryWrapper<Gdglinfo>().lambda().eq(isRxlx != null, Gdglinfo::getIsRxlx, isRxlx).between(Gdglinfo::getDjsj, timeDTO.getStartTime(), timeDTO.getEndTime()).eq(Gdglinfo::getLcjd, Long.valueOf(GdglinfoEM.GDGD.getType())));
        int number = (int) Math.ceil((double) (count * bl) / 100d);
        return baseMapper.selectSpotCheckInfo(page, timeDTO, number, isRxlx);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean auditDispose(Long planId, String auditResult, String auditNotes, GdglinfoExtendDto extend) {
        // 操作用户
        Long userId = SecurityUtils.getUserId();
        Audit dto = new Audit();
        dto.setAuditType(AuditEnum.GD_TYPE.getCode());
        dto.setAuditPlanId(planId);
        Audit inputNextAudit = extend.getAudit();
        // 获取审批链
        List<Audit> list = auditClient.getAuditInfo(dto).getResult();
        if (null != list && list.size() > 0) {
            // 不支持对应的同一个负责人审批多次
            List<Audit> auditList = list.stream().
                    filter(i -> userId.equals(i.getAuditUser()) && AuditEnum.AUDIT_UNCOMMITTED.getCode()
                            .equals(i.getAuditState())).collect(Collectors.toList());
            if (auditList.size() > 0) {
                Audit audit = auditList.get(0);
                Gdglinfo gdglinfo = gdglinfoService.getById(audit.getAuditPlanId());
                Long gdglinfoId = gdglinfo.getId();
                Integer auditLevel = audit.getAuditLevel();
                Date now = DateTimeUtil.convertLDTToDate(LocalDateTime.now());
                // 修改审核对象 审核时间/审核说明/审核状态
                audit.setAuditTime(now);
                audit.setAuditNote(auditNotes);
                audit.setAuditState(auditResult);
                String processDeposit = gdglinfo.getProcessDeposit();
                if ("0".equals(gdglinfo.getJdzt())) {
                    gdglinfo.setJdzt("1");
                }
                // 判断当前审核是否为一级 且被拒绝
                if (1 == auditLevel && AuditEnum.AUDIT_NO.getCode().equals(auditResult)) {
                    // 进入则为一级驳回需要
                    // 1.修改工单状态(根据当前流转状态获取上级驳回流程)
                    gdglinfo.setLcjd(this.getRejectedNode(processDeposit));
                    gdglinfo.setProcessInfo(sub2(gdglinfo.getProcessInfo()));
                    if (gdglinfo.getLcjd().equals(Long.valueOf(GdglinfoEM.GDDJ.getType()))) {
                        gdglinfo.setProcessDeposit(null);
                        gdglinfo.setJdzt("0");
                        gdglinfo.setJdsx(null);
                    } else {
                        if (gdglinfo.getProcessDeposit().length() > 2) {
                            gdglinfo.setProcessDeposit(sub2(gdglinfo.getProcessDeposit()));
                        }
                        // 判断是否为漏点
                        if ("1".equals(gdglinfo.getIsLeak())) {
                            leakInfoService.update(new UpdateWrapper<LeakInfo>().lambda()
                                    .eq(LeakInfo::getGdinfoId, gdglinfo.getId())
                                    .set(LeakInfo::getDisposeState, LeakStateEnum.ZZCL.getCode()));
                        }
                        // 判断是否为噪音
                        if ("1".equals(gdglinfo.getIsNoise())) {
                            noiseUploadService.update(new UpdateWrapper<NoiseLoggerInfo>().lambda()
                                    .eq(NoiseLoggerInfo::getGdinfoId, gdglinfo.getId())
                                    .set(NoiseLoggerInfo::getDisposeState, NoiseStateEnum.ZZCL.getCode())
                            );

                        }
                    }
                    gdglinfo.setBhzt("1");
                    // 2.增加驳回记录
                    Gdglflow gdglflow = new Gdglflow();
                    gdglflow.setGdbh(gdglinfo.getGdbh());
                    gdglflow.setClry(SecurityUtils.getUser().getRealName());
                    gdglflow.setClsj(gdglinfo.getRzsj());
                    gdglflow.setClyj(auditNotes);
                    gdglflow.setLcjd(codeClient.getname(Long.valueOf(GdglinfoEM.JGSH.getType())));
                    gdglflow.setBbhLcjd(codeClient.getname(gdglinfo.getLcjd()));
                    // 新增被驳回的信息及时间
                    gdglflow.setBbhYj(auditNotes);
                    gdglflow.setBbhClsj(now);
                    gdglflowService.save(gdglflow);
                    // 3.清空当前计划id绑定的审批链
                    auditClient.delete(audit.getAuditType(), audit.getAuditPlanId());
                    //审核人等级减一
                    gdglinfo.setShrdj(0);
                    log.info("一级驳回处理 工单id:{},驳回工单状态为:{}", gdglinfoId, gdglinfo.getLcjdName());
                } else {
                    //选择的审核人不能与已经存在相同
                    List<Audit> audits = list.stream()
                            .filter(user -> user.getAuditUser().equals(inputNextAudit.getAuditUser())).collect(Collectors.toList());
                    if (audits.size() > 0) {
                        throw new ToflyDeniedException("不能选择相同历史审核人");
                    }
                    // 当前审批是否为通过
                    if (AuditEnum.AUDIT_YES.getCode().equals(auditResult)) {
                        //查询上一级审核等级
                        Integer shrdj = gdglinfo.getShrdj();
                        Gdflowconfig gdflowconfig = gdflowconfigService.getOne(new QueryWrapper<Gdflowconfig>().lambda().eq(Gdflowconfig::getId, gdglinfo.getLcid()));
                        Integer jgshccjb = Integer.parseInt(gdflowconfig.getJgshCcjb());
                        //是否还需要下一级审核
                        if (shrdj < jgshccjb) {
                            //工单登记添加审批链
                            if (StringUtil.isNotNull(inputNextAudit)) {
                                //得到下一级是否有已保存的审核人员
                                List<Audit> isNextAuditList = list.stream().filter(v -> v.getAuditLevel().equals(shrdj + 1)).collect(Collectors.toList());
                                //有下一级的情况
                                if (isNextAuditList.size() > 0) {
                                    Audit isNextAudit = isNextAuditList.get(0);
                                    //判断当前选择的审核人与之前保存的审核人是否相同；不相同则修改下一级审核人
                                    if (!isNextAudit.getAuditUser().equals(inputNextAudit.getAuditUser())) {
                                        isNextAudit.setAuditUser(inputNextAudit.getAuditUser());
                                        isNextAudit.setAuditNote("");
                                        //设置为待审核
                                        isNextAudit.setAuditState(AuditEnum.AUDIT_UNCOMMITTED.getCode());
                                        //修改下一级审核人
                                        auditClient.update(isNextAudit);
                                    }
                                    gdglinfo.setShrdj(isNextAudit.getAuditLevel());
                                    gdglinfo.setJgczry(isNextAudit.getAuditUser());
                                } else {
                                    inputNextAudit.setAuditState("0");
                                    inputNextAudit.setAuditPlanId(planId);
                                    inputNextAudit.setAuditType(AuditEnum.GD_TYPE.getCode());
                                    gdglinfo.setShrdj(shrdj + 1);
                                    inputNextAudit.setAuditLevel(shrdj + 1);
                                    gdglinfo.setJgczry(inputNextAudit.getAuditUser());
                                    List<Audit> addAuditList = new ArrayList<>();
                                    addAuditList.add(inputNextAudit);
                                    boolean flag = saveAuditChain(addAuditList);
                                    if (!flag) {
                                        throw new ToflyDeniedException("添加审批人信息失败");
                                    }
                                }
                                // 发送消息通知该审批人
                                this.reportGd(planId, inputNextAudit.getAuditUser(), true);
                            } else {
                                throw new ToflyDeniedException("请添加审批人信息");
                            }
                        } else {
                            // 处理审核完毕的业务
//                            if (gdflowconfig.getTransferOutType() != null && Long.valueOf(GdglinfoEM.QWX.getType()).equals(gdflowconfig.getTransferOutType())) {
//                                //工单标记挂起
//                                gdglinfo.setHangUp("1");
//                                StringBuilder str = new StringBuilder(processDeposit);
//                                str.append(",6");
//                                gdglinfo.setProcessDeposit(sub1(String.valueOf(str)));
//                                gdglinfo.setLcjd(Long.valueOf(GdglinfoEM.JGSH.getType()));
//                                if (callSwitchToInterface(extend, gdglinfo, gdflowconfig)) {
//                                    return false;
//                                }
//                            } else {

                            // 增加流程节点(增加 6,7)
                            String node = this.addProcessDeposit(processDeposit);
                            log.info("归档处理 流程节点:{}", node);
                            gdglinfo.setProcessDeposit(node);
                            //下一流程节点
                            gdglinfo.setProcessInfo(sub1(gdglinfo.getProcessInfo() + ",7"));
                            gdglinfo.setFinishTime(new Date());
                            // 修改当前工单状态为 归档
                            gdglinfo.setLcjd(Long.valueOf(GdglinfoEM.GDGD.getType()));
                            log.info("归档处理 工单id:{}", gdglinfoId);
                            // 判断是否为漏点
                            if ("1".equals(gdglinfo.getIsLeak())) {
                                leakInfoService.update(new UpdateWrapper<LeakInfo>().lambda()
                                        .eq(LeakInfo::getGdinfoId, gdglinfo.getId())
                                        .set(LeakInfo::getDisposeState, LeakStateEnum.CLWC.getCode()));
                                LeakInfo one = leakInfoService.getOne(new QueryWrapper<LeakInfo>().lambda().eq(LeakInfo::getGdinfoId, gdglinfo.getId()));
                                // 同步到公众参与对象 状态及预估水量
                                String state = "";
                                if("1".equals(one.getIsReal())){
                                    state = "3";
                                }else {
                                    state = "2";
                                }
                                leakInfoService.updatePublicLeakInfo(one.getEstimatedWaterLoss()+"",gdglinfo.getId(),state);
                            }
                            // 判断是否为噪音
                            if ("1".equals(gdglinfo.getIsNoise())) {
                                noiseUploadService.update(new UpdateWrapper<NoiseLoggerInfo>().lambda()
                                        .eq(NoiseLoggerInfo::getGdinfoId, gdglinfo.getId())
                                        .set(NoiseLoggerInfo::getDisposeState, NoiseStateEnum.CLWC.getCode())
                                );
                            }
                            // 判断是否为奖励水量
                            if("1".equals(gdglinfo.getIsRewardWater())){
                                // 同步到营销系统,成功则
                                Map<String, String> headers = new HashMap<>(12);
                                Map<String,String> restMap = new HashMap<>(12);
                                restMap.put("token","C87735654AA5087275FDE08D5C8A350A");
                                Map<String,String> restUserMap = new HashMap<>(12);

                                restUserMap.put("BH",gdglinfo.getGdbh());
                                // 获取当前工单对应的奖励水量openId,奖励水量
                                PublicRewardWaterVo waterVolumeOpenId = leakInfoService.getPublicRewardWaterVolumeOpenId(gdglinfo.getId());
                                restUserMap.put("REGISTER_OPENID",String.valueOf(waterVolumeOpenId.getOpenId()));
                                restUserMap.put("REGISTER_YHBH",gdglinfo.getKhbh());
                                restUserMap.put("REGISTER_NAME",gdglinfo.getKhxm());
                                restUserMap.put("REGISTER_ADDRESS",gdglinfo.getAddress());
                                restUserMap.put("REGISTER_PHONE",gdglinfo.getLxdh());
                                restUserMap.put("REGISTER_CONTEXT",gdglinfo.getGdms());
                                restUserMap.put("REGISTER_SL",waterVolumeOpenId.getRewardWaterVolume());
                                restUserMap.put("LY","1");
                                restMap.put("data",JSON.toJSONString(restUserMap));
                                try {
                                    String s = HttpClientUtil.doPostJson(yxJLSLUrl, headers, JSON.toJSONString(restMap));
                                    JSONObject jsonObject = JSON.parseObject(s);
                                    if("200".equals(jsonObject.get("Code")+"")){
                                        leakInfoService.updateYxState(gdglinfo.getId());
                                    }else {
                                        log.error("营销调用异常返回{}",s);
                                    }
                                } catch (IOException e) {
                                    e.printStackTrace();
                                    log.error("营销调用失败{}",e.getMessage());
                                }


                            }
//                            }
                        }
                    } else {
                        // 审核不通过 获取上级审核
                        Audit superiorAudit = this.getSuperiorAudit(list, audit.getAuditLevel());
                        // 1.修改上级审核状态为 0 未审核
                        // 2.修改当前审核状态为 3 不可审核
                        superiorAudit.setAuditState(AuditEnum.AUDIT_UNCOMMITTED.getCode());
                        auditClient.update(superiorAudit);
                        audit.setAuditState(AuditEnum.AUDIT_NOT_DISPOSE.getCode());
                        // 发送消息通知该审批人
                        this.reportGd(planId, superiorAudit.getAuditUser(), false);
                        //审核人等级减一
                        gdglinfo.setShrdj(gdglinfo.getShrdj() - 1);
                        log.info("审核不通过 工单id:{},驳回上级审核人为:{}", gdglinfoId, superiorAudit.getAuditUser());
                    }
                }
                // 待办事项处理状态置为完成
                // 待办事项处理
                Usertask usertask = new Usertask();
                usertask.setTableName(AuditEnum.MESSAGE_TABLE.getCode());
                usertask.setHandleUser(SecurityUtils.getUserId());
                usertask.setTkty(AuditEnum.MESSAGE_TYPE_GD.getCode());
                usertask.setIshandle("0");
                usertask.setTableId(gdglinfoId);
                List<Usertask> result = userTaskClient.getUserTaskInfo(usertask).getResult();
                if (null != result && result.size() > 0) {
                    Usertask task = result.get(0);
                    task.setHandleTime(DateTimeUtil.convertLDTToDate(LocalDateTime.now()));
                    task.setHandleUser(SecurityUtils.getUserId());
                    task.setIshandle("1");
                    userTaskClient.updateById(task);
                }
                Checkhistory checkhistory = new Checkhistory();
                checkhistory.setType(dto.getAuditType());
                checkhistory.setCheckId(dto.getAuditPlanId());
                checkhistory.setAuditResult(auditResult);
                checkhistory.setAuditNotes(auditNotes);
                checkhistory.setAuditUser(userId);
                checkhistory.setAuditTime(now);
                // 保存审核记录
                auditClient.saveAuditHisInfo(checkhistory);
                // 更新当前审批对象
                auditClient.update(audit);
                // 更新工单信息
                Gdglinfo updateGd = new Gdglinfo();
                updateGd.setId(gdglinfoId);
                updateGd.setHangUp(gdglinfo.getHangUp());
                updateGd.setBhzt(gdglinfo.getBhzt());
                updateGd.setLcjd(gdglinfo.getLcjd());
                updateGd.setFinishTime(gdglinfo.getFinishTime());
                updateGd.setJdzt(gdglinfo.getJdzt());
                updateGd.setProcessDeposit(gdglinfo.getProcessDeposit());
                updateGd.setProcessInfo(gdglinfo.getProcessInfo());
                updateGd.setShrdj(gdglinfo.getShrdj());
                if (StringUtil.isNotNull(inputNextAudit.getAuditUser())) {
                    updateGd.setJgczry(inputNextAudit.getAuditUser());
                }
                gdglinfoService.updateById(updateGd);
                log.info("当前工单审核流程节点:{} 处理完成", audit.getAuditLevel());
//                callbackForeign(gdglinfo, gdglinfo);
            } else {
                // 当前用户没有审该数据权限
                throw new BusinessException(Constant.PLAN_DISPATCHING_AUDIT_ERROR_CODE, Constant.PLAN_DISPATCHING_AUDIT_ERROR);
            }
        } else {
            throw new BusinessException(Constant.PLAN_DISPATCHING_AUDIT_ERROR_CODE, Constant.PLAN_DISPATCHING_AUDIT_ERROR);
        }
        removeDB(planId, CommonConstants.JGSH);
        return true;
    }

    /**
     * 增加节点流程
     *
     * @param processDeposit
     * @return
     */
    private String addProcessDeposit(String processDeposit) {
        List<String> collect = Arrays.stream(processDeposit.split(Constant.CSV))
                .collect(Collectors.toList());
        collect.add("6");
        collect.add("7");
        List<String> sortedList = collect.stream().sorted().collect(Collectors.toList());
        StringBuilder stringBuilder = new StringBuilder("");
        sortedList.forEach(info -> {
            stringBuilder.append(info).append(Constant.CSV);
        });
        return stringBuilder.toString();
    }

    @Override
    public List<AuditInfoVo> isAuditChain(Long planId) {
        Audit audit = new Audit();
        audit.setAuditType(AuditEnum.GD_TYPE.getCode());
        audit.setAuditPlanId(planId);
        List<Audit> result = auditClient.getAuditInfo(audit).getResult();
        if (null != result && result.size() > 0) {
            List<AuditInfoVo> auditInfoVoList = new ArrayList<>();
            result.forEach(info -> {
                AuditInfoVo vo = JSON.parseObject(JSON.toJSONString(info), AuditInfoVo.class);
                User result1 = userClent.getById(info.getAuditUser()).getResult();
                if (null != result1) {
                    vo.setAuditUserName(result1.getRealName());
                    vo.setDeptId(result1.getDepartmentId());
                    vo.setDeptName(result1.getDepartmentName());
                }
                vo.setAuditStateName(IsAuditEnum.getCodeForValue(info.getAuditState()));
                auditInfoVoList.add(vo);
            });
            if (auditInfoVoList.size() > 0) {
                auditInfoVoList.sort(Comparator.comparing(AuditInfoVo::getAuditLevel));
            }
            return auditInfoVoList;
        }
        return null;
    }

    @Override
    public boolean saveAuditChain(List<Audit> auditList) {
        // 判断当前审核链列表是否有相同审核人 ,若存在相同审核人则不允许新增
        Set<Long> collect = auditList.stream().map(Audit::getAuditUser).collect(Collectors.toSet());
        if (auditList.size() > collect.size()) {
            throw new BusinessException(Constant.AUDIT_USER_REPEAT_ERROR_CODE, Constant.AUDIT_USER_REPEAT_ERROR);
        }
        auditList.forEach(info -> {
            // 默认一级待审核 0
            Integer auditLevel = info.getAuditLevel();
            if (0 == auditLevel) {
                info.setAuditState("0");
                // 发送消息通知该审批人
                this.reportGd(info.getAuditPlanId(), info.getAuditUser(), true);
            }
            if (StringUtils.isEmpty(info.getAuditState())) {
                info.setAuditState(null);

            }
            info.setAuditTime(null);
            info.setAuditNote(null);
        });
        // 待办事项处理状态置为完成
        // 待办事项处理
        Usertask usertask = new Usertask();
        usertask.setTableName(AuditEnum.MESSAGE_TABLE.getCode());
        usertask.setIshandle("0");
        usertask.setTknm(CommonConstants.JGSH);
        usertask.setHandleUser(SecurityUtils.getUserId());
        usertask.setTableId(auditList.get(0).getAuditPlanId());
        List<Usertask> result = userTaskClient.getUserTaskInfo(usertask).getResult();
        if (null != result && result.size() > 0) {
            Usertask task = result.get(0);
            task.setHandleTime(DateTimeUtil.convertLDTToDate(LocalDateTime.now()));
            task.setHandleUser(SecurityUtils.getUserId());
            task.setIshandle("1");
            userTaskClient.updateById(task);
        }


        auditClient.save(JSON.toJSONString(auditList));
        return true;
    }

    @Override
    public boolean updateAuditChain(List<Audit> auditList) {
        auditList.forEach(info -> {
            // 当前状态为不可审核可修改
            String auditState = info.getAuditState();
            if (AuditEnum.AUDIT_NOT_DISPOSE.getCode().equals(auditState)) {
                auditClient.update(info);
            }
        });
        return true;
    }

    @Override
    public List<Checkhistory> getAuditHisInfo(Long planId) {
        Checkhistory checkhistory = new Checkhistory();
        checkhistory.setCheckId(planId);
        checkhistory.setType(AuditEnum.GD_TYPE.getCode());
        return (List<Checkhistory>) auditClient.getAuditHisInfo(checkhistory).getResult();
    }

    /**
     * 抢维修工单归档
     *
     * @param wxgdbh
     * @return
     */
    @Override
    public Boolean updateGdLcjdState(String wxgdbh, Integer type) {
        GdglCirculation gdglCirculation = gdglCirculationService.getOne(new QueryWrapper<GdglCirculation>().lambda().eq(GdglCirculation::getOtherBh, wxgdbh).eq(GdglCirculation::getGdstate, "0"));
        if (gdglCirculation == null) {
            return false;
        }

        Gdglinfo gdglinfo = this.getOne(new QueryWrapper<Gdglinfo>().lambda().eq(Gdglinfo::getGdbh, gdglCirculation.getGdbh()));
        if (gdglinfo == null) {
            return false;
        }
        if (type != null && type == 1) {
            StringBuilder str = new StringBuilder(gdglinfo.getProcessDeposit());
            str.append(",7");
            return this.update(new UpdateWrapper<Gdglinfo>().lambda()
                    .set(Gdglinfo::getLcjd, Long.valueOf(GdglinfoEM.GDGD.getType()))
                    .set(Gdglinfo::getProcessDeposit, sub1(String.valueOf(str)))
                    .set(Gdglinfo::getHangUp, "0").eq(Gdglinfo::getGdbh, gdglCirculation.getGdbh()));
        } else if (type != null && type == 0) {
            gdglCirculationService.update(new UpdateWrapper<GdglCirculation>().lambda().set(GdglCirculation::getGdstate, "1").eq(GdglCirculation::getId, gdglCirculation.getId()));
            return this.update(new UpdateWrapper<Gdglinfo>().lambda().set(Gdglinfo::getHangUp, "-1").eq(Gdglinfo::getGdbh, gdglCirculation.getGdbh()));
        }
        return false;

    }

    /**
     * 调用接口查询第三方抢维修信息
     *
     * @param gdbh
     * @return
     */
    @Override
    public List<RepairOrderDetailVo> gdGdQWXInfo(String gdbh, String flag, String type) {
        List<GdglCirculation> gdglCirculations = gdglCirculationService.list(new QueryWrapper<GdglCirculation>().lambda().eq(GdglCirculation::getGdbh, gdbh).eq(!StringUtils.isEmpty(type), GdglCirculation::getGdstate, type));
        if (gdglCirculations == null || gdglCirculations.isEmpty()) {
            return null;
        }
        List<RepairOrderDetailVo> rds = gdglCirculations.stream().map(t -> orderClient.getPlanRepairOrderDetail(Long.valueOf(t.getOtherBh()), flag).getResult()).collect(Collectors.toList());
        return rds;
    }

    /**
     * 获取审核一级驳回上级
     *
     * @param processDeposit
     * @return
     */
    private Long getRejectedNode(String processDeposit) {
        List<Long> warnTypeIdList = Arrays.stream(processDeposit.split(Constant.CSV)).map(s -> Long.parseLong(s.trim()))
                .collect(Collectors.toList());
        if (warnTypeIdList.size() > 1) {
            String substring = processDeposit.substring(processDeposit.lastIndexOf(Constant.CSV) + 1);
            return RejectedNodeEnum.getNodeForCode(substring);
        } else {
            return RejectedNodeEnum.getNodeForCode(String.valueOf(warnTypeIdList.get(0)));
        }

    }


    /**
     * 审批下级查询
     *
     * @param list
     * @param auditLevel
     * @return
     */
    private Audit getNextAudit(List<Audit> list, Integer auditLevel) {
        AtomicReference<Audit> audit = new AtomicReference<>();
        AtomicBoolean flag = new AtomicBoolean(true);
        list.sort(Comparator.comparing(Audit::getAuditLevel));
        list.forEach(info -> {
            if (flag.get()) {
                if (auditLevel < info.getAuditLevel()) {
                    audit.set(info);
                    flag.set(false);
                }
            }
        });
        return audit.get();
    }

    /**
     * 审批上级查询
     *
     * @param list
     * @param auditLevel
     * @return
     */
    private Audit getSuperiorAudit(List<Audit> list, Integer auditLevel) {
        AtomicReference<Audit> audit = new AtomicReference<>();
        AtomicBoolean flag = new AtomicBoolean(true);
        // level排序
        list.sort(Comparator.comparing(Audit::getAuditLevel).reversed());
        list.forEach(info -> {
            if (flag.get()) {
                if (auditLevel > info.getAuditLevel()) {
                    audit.set(info);
                    flag.set(false);
                }
            }
        });
        return audit.get();
    }

    /**
     * 消息发送
     *
     * @param id
     * @param userId
     * @param flag
     */
    public void reportGd(Long id, Long userId, boolean flag) {
        Messagepush messagepush = new Messagepush();
        // 消息主题/消息类型/消息表名/消息表中id/路由地址跳转/消息详情
        messagepush.setTopic(AuditEnum.MESSAGE_TOPIC.getCode());
        messagepush.setType(AuditEnum.MESSAGE_TYPE.getCode());
        messagepush.setTableName(AuditEnum.MESSAGE_TABLE.getCode());
        messagepush.setRouteIp("/work/order/finalDecision1");
        messagepush.setRouteIpApp("com.tofly.tyuan.ui.activity.YwgdListActivity");
        messagepush.setTableId(id);
        // 消息与接收人信息处理
        this.setMessageRecipient(messagepush, userId);
        // flag是否代办任务发送消息
        if (flag) {
            // 新增代办任务
            Usertask usertask = new Usertask();
            usertask.setStartTime(new Date());
            usertask.setTknm(AuditEnum.MESSAGE_TOPIC.getCode());
            usertask.setTkty(AuditEnum.MESSAGE_TYPE_GD.getCode());
            usertask.setTableName(AuditEnum.MESSAGE_TABLE.getCode());
            usertask.setTableId(id);
            usertask.setIshandle("0");
            usertask.setRouteIp("/work/order/finalDecision1");
            usertask.setRouteAppIp("com.tofly.tyuan.ui.activity.YwgdListActivity");
            usertask.setHandleUser(userId);
            userTaskClient.save(usertask);
        }
    }

    /**
     * 消息处理
     *
     * @param messagepush
     * @param userId
     */
    public void setMessageRecipient(Messagepush messagepush, Long userId) {
        try {
            Long messagePushId = messageClient.save(messagepush).getResult();
            Messagerecipient messagerecipient = new Messagerecipient();
            messagerecipient.setMessageId(messagePushId);
            messagerecipient.setRecipient(userId);
            messagerecipient.setFlag(AuditEnum.MESSAGE_SATE_NO.getCode());
            messageStateClient.save(messagerecipient).getResult();

        } catch (FeignException e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }

    }

    /**
     * list 输出 page
     *
     * @param page     page
     * @param pageList list
     * @return page
     */
    public static Page listToPage(Page page, List pageList) {
        // 当前页第一条数据在List中的位置
        int start = (int) ((page.getCurrent() - 1) * page.getSize());
        // 当前页最后一条数据在List中的位置
        int end = (int) ((start + page.getSize()) > pageList.size() ? pageList.size() : (page.getSize() * page.getCurrent()));
        page.setRecords(new ArrayList<>());
        if (page.getSize() * (page.getCurrent() - 1) <= page.getTotal()) {
            // 分隔列表 当前页存在数据时 设置
            page.setRecords(pageList.subList(start, end));
        }
        page.setTotal(pageList.size());
        return page;
    }

    /**
     * 辅助派工
     */
    @Override
    public List<AuxiliaryDispatchingVo> auxiliaryDispatching(String deptIds) {
        // 获取当前用户部门今天已签到的所有用户最新位置信息列表
        List<AuxiliaryDispatchingVo> auxiliaryDispatchingVos = new ArrayList<>();
        List<AuxiliarySingleVo> result = orderClient.getAuxiliarySingle(StringUtils.isEmpty(deptIds) ? SecurityUtils.getUserDeptId() + "" : deptIds).getResult();
        log.info("获取当前用户部门今天已签到的所有用户最新位置信息列表:{}", JSON.toJSONString(result));
        if (null != result && result.size() > 0) {
            // 获取用户列表
            Set<Long> userIdList = result.stream().map(AuxiliarySingleVo::getUserId).collect(Collectors.toSet());
            // 查询当前今日排班情况
            Date currentDate = DateTimeUtil.convertLDTToDate(DateTimeUtil.getTodayBeginTime());
            List<Dutyroster> list = dutyrosterService.list(new QueryWrapper<Dutyroster>().lambda()
                    .eq(Dutyroster::getDutyDate, currentDate)
                    .eq(Dutyroster::getIsHis, "0")
                    .in(Dutyroster::getDutyUser, userIdList));

            auxiliaryDispatchingVos = JSONArray.parseArray(JSON.toJSONString(result), AuxiliaryDispatchingVo.class);
            log.info("业务工单辅助派工列表{}", JSON.toJSONString(auxiliaryDispatchingVos));
            if (null != list && list.size() > 0 && auxiliaryDispatchingVos.size() > 0) {
                Map<Long, Dutyroster> collect = list.stream().collect(Collectors.toMap(Dutyroster::getDutyUser, a -> a, (k1, k2) -> k2));
                auxiliaryDispatchingVos.forEach(info -> {
                    Long userId = info.getUserId();
                    Dutyroster dutyroster = collect.get(userId);
                    if(null!=dutyroster){
                        info.setWorkTime(dutyroster.getWorkTime());
                        info.setWorkTimeName(dutyroster.getWorkName());
                    }
                });
            }

        } else {
            throw new BusinessException(Constant.SING_USER_IS_NULL_CODE, Constant.SING_USER_IS_NULL);
        }
        return auxiliaryDispatchingVos;
    }

    @Override
    public Boolean orderUrgent(Long orderId, String lcjd, String userIds) {
        boolean update = this.update(new UpdateWrapper<Gdglinfo>().lambda().eq(Gdglinfo::getId, orderId)
                .set(Gdglinfo::getIsEmergency, "1"));
        if (update) {
            Set<Long> userIdSet = Arrays.stream(userIds.split(Constant.CSV)).map(s -> Long.parseLong(s.trim()))
                    .collect(Collectors.toSet());
            String routeIp = "";
            String routeIpApp = "";
            String topic = "";
            if (GdglinfoEM.GDDJ.getType().equals(lcjd)) {
                routeIp = GD_URL;
                routeIpApp = GD_URLAPP;
                topic = CommonConstants.GDDJ;
            } else if (GdglinfoEM.RZCZ.getType().equals(lcjd)) {
                routeIp = RZ_URL;
                routeIpApp = RZ_URLAPP;
                topic = CommonConstants.RZCL;
            } else if (GdglinfoEM.JGSH.getType().equals(lcjd)) {
                routeIp = JGSH_URL;
                routeIpApp = JGSH_URLAPP;
                topic = CommonConstants.JGSH;
            }
            String finalRouteIp = routeIp;
            String finalRouteIpApp = routeIpApp;
            String finalTopic = topic;
            userIdSet.forEach(userId -> {
                // 获取当前业务工单流程状态
                Messagepush messagepush = new Messagepush();
                messagepush.setRouteIp(finalRouteIp);
                messagepush.setRouteIpApp(finalRouteIpApp);
                messagepush.setMessage("加急督办");
                messagepush.setTopic(finalTopic);
                messagepush.setType("6");
                // 加急
                messagepush.setIsEmergency("1");
                ResultRespone<Long> rl = messageClient.save(messagepush);
                if (rl != null) {
                    Long result1 = rl.getResult();
                    //添加指派人
                    Messagerecipient messagerecipient = new Messagerecipient();
                    messagerecipient.setMessageId(result1);
                    messagerecipient.setRecipient(userId);
                    messageStateClient.save(messagerecipient);
                }
            });
        } else {
            return false;
        }
        return true;
    }

    @Override
    public List<OrderUserDealNumVo> getOrderUserDealNum() {
        return baseMapper.getOrderUserDealNum();
    }
}
