package com.tofly.qualitycontrol.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
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.google.common.collect.Maps;
import com.tofly.api.CodeClient;
import com.tofly.api.DepartmentClient;
import com.tofly.common.core.entity.ResultRespone;
import com.tofly.common.core.util.DateUtil;
import com.tofly.common.oauth.exception.ToflyDeniedException;
import com.tofly.common.oauth.util.SecurityUtils;
import com.tofly.pojo.Department;
import com.tofly.pojo.message.Messagepush;
import com.tofly.qualitycontrol.common.QualityControlConstant;
import com.tofly.qualitycontrol.dto.*;
import com.tofly.qualitycontrol.entity.*;
import com.tofly.qualitycontrol.mapper.RectifyOrderMapper;
import com.tofly.qualitycontrol.qcenum.QualityControlMessageTopicEnum;
import com.tofly.qualitycontrol.qcenum.QualityControlMessageTypeEnum;
import com.tofly.qualitycontrol.service.*;
import com.tofly.qualitycontrol.util.ConfigUtils;
import com.tofly.qualitycontrol.vo.*;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import static com.tofly.common.oauth.util.SecurityUtils.getUserDeptId;
import static com.tofly.common.oauth.util.SecurityUtils.getUserId;
import static com.tofly.qualitycontrol.util.QualityControlUtil.*;
import static java.lang.Long.valueOf;

/**
 * 整改服务实现类
 *
 * @author B
 */
@Service
@RequiredArgsConstructor
public class RectifyOrderServiceImpl extends ServiceImpl<RectifyOrderMapper, RectifyOrder> implements IRectifyOrderService, QualityControlConstant {

    private final IQualityControlMessageRecipientService qualityControlMessageRecipientService;
    private final IRejectedRecordService rejectedRecordService;
    private final DepartmentClient departmentClient;
    private final IQualityControlFileService fileService;
    private final IRejectedCountConfigService rejectedCountConfigService;
    private final MassauditService massauditService;

    private final IZlTransferService IZlTransferService;

    private final CodeClient codeClient;

    private final ConfigUtils configUtils;

    private final static String MASSAUDIT_NAME = "TF_YWPN_MASSAUDIT_W";

    @Lazy
    @Resource
    private ICertificationOrderService certificationOrderService;
    @Value("${xrty.ftp.qualityControl}")
    private String certificationOrderFilePath;
    @Value("${xrtyquality.complete.ratio}")
    private Integer ratio;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateRectifyIssue(RectifyOrder rectifyOrder, List<MultipartFile> fileList, String executeAdvice) {
        Long rectifyOrderId = rectifyOrder.getId();

        //可能存在的之前的被驳回的整改工单 构建查询器
        LambdaQueryWrapper<RectifyOrder> queryWrapper = Wrappers.<RectifyOrder>lambdaQuery()
                .eq(RectifyOrder::getCertificationNumber, rectifyOrder.getCertificationNumber())
                .eq(RectifyOrder::getIssueStatus, FLOW_REJECTED);

        RectifyOrder oldRectifyOrder = getOne(queryWrapper);

        boolean isExist = Objects.nonNull(oldRectifyOrder);


        RectifyOrder order = getById(rectifyOrderId);
        //存储文件
        String fileIdsdb = order.getIssueFileIds();
        String fileIds = rectifyOrder.getIssueFileIds();
        StringBuilder files = saveFiles(fileList, fileIdsdb, fileIds);
        if (files == null && CollUtil.isNotEmpty(fileList)) {
            return false;
        }
        if (StringUtils.isEmpty(files)) {
            this.update(new UpdateWrapper<RectifyOrder>().lambda().set(RectifyOrder::getIssueFileIds, "").eq(RectifyOrder::getId, rectifyOrderId));
        }
        rectifyOrder.setIssueFileIds(files.toString());
        Boolean flag3 = true;
        Boolean flag4 = true;
        //删除之前的整改工单
        if (isExist) {
            flag4 = remove(queryWrapper);
        }
        String issueStatus = rectifyOrder.getIssueStatus();
        //对应工单
        CertificationOrder certificationOrder = certificationOrderService.getOne(Wrappers.<CertificationOrder>lambdaQuery().eq(CertificationOrder::getCertificationNumber, rectifyOrder.getCertificationNumber()));
        //进入整改处置
        if (FLOW_NEXT.equals(issueStatus)) {
            //更新流程环节
            certificationOrder.setCurrentProcess(DEAL_PROCESS);
            //下个环节状态值设默认值
            rectifyOrder.setRectifyStatus(FLOW_CURRENT_PROCESS);
            if (order.getIssueTimeLimit().getTime() < System.currentTimeMillis()) {
                if (order.getIssueExceptionStatus().equals(FLOW_REJECTED_STATUS)) {
                    rectifyOrder.setIssueExceptionStatus(FLOW_OVERTIME_REJECTED_STATUS);
                } else {
                    rectifyOrder.setIssueExceptionStatus(FLOW_OVERTIME_STATUS);
                }
            }
            Messagepush messagePush = getMessagePush(rectifyOrderId, RECTIFY_RESULT_MESSAGE, QualityControlMessageTopicEnum.RECTIFY_PROCESS, QualityControlMessageTypeEnum.MESSAGE_TYPE_QUALITY_ORDER);
            messagePush.setRouteIp(configUtils.getZgczUrl());
            messagePush.setRouteIpApp(configUtils.getZgczUrlapp());
            qualityControlMessageRecipientService.setMessageRecipient(messagePush, order.getRectifyPersonId(), rectifyOrder.getResultTimeLimit());
        } else if (FLOW_REJECTED.equals(issueStatus)) {
            //增加驳回记录
            RejectedRecord rejectedRecord = RejectedRecord.builder()
                    .certificationNumber(rectifyOrder.getCertificationNumber())
                    .executeDept(rectifyOrder.getCertificationDept())
                    .executePerson(rectifyOrder.getCertificationPerson())
                    .executePersonId(rectifyOrder.getCertificationPersonId())
                    //.executeTime(rectifyOrder.getCertificationTime())
                    .executeTime(DateUtil.getCurrentTime())
                    .executeAdvice(executeAdvice)
                    .currentProcess(ISSUE_PROCESS)
                    .createTime(DateUtil.getCurrentTime())
                    .createUser(SecurityUtils.getUserName())
                    .createUserId(SecurityUtils.getUserId()).build();

            flag3 = rejectedRecordService.save(rejectedRecord);
            if (certificationOrder.getCertificationExceptionStatus() == null || certificationOrder.getCertificationExceptionStatus() == 0) {
                certificationOrder.setCertificationExceptionStatus(FLOW_REJECTED_STATUS);
            } else if (certificationOrder.getCertificationExceptionStatus() == 1) {
                certificationOrder.setCertificationExceptionStatus(FLOW_OVERTIME_REJECTED_STATUS);
            }
            //工单更新检验记录状态
            certificationOrder.setCertificationStatus(FLOW_CURRENT_PROCESS).setCurrentProcess(INSPECTION_PROCESS);
            certificationOrder.setOrderExceptionStatus(FLOW_REJECTED_STATUS);

            Messagepush messagePush = getMessagePush(certificationOrder.getId(), ISSUE_REJECTED_MESSAGE, QualityControlMessageTopicEnum.INSPECTION_PROCESS, QualityControlMessageTypeEnum.MESSAGE_TYPE_QUALITY_ORDER);
            messagePush.setRouteIp(configUtils.getJyjlUrl());
            messagePush.setRouteIpApp(configUtils.getJyjlUrlapp());
            qualityControlMessageRecipientService.setMessageRecipient(messagePush, certificationOrder.getCertificationPersonId(), null);
        }
        if (!FLOW_CURRENT_PROCESS.equals(issueStatus)) {
            qualityControlMessageRecipientService.removeDB(rectifyOrderId, QualityControlMessageTopicEnum.ISSUE_PROCESS);
        }
        Boolean flag1 = updateById(rectifyOrder);
        Boolean flag2 = certificationOrderService.updateById(certificationOrder);

        return flag1 && flag2 && flag3 && flag4;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateRectifyIssue(RectifyOrder rectifyOrder, List<MultipartFile> fileList, String executeAdvice, Massaudit maudit) {
        Long rectifyOrderId = rectifyOrder.getId();

        //可能存在的之前的被驳回的整改工单 构建查询器
//        LambdaQueryWrapper<RectifyOrder> queryWrapper = Wrappers.<RectifyOrder>lambdaQuery()
//                .eq(RectifyOrder::getCertificationNumber, rectifyOrder.getCertificationNumber())
//                .eq(RectifyOrder::getIssueStatus, FLOW_REJECTED);

//        RectifyOrder oldRectifyOrder = getOne(queryWrapper);

//        boolean isExist = Objects.nonNull(oldRectifyOrder);


        RectifyOrder order = getById(rectifyOrderId);
        //存储文件
        String fileIdsdb = order.getIssueFileIds();
        String fileIds = rectifyOrder.getIssueFileIds();
        StringBuilder files = saveFiles(fileList, fileIdsdb, fileIds);
        if (files == null && CollUtil.isNotEmpty(fileList)) {
            return false;
        }
        if (StringUtils.isEmpty(files)) {
            this.update(new UpdateWrapper<RectifyOrder>().lambda().set(RectifyOrder::getIssueFileIds, "").eq(RectifyOrder::getId, rectifyOrderId));
        }
        assert files != null;
        rectifyOrder.setIssueFileIds(files.toString());

        //删除之前的整改工单
//        if (isExist) {
//            remove(queryWrapper);
//        }
        String issueStatus = rectifyOrder.getIssueStatus();
        //对应工单
        CertificationOrder certificationOrder = certificationOrderService.getOne(Wrappers.<CertificationOrder>lambdaQuery().eq(CertificationOrder::getCertificationNumber, rectifyOrder.getCertificationNumber()));

        if (maudit == null) {
            throw new ToflyDeniedException("审核信息为空");
        }

        //查询需当前审核人员审核相关记录
        Massaudit massaudit = massauditService.getOne(Wrappers.<Massaudit>lambdaQuery()
                .eq(Massaudit::getAuditUser, getUserId())
                .eq(Massaudit::getAuditDept, getUserDeptId())
                .eq(Massaudit::getCode, rectifyOrder.getCertificationNumber())
                .eq(Massaudit::getProcess, FLOW_PROCESS_ONE)
                .eq(Massaudit::getAuditState, FLOW_AUDIT_DEFAULT));
        //为空说明是之前工单，为之前的工单生成审核记录
        if (massaudit == null) {
            massaudit = new Massaudit();
            massaudit.setInitiator(certificationOrder.getCertificationPersonId())
                    .setAuditUser(getUserId())
                    .setMsg(maudit.getMsg())
                    .setAuditState(FLOW_AUDIT_DEFAULT)
                    .setProcess(FLOW_PROCESS_ONE)
                    .setAuditDept(getUserDeptId())
                    .setNum(1L)
                    .setCode(certificationOrder.getCertificationNumber());
            massauditService.save(massaudit);
        }
        //进入整改处置
        if (FLOW_NEXT.equals(issueStatus)) {
            //如果查询不为空说明该工单验证审核时已生成该审核信息

            //修改部分审核信息
            massaudit.setMsg(maudit.getMsg())
                    .setAuditUser(getUserId())
                    .setAuditDept(getUserDeptId())
                    .setAuditState(FLOW_AUDIT_THROUGH)
                    .setFileIds(files.toString());
            //直接进入下一环节
            massauditService.updateById(massaudit);

            //下一环节没有选择审核人员
            if (maudit.getAuditUser() == null) {
                //更新流程环节
                certificationOrder.setCurrentProcess(DEAL_PROCESS);
                //下个环节状态值设默认值
                rectifyOrder.setRectifyStatus(FLOW_CURRENT_PROCESS);
                if (order.getIssueTimeLimit().getTime() < System.currentTimeMillis()) {
                    if (order.getIssueExceptionStatus().equals(FLOW_REJECTED_STATUS)) {
                        rectifyOrder.setIssueExceptionStatus(FLOW_OVERTIME_REJECTED_STATUS);
                    } else {
                        rectifyOrder.setIssueExceptionStatus(FLOW_OVERTIME_STATUS);
                    }
                }
                Messagepush messagePush = getMessagePush(rectifyOrderId, RECTIFY_RESULT_MESSAGE, QualityControlMessageTopicEnum.RECTIFY_PROCESS, QualityControlMessageTypeEnum.MESSAGE_TYPE_QUALITY_ORDER);
                messagePush.setRouteIp(configUtils.getZgczUrl());
                messagePush.setRouteIpApp(configUtils.getZgczUrlapp());
                qualityControlMessageRecipientService.setMessageRecipient(messagePush, getUserId(), rectifyOrder.getResultTimeLimit());
                qualityControlMessageRecipientService.removeDB(rectifyOrderId, QualityControlMessageTopicEnum.ISSUE_PROCESS);

            } else {
                //生成下个审核人的部分信息
                Massaudit audit = new Massaudit();
                audit.setParentId(massaudit.getId())
                        .setFileIds(files.toString())
                        .setInitiator(getUserId())
                        .setAuditDept(maudit.getAuditDept())
                        .setAuditUser(maudit.getAuditUser())
                        .setCode(rectifyOrder.getCertificationNumber())
                        .setProcess(FLOW_PROCESS_ONE)
                        .setNum(massaudit.getNum() + 1)
                        .setAuditState(FLOW_AUDIT_DEFAULT);

                massauditService.save(audit);

                rectifyOrder.setIssueStatus(FLOW_CURRENT_PROCESS);
                //因为这是先清除所有整改下达的，所以先清除，再生成
                qualityControlMessageRecipientService.removeDB(rectifyOrderId, QualityControlMessageTopicEnum.ISSUE_PROCESS);

                Messagepush messagePush = getMessagePush(rectifyOrderId, RECTIFY_ISSUED_AUDIT_MESSAGE, QualityControlMessageTopicEnum.ISSUE_PROCESS, QualityControlMessageTypeEnum.MESSAGE_TYPE_QUALITY_ORDER);
                messagePush.setRouteIp(configUtils.getZgxdUrl());
                messagePush.setRouteIpApp(configUtils.getZgxdUrlapp());
                qualityControlMessageRecipientService.setMessageRecipient(messagePush, maudit.getAuditUser(), null);
            }

        } else if (FLOW_REJECTED.equals(issueStatus)) {

            //如果生成的驳回信息登记为1级别，则驳回就直接回到验证记录
            if (massaudit.getNum() == 1) {

                RejectedRecord rejectedRecord = RejectedRecord.builder()
                        .certificationNumber(rectifyOrder.getCertificationNumber())
                        .executeDept(rectifyOrder.getCertificationDept())
                        .executePerson(rectifyOrder.getCertificationPerson())
                        .executePersonId(rectifyOrder.getCertificationPersonId())
                        //.executeTime(rectifyOrder.getCertificationTime())
                        .executeTime(DateUtil.getCurrentTime())
                        .executeAdvice(executeAdvice)
                        .currentProcess(ISSUE_PROCESS)
                        .createTime(DateUtil.getCurrentTime())
                        .createUser(SecurityUtils.getUserName())
                        .createUserId(SecurityUtils.getUserId()).build();
                rejectedRecordService.save(rejectedRecord);

                if (certificationOrder.getCertificationExceptionStatus() == null || certificationOrder.getCertificationExceptionStatus() == 0) {
                    certificationOrder.setCertificationExceptionStatus(FLOW_REJECTED_STATUS);
                } else if (certificationOrder.getCertificationExceptionStatus() == 1) {
                    certificationOrder.setCertificationExceptionStatus(FLOW_OVERTIME_REJECTED_STATUS);
                }
                //工单更新检验记录状态
                certificationOrder.setCertificationStatus(FLOW_CURRENT_PROCESS).setCurrentProcess(INSPECTION_PROCESS);
                certificationOrder.setOrderExceptionStatus(FLOW_REJECTED_STATUS);

                Messagepush messagePush = getMessagePush(certificationOrder.getId(), ISSUE_REJECTED_MESSAGE, QualityControlMessageTopicEnum.INSPECTION_PROCESS, QualityControlMessageTypeEnum.MESSAGE_TYPE_QUALITY_ORDER);
                messagePush.setRouteIp(configUtils.getJyjlUrl());
                messagePush.setRouteIpApp(configUtils.getJyjlUrlapp());
                qualityControlMessageRecipientService.setMessageRecipient(messagePush, massaudit.getInitiator(), null);
                qualityControlMessageRecipientService.removeDB(rectifyOrderId, QualityControlMessageTopicEnum.ISSUE_PROCESS);
            } else {
                //生成下个审核人的部分信息
                Massaudit audit = new Massaudit();
                audit.setParentId(massaudit.getId())
                        .setInitiator(getUserId())
                        .setAuditDept(baseMapper.getDeptIdByUser(massaudit.getInitiator()))
                        .setAuditUser(massaudit.getInitiator())
                        .setCode(rectifyOrder.getCertificationNumber())
                        .setProcess(FLOW_PROCESS_ONE)
                        .setNum(massaudit.getNum() - 1)
                        .setAuditState(FLOW_AUDIT_DEFAULT);

                massauditService.save(audit);

                rectifyOrder.setIssueStatus(FLOW_CURRENT_PROCESS);

                massaudit.setNum(massaudit.getNum() - 1);

                //因为这是先清除所有整改下达的，所以先清除，再生成
                qualityControlMessageRecipientService.removeDB(rectifyOrderId, QualityControlMessageTopicEnum.ISSUE_PROCESS);

                Messagepush messagePush = getMessagePush(rectifyOrderId, ISSUE_REJECTED_MESSAGE, QualityControlMessageTopicEnum.ISSUE_PROCESS, QualityControlMessageTypeEnum.MESSAGE_TYPE_QUALITY_ORDER);
                messagePush.setRouteIp(configUtils.getZgxdUrl());
                messagePush.setRouteIpApp(configUtils.getZgxdUrlapp());
                qualityControlMessageRecipientService.setMessageRecipient(messagePush, massaudit.getInitiator(), null);
            }
            //记录驳回
            massaudit.setMsg(executeAdvice)
                    .setAuditUser(getUserId())
                    .setAuditDept(getUserDeptId())
                    .setAuditState(FLOW_AUDIT_REJECT)
                    .setParentId(massaudit.getId());
            massauditService.updateById(massaudit);
        }

        updateById(rectifyOrder);
        certificationOrderService.updateById(certificationOrder);
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateRectifyIssue(NewRectifyIssueDto dto, List<MultipartFile> fileList) {
        RectifyOrder rectifyOrder = dto.getRectifyOrder();
        String executeAdvice = dto.getExecuteAdvice();
        List<Massaudit> maudits = dto.getMaudits();

        Long rectifyOrderId = rectifyOrder.getId();
        String certificationNumber = rectifyOrder.getCertificationNumber();

        RectifyOrder order = getById(rectifyOrderId);
        //存储文件
        String fileIdsdb = order.getIssueFileIds();
        String fileIds = rectifyOrder.getIssueFileIds();
        StringBuilder files = saveFiles(fileList, fileIdsdb, fileIds);
        if (files == null && CollUtil.isNotEmpty(fileList)) {
            return false;
        }
        if (StringUtils.isEmpty(files)) {
            this.update(new UpdateWrapper<RectifyOrder>().lambda().set(RectifyOrder::getIssueFileIds, "").eq(RectifyOrder::getId, rectifyOrderId));
        }
        assert files != null;
        rectifyOrder.setIssueFileIds(files.toString());

        String issueStatus = rectifyOrder.getIssueStatus();
        //对应工单
        CertificationOrder certificationOrder = certificationOrderService.getOne(Wrappers.<CertificationOrder>lambdaQuery().eq(CertificationOrder::getCertificationNumber, certificationNumber));
        //获取最大审核等级
        Long maxAuditLevel = baseMapper.maxAuditLevel(certificationNumber, FLOW_PROCESS_ONE);
        //进入整改处置
        if (FLOW_NEXT.equals(issueStatus)) {
            Long maxId = baseMapper.getMaxId(MASSAUDIT_NAME);
            //如果传入集合不为空，说明是添加审核人
            if (maudits != null && !maudits.isEmpty()) {
                for (int i = 0; i < maudits.size(); i++) {
                    Massaudit massaudit = maudits.get(i);
                    if (i == 0) {
                        massaudit.setInitiator(certificationOrder.getIssuePersonId());
                    } else {
                        massaudit.setInitiator(maudits.get(i - 1).getAuditUser());
                    }
                    massaudit.setId(maxId);
                    maxId++;
                    massauditService.save(massaudit);
                }
                //获取添加的第一条审核人信息
                Massaudit massaudit = maudits.stream()
                        .sorted(Comparator.comparing(Massaudit::getNum))
                        .collect(Collectors.toList()).get(0);

                rectifyOrder.setIssueStatus(FLOW_CURRENT_PROCESS);

                qualityControlMessageRecipientService.removeDB(rectifyOrderId, QualityControlMessageTopicEnum.ISSUE_PROCESS);

                Messagepush messagePush = getMessagePush(rectifyOrderId, RECTIFY_RELEASE_MESSAGE, QualityControlMessageTopicEnum.ISSUE_PROCESS, QualityControlMessageTypeEnum.MESSAGE_TYPE_QUALITY_ORDER);
                messagePush.setRouteIp(configUtils.getZgxdUrl());
                messagePush.setRouteIpApp(configUtils.getZgxdUrlapp());
                qualityControlMessageRecipientService.setMessageRecipient(messagePush, massaudit.getAuditUser(), rectifyOrder.getIssueTimeLimit());

            } else {

                Long num = 0L;

                //获取未审核记录
                List<Massaudit> massauditList = massauditService.list(Wrappers.<Massaudit>lambdaQuery()
                        .eq(Massaudit::getCode, certificationNumber)
                        .eq(Massaudit::getProcess, FLOW_PROCESS_ONE).eq(Massaudit::getAuditState, FLOW_AUDIT_DEFAULT)
                        .orderByAsc(Massaudit::getNum));
                //如果有未审核记录，审核
                if (!massauditList.isEmpty()) {

                    Massaudit massaudit = massauditList.get(0);
                    massaudit.setMsg(executeAdvice);
                    massaudit.setAuditState(FLOW_AUDIT_THROUGH);
                    massaudit.setCreateTime(new Date());
                    massauditService.updateById(massaudit);

                    num = massaudit.getNum();

                    if (num < maxAuditLevel) {

                        rectifyOrder.setIssueStatus(FLOW_CURRENT_PROCESS);

                        //查询下一等级是否有未审核记录
                        List<Massaudit> nextAuditList = massauditService.list(Wrappers.<Massaudit>lambdaQuery()
                                .eq(Massaudit::getCode, certificationNumber)
                                .eq(Massaudit::getProcess, FLOW_PROCESS_ONE)
                                .eq(Massaudit::getAuditState, FLOW_AUDIT_DEFAULT)
                                .eq(Massaudit::getNum, num + 1));

                        Long auditUser;

                        //如果没有生成一条审核记录
                        if (nextAuditList.isEmpty()) {
                            Massaudit nextAudit = massauditService.list(Wrappers.<Massaudit>lambdaQuery()
                                    .eq(Massaudit::getCode, certificationNumber)
                                    .eq(Massaudit::getProcess, FLOW_PROCESS_ONE)
                                    .eq(Massaudit::getNum, num + 1)).get(0);

                            nextAudit.setMsg(null).setCreateTime(null).setAuditState(FLOW_AUDIT_DEFAULT);

                            massauditService.save(nextAudit);

                            auditUser = nextAudit.getAuditUser();
                        } else {
                            auditUser = nextAuditList.get(0).getAuditUser();
                        }
                        qualityControlMessageRecipientService.removeDB(rectifyOrderId, QualityControlMessageTopicEnum.ISSUE_PROCESS);

                        Messagepush messagePush = getMessagePush(rectifyOrderId, RECTIFY_RELEASE_MESSAGE, QualityControlMessageTopicEnum.ISSUE_PROCESS, QualityControlMessageTypeEnum.MESSAGE_TYPE_QUALITY_ORDER);
                        messagePush.setRouteIp(configUtils.getZgxdUrl());
                        messagePush.setRouteIpApp(configUtils.getZgxdUrlapp());
                        qualityControlMessageRecipientService.setMessageRecipient(messagePush, auditUser, rectifyOrder.getIssueTimeLimit());

                    }

                } else {
                    //没有未审核记录的话
                    List<Massaudit> mauditList = massauditService.list(Wrappers.<Massaudit>lambdaQuery()
                            .eq(Massaudit::getCode, certificationNumber)
                            .eq(Massaudit::getProcess, FLOW_PROCESS_ONE)
                            .orderByDesc(Massaudit::getCreateTime));

                    if (!mauditList.isEmpty()) {
                        Massaudit massaudit = mauditList.get(0);
                        //如果最后一条等级是1，并且是驳回的
                        if (massaudit.getNum() == 1 && massaudit.getAuditState().equals(FLOW_AUDIT_REJECT)) {
                            massaudit.setMsg(null);
                            massaudit.setCreateTime(null);
                            massaudit.setAuditState(FLOW_AUDIT_DEFAULT);

                            massauditService.save(massaudit);

                            qualityControlMessageRecipientService.removeDB(rectifyOrderId, QualityControlMessageTopicEnum.ISSUE_PROCESS);

                            Messagepush messagePush = getMessagePush(rectifyOrderId, RECTIFY_RELEASE_MESSAGE, QualityControlMessageTopicEnum.ISSUE_PROCESS, QualityControlMessageTypeEnum.MESSAGE_TYPE_QUALITY_ORDER);
                            messagePush.setRouteIp(configUtils.getZgxdUrl());
                            messagePush.setRouteIpApp(configUtils.getZgxdUrlapp());
                            qualityControlMessageRecipientService.setMessageRecipient(messagePush, massaudit.getAuditUser(), rectifyOrder.getIssueTimeLimit());

                        }
                    }
                }

                if (num.equals(maxAuditLevel)) {

                    //更新流程环节
                    certificationOrder.setCurrentProcess(DEAL_PROCESS);
                    //下个环节状态值设默认值
                    rectifyOrder.setRectifyStatus(FLOW_CURRENT_PROCESS);
                    if (order.getIssueTimeLimit().getTime() < System.currentTimeMillis()) {
                        if (order.getIssueExceptionStatus().equals(FLOW_REJECTED_STATUS)) {
                            rectifyOrder.setIssueExceptionStatus(FLOW_OVERTIME_REJECTED_STATUS);
                        } else {
                            rectifyOrder.setIssueExceptionStatus(FLOW_OVERTIME_STATUS);
                        }
                    }

                    qualityControlMessageRecipientService.removeDB(rectifyOrderId, QualityControlMessageTopicEnum.ISSUE_PROCESS);

                    Messagepush messagePush = getMessagePush(rectifyOrderId, RECTIFY_RESULT_MESSAGE, QualityControlMessageTopicEnum.RECTIFY_PROCESS, QualityControlMessageTypeEnum.MESSAGE_TYPE_QUALITY_ORDER);
                    messagePush.setRouteIp(configUtils.getZgczUrl());
                    messagePush.setRouteIpApp(configUtils.getZgczUrlapp());
                    qualityControlMessageRecipientService.setMessageRecipient(messagePush, order.getRectifyPersonId(), rectifyOrder.getResultTimeLimit());
                }
            }
        } else if (FLOW_REJECTED.equals(issueStatus)) {

            //获取未审核记录
            List<Massaudit> massauditList = massauditService.list(Wrappers.<Massaudit>lambdaQuery()
                    .eq(Massaudit::getCode, certificationNumber)
                    .eq(Massaudit::getProcess, FLOW_PROCESS_ONE).eq(Massaudit::getAuditState, FLOW_AUDIT_DEFAULT)
                    .orderByAsc(Massaudit::getNum));

            if (!massauditList.isEmpty()) {
                Massaudit massaudit = massauditList.get(0);
                massaudit.setMsg(executeAdvice);
                massaudit.setCreateTime(new Date());
                massaudit.setAuditState(FLOW_AUDIT_REJECT);
                massauditService.updateById(massaudit);

                rectifyOrder.setIssueStatus(FLOW_CURRENT_PROCESS);

                qualityControlMessageRecipientService.removeDB(rectifyOrderId, QualityControlMessageTopicEnum.ISSUE_PROCESS);

                Messagepush messagePush = getMessagePush(rectifyOrderId, RECTIFY_RELEASE_MESSAGE, QualityControlMessageTopicEnum.ISSUE_PROCESS, QualityControlMessageTypeEnum.MESSAGE_TYPE_QUALITY_ORDER);
                messagePush.setRouteIp(configUtils.getZgxdUrl());
                messagePush.setRouteIpApp(configUtils.getZgxdUrlapp());
                Long num = massaudit.getNum();

                if (num != 0) {
                    Long nowAuditUser = baseMapper.getNowAuditUser(certificationNumber, FLOW_PROCESS_ONE, num - 1);
                    Massaudit audit = new Massaudit();
                    audit.setNum(num - 1);
                    audit.setProcess(FLOW_PROCESS_ONE);
                    audit.setAuditState(FLOW_AUDIT_DEFAULT);
                    audit.setCode(massaudit.getCode());
                    audit.setInitiator(SecurityUtils.getUserId());
                    //发起人默认为上一级审核人
                    audit.setAuditUser(nowAuditUser != null ? nowAuditUser : order.getIssuePersonId());
                    audit.setAuditDept(baseMapper.getDeptIdByUser(massaudit.getInitiator()));

                    massauditService.save(audit);

                    qualityControlMessageRecipientService.setMessageRecipient(messagePush, audit.getAuditUser(), rectifyOrder.getResultTimeLimit());
                }/* else {
                    qualityControlMessageRecipientService.setMessageRecipient(messagePush, order.getIssuePersonId(), rectifyOrder.getResultTimeLimit());
                }*/
            }

            if (massauditList.isEmpty() || massauditList.get(0).getNum() == 0) {
                //当查询出未审核记录为空时说明再驳回就直接回到上一环节
                //增加驳回记录
                RejectedRecord rejectedRecord = RejectedRecord.builder()
                        .certificationNumber(certificationNumber)
                        .executeDept(rectifyOrder.getCertificationDept())
                        .executePerson(rectifyOrder.getCertificationPerson())
                        .executePersonId(rectifyOrder.getCertificationPersonId())
                        //.executeTime(rectifyOrder.getCertificationTime())
                        .executeTime(DateUtil.getCurrentTime())
                        .executeAdvice(executeAdvice)
                        .currentProcess(ISSUE_PROCESS)
                        .createTime(DateUtil.getCurrentTime())
                        .createUser(SecurityUtils.getUserName())
                        .createUserId(SecurityUtils.getUserId()).build();

                rejectedRecordService.save(rejectedRecord);

                if (certificationOrder.getCertificationExceptionStatus() == null || certificationOrder.getCertificationExceptionStatus() == 0) {
                    certificationOrder.setCertificationExceptionStatus(FLOW_REJECTED_STATUS);
                } else if (certificationOrder.getCertificationExceptionStatus() == 1) {
                    certificationOrder.setCertificationExceptionStatus(FLOW_OVERTIME_REJECTED_STATUS);
                }
                //工单更新检验记录状态
                certificationOrder.setCertificationStatus(FLOW_CURRENT_PROCESS).setCurrentProcess(INSPECTION_PROCESS);
                certificationOrder.setOrderExceptionStatus(FLOW_REJECTED_STATUS);

                qualityControlMessageRecipientService.removeDB(rectifyOrderId, QualityControlMessageTopicEnum.ISSUE_PROCESS);

                Messagepush messagePush = getMessagePush(certificationOrder.getId(), ISSUE_REJECTED_MESSAGE, QualityControlMessageTopicEnum.INSPECTION_PROCESS, QualityControlMessageTypeEnum.MESSAGE_TYPE_QUALITY_ORDER);
                messagePush.setRouteIp(configUtils.getJyjlUrl());
                messagePush.setRouteIpApp(configUtils.getJyjlUrlapp());
                qualityControlMessageRecipientService.setMessageRecipient(messagePush, certificationOrder.getCertificationPersonId(), null);
            }
        }

        updateById(rectifyOrder);
        certificationOrderService.updateById(certificationOrder);

        return true;
    }

    @Override
    public IPage<RectifyOrderListVo> getRectifyIssueList(ReportOrderDto orderDto, Page<RectifyOrder> page) {
        Page<RectifyOrderListVo> oPage = null;
        if (orderDto.getType() == null || orderDto.getType().equals(0)) {
            oPage = this.baseMapper.loadRectifyIssueList(orderDto, getUserId(), null, ratio, page);
        } else if (orderDto.getType().equals(1)) {
            oPage = this.baseMapper.loadRectifyIssueList(orderDto, null, getUserDeptId(), ratio, page);
        }
        fillDeptName(oPage);

        if (oPage != null && oPage.getTotal() != 0) {
            for (RectifyOrderListVo record : oPage.getRecords()) {

                String certificationNumber = record.getCertificationNumber();

                List<Massaudit> auditInfo = massauditService.list(Wrappers.<Massaudit>lambdaQuery()
                        .eq(Massaudit::getCode, certificationNumber).eq(Massaudit::getProcess, FLOW_PROCESS_ONE)
                        .eq(Massaudit::getAuditState, FLOW_AUDIT_DEFAULT)
                        .orderByAsc(Massaudit::getNum));

                if (!auditInfo.isEmpty()) {
                    record.setAuditId(auditInfo.get(0).getAuditUser());
                } else {
                    record.setAuditId(baseMapper.getAuditUser(certificationNumber, FLOW_PROCESS_ONE));
                }

                Long nowLevel = baseMapper.getNowLevel(certificationNumber, FLOW_PROCESS_ONE);

                record.setAuditLevel(nowLevel == null ? 0 : nowLevel);

                /*List<Massaudit> auditInfo = massauditService.list(Wrappers.<Massaudit>lambdaQuery()
                        .eq(Massaudit::getCode, record.getCertificationNumber()).eq(Massaudit::getProcess, FLOW_PROCESS_ONE)
                        .isNotNull(Massaudit::getCreateTime)
                        .orderByDesc(Massaudit::getCreateTime));

                if (!auditInfo.isEmpty()) {
                    Massaudit massaudit = auditInfo.get(0);

                    Long num = massaudit.getNum();

                    List<Massaudit> nextAuditList = massauditService.list(Wrappers.<Massaudit>lambdaQuery()
                            .eq(Massaudit::getCode, record.getCertificationNumber()).eq(Massaudit::getProcess, FLOW_PROCESS_ONE)
                            .eq(Massaudit::getAuditState, FLOW_AUDIT_DEFAULT)
                            .eq(Massaudit::getNum, massaudit.getAuditState().equals(FLOW_AUDIT_REJECT) ? num - 1 : num + 1));

                    if (nextAuditList.isEmpty()) {
                        record.setAuditId(baseMapper.getAuditUser(record.getCertificationNumber(), FLOW_PROCESS_ONE));
                    } else {
                        record.setAuditId(nextAuditList.get(0).getAuditUser());
                    }
                } else {

                    List<Massaudit> auditList = massauditService.list(Wrappers.<Massaudit>lambdaQuery()
                            .eq(Massaudit::getCode, record.getCertificationNumber()).eq(Massaudit::getProcess, FLOW_PROCESS_ONE)
                            .eq(Massaudit::getAuditState, FLOW_AUDIT_DEFAULT)
                            .orderByAsc(Massaudit::getNum));

                    if (auditList.isEmpty()) {
                        record.setAuditId(baseMapper.getAuditUser(record.getCertificationNumber(), FLOW_PROCESS_ONE));
                    } else {
                        record.setAuditId(auditList.get(0).getAuditUser());
                    }
                }*/
            }
        }

        return oPage;
    }

    private void fillDeptName(Page<RectifyOrderListVo> oPage) {
        Map<Long, String> deptMap = new HashMap<>();
        if (oPage != null && oPage.getRecords() != null) {
            for (RectifyOrderListVo vo : oPage.getRecords()) {
                String currentProcess = vo.getCurrentProcess();
                vo.setCurrentProcessName(getProcessName(currentProcess));
                vo.setAuditDeptName(deptName(deptMap, vo.getAuditDept()));
                vo.setRectifyDeptName(deptName(deptMap, vo.getRectifyDept()));
                vo.setIssueDeptName(deptName(deptMap, vo.getIssueDept()));
                vo.setValidateDeptName(deptName(deptMap, vo.getValidateDept()));
                vo.setVerifyDeptName(deptName(deptMap, vo.getVerifyDept()));
                vo.setCertificationDeptName(deptName(deptMap, vo.getCertificationDept()));
                String metertype = vo.getMeterType();
                if (StringUtils.isNotEmpty(metertype)) {
                    if (!metertype.toUpperCase().contains("DN")) {
                        metertype = "DN" + metertype;
                    }
                }
                vo.setMeterType(metertype);
            }
        }
    }

    private String getProcessName(String currentProcess) {
        return StringUtils.isEmpty(currentProcess) || "0".equals(currentProcess) ? "检验记录" : "1".equals(currentProcess) ? "整改下达" : "2".equals(currentProcess) ? "整改处置" : "3".equals(currentProcess) ? "整改审核" : "4".equals(currentProcess) ? "整改验证" : "5".equals(currentProcess) ? "验证审核" : "其它";
    }

    private String deptName(Map<Long, String> deptMap, String deptkey) {
        if (StringUtils.isNotEmpty(deptkey)) {
            Long key = Long.parseLong(deptkey);
            if (deptMap.containsKey(key)) {
                return deptMap.get(key);
            } else {
                ResultRespone<Department> rr = departmentClient.getById(key);
                if (rr == null || rr.getResult() == null) {
                    deptMap.put(key, "");
                }
                String deptName = rr.getResult().getName();
                deptMap.put(key, deptName);
                return deptName;
            }
        }
        return null;
    }

    @Override
    public RectifyIssueOrderVO_D getRectifyIssueDetail(Long id) {
        RectifyIssueOrderVO_D vo = getVO(getById(id), RectifyIssueOrderVO_D.class);

        String issueDept = vo.getIssueDept();

        Boolean flag1 = isNotNull(issueDept);
        if (flag1) {
            vo.setIssueDept(getDeptName(issueDept));
        }
        return vo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateRectifyResult(RectifyOrder rectifyOrder, List<MultipartFile> fileList, String executeAdvice, String transferIdea) {
        Long rectifyOrderId = rectifyOrder.getId();

        //存储文件
        RectifyOrder order = getById(rectifyOrderId);
        if (order == null) {
            return false;
        }
        String fileIdsdb = order.getRectifyFileIds();
        String fileIds = rectifyOrder.getRectifyFileIds();
        StringBuilder files = saveFiles(fileList, fileIdsdb, fileIds);
        if (files == null && CollUtil.isNotEmpty(fileList)) {
            return false;
        }
        if (StringUtils.isEmpty(files)) {
            this.update(new UpdateWrapper<RectifyOrder>().lambda().set(RectifyOrder::getRectifyFileIds, "").eq(RectifyOrder::getId, rectifyOrder.getId()));
        }
        rectifyOrder.setRectifyFileIds(files.toString());

        Boolean flag2 = true;
        Boolean flag3 = true;

        String rectifyStatus = rectifyOrder.getRectifyStatus();

        CertificationOrder certificationOrder = certificationOrderService.getOne(Wrappers.<CertificationOrder>lambdaQuery().eq(CertificationOrder::getCertificationNumber, rectifyOrder.getCertificationNumber()));

        //进入整改审核
        if (FLOW_NEXT.equals(rectifyStatus)) {
            certificationOrder.setCurrentProcess(AUDIT_PROCESS);
            flag2 = certificationOrderService.updateById(certificationOrder);

            rectifyOrder.setAuditStatus(FLOW_CURRENT_PROCESS);
            if (order.getResultTimeLimit().getTime() < System.currentTimeMillis()) {
                if (order.getRectifyExceptionStatus().equals(FLOW_REJECTED_STATUS)) {
                    order.setRectifyExceptionStatus(FLOW_OVERTIME_REJECTED_STATUS);
                } else {
                    order.setRectifyExceptionStatus(FLOW_OVERTIME_STATUS);
                }
            }
            Messagepush messagePush = getMessagePush(rectifyOrderId, RECTIFY_AUDIT_MESSAGE, QualityControlMessageTopicEnum.AUDIT_PROCESS, QualityControlMessageTypeEnum.MESSAGE_TYPE_QUALITY_ORDER);
            messagePush.setRouteIp(configUtils.getZgshUrl());
            messagePush.setRouteIpApp(configUtils.getZgshUrlapp());
            qualityControlMessageRecipientService.setMessageRecipient(messagePush, rectifyOrder.getAuditPersonId(), rectifyOrder.getResultTimeLimit());
        } else if (FLOW_TRANSFER.equals(rectifyStatus)) {
            RectifyOrder ro = getById(rectifyOrderId);
            //本环节状态值重设为默认值
            rectifyOrder.setRectifyStatus(FLOW_CURRENT_PROCESS);
            ZlTransfer zp = ZlTransfer.builder().gdbh(rectifyOrder.getCertificationNumber())
                    .clbm(rectifyOrder.getRectifyDept())
                    .zpry(ro.getRectifyPerson())
                    .zpryid(ro.getRectifyPersonId())
                    .zpsj(DateUtil.getCurrentTime())
                    .zpyj(transferIdea)
                    .lcjd(DEAL_PROCESS)
                    .jsry(rectifyOrder.getRectifyPerson())
                    .jsryid(rectifyOrder.getRectifyPersonId())
                    .createTime(DateUtil.getCurrentTime())
                    .createUser(SecurityUtils.getUserId())
                    .build();
            IZlTransferService.save(zp);
            if (StringUtils.isNotEmpty(rectifyOrder.getRectifyDept())) {
                certificationOrder.setRectifyDept(rectifyOrder.getRectifyDept());
            }
            if (StringUtils.isNotEmpty(rectifyOrder.getRectifyPerson())) {
                certificationOrder.setRectifyPerson(rectifyOrder.getRectifyPerson());
            }
            if (rectifyOrder.getRectifyPersonId() != null) {
                certificationOrder.setRectifyPersonId(rectifyOrder.getRectifyPersonId());
            }
            certificationOrderService.updateById(certificationOrder);
            Messagepush messagePush = getMessagePush(rectifyOrderId, RECTIFY_RESULT_MESSAGE, QualityControlMessageTopicEnum.RECTIFY_PROCESS, QualityControlMessageTypeEnum.MESSAGE_TYPE_QUALITY_ORDER);
            messagePush.setRouteIp(configUtils.getZgczUrl());
            messagePush.setRouteIpApp(configUtils.getZgczUrlapp());
            qualityControlMessageRecipientService.setMessageRecipient(messagePush, rectifyOrder.getRectifyPersonId(), rectifyOrder.getResultTimeLimit());
        } else if (FLOW_REJECTED.equals(rectifyStatus)) {
            RejectedRecord rejectedRecord = RejectedRecord.builder()
                    .certificationNumber(rectifyOrder.getCertificationNumber())
                    .executeDept(rectifyOrder.getIssueDept())
                    .executePerson(rectifyOrder.getIssuePerson())
                    .executePersonId(rectifyOrder.getIssuePersonId())
                    //.executeTime(rectifyOrder.getIssueTime())
                    .executeTime(DateUtil.getCurrentTime())
                    .executeAdvice(executeAdvice)
                    .currentProcess(DEAL_PROCESS)
                    .createTime(DateUtil.getCurrentTime())
                    .createUser(SecurityUtils.getUserName())
                    .createUserId(SecurityUtils.getUserId()).build();

            flag3 = rejectedRecordService.save(rejectedRecord);

//            第二版废弃代码
//            List<Massaudit> auditInfoList = massauditService.list(Wrappers.<Massaudit>lambdaQuery()
//                    .eq(Massaudit::getCode, rectifyOrder.getCertificationNumber())
//                    .eq(Massaudit::getAuditState, FLOW_AUDIT_THROUGH)
//                    .eq(Massaudit::getProcess, FLOW_PROCESS_ONE)
//                    .orderByDesc(Massaudit::getCreateTime));
//
//            Massaudit massaudit = auditInfoList.get(0);
//            //默认审核信息
//            Massaudit audit = new Massaudit();
//            audit.setNum(massaudit.getNum())
//                    .setInitiator(massaudit.getAuditUser())
//                    .setCode(rectifyOrder.getCertificationNumber())
//                    .setMsg(executeAdvice)
//                    .setAuditUser(massaudit.getInitiator())
//                    .setAuditDept(baseMapper.getDeptIdByUser(massaudit.getInitiator()))
//                    .setProcess(FLOW_PROCESS_ONE)
//                    .setFileIds(massaudit.getFileIds())
//                    .setAuditState(FLOW_AUDIT_DEFAULT);
//
//            massauditService.save(audit);


            //第三版代码

            Long userId;

            Long maxAuditLevel = baseMapper.maxAuditLevel(rectifyOrder.getCertificationNumber(), FLOW_PROCESS_ONE);
            List<Massaudit> maxAuditList = massauditService.list(Wrappers.<Massaudit>lambdaQuery()
                    .eq(Massaudit::getCode, rectifyOrder.getCertificationNumber())
                    .eq(Massaudit::getProcess, FLOW_PROCESS_ONE)
                    .eq(Massaudit::getNum, maxAuditLevel));

            if (!maxAuditList.isEmpty()) {
                Massaudit massaudit = maxAuditList.get(0);
                massaudit.setMsg(null).setCreateTime(null).setAuditState(FLOW_AUDIT_DEFAULT);
                massauditService.save(massaudit);

                userId = massaudit.getAuditUser();
            } else {
                userId = certificationOrder.getIssuePersonId();
            }
            //结束


            if (rectifyOrder.getIssueExceptionStatus() == null || rectifyOrder.getIssueExceptionStatus() == 0) {
                rectifyOrder.setIssueExceptionStatus(FLOW_REJECTED_STATUS);
            } else if (rectifyOrder.getIssueExceptionStatus() == 1) {
                rectifyOrder.setIssueExceptionStatus(FLOW_OVERTIME_REJECTED_STATUS);
            }
            rectifyOrder.setIssueStatus(FLOW_CURRENT_PROCESS);
            certificationOrder.setCurrentProcess(ISSUE_PROCESS);
            certificationOrder.setOrderExceptionStatus(FLOW_REJECTED_STATUS);
            flag2 = certificationOrderService.updateById(certificationOrder);
            Messagepush messagePush = getMessagePush(rectifyOrderId, RECTIFY_REJECTED_MESSAGE, QualityControlMessageTopicEnum.ISSUE_PROCESS, QualityControlMessageTypeEnum.MESSAGE_TYPE_QUALITY_ORDER);
            messagePush.setRouteIp(configUtils.getZgxdUrl());
            messagePush.setRouteIpApp(configUtils.getZgxdUrlapp());
            qualityControlMessageRecipientService.setMessageRecipient(messagePush, userId, rectifyOrder.getResultTimeLimit());
        }
        Boolean flag1 = updateById(rectifyOrder);
        if (!FLOW_CURRENT_PROCESS.equals(rectifyStatus)) {
            qualityControlMessageRecipientService.removeDB(rectifyOrderId, QualityControlMessageTopicEnum.RECTIFY_PROCESS);
        }
        return flag1 && flag2 && flag3;
    }

    /**
     * 存储文件
     *
     * @param fileList
     * @param fileIdsdb
     * @param fileIds
     * @return
     */
    private StringBuilder saveFiles(List<MultipartFile> fileList, String fileIdsdb, String fileIds) {
        StringBuilder fileIdList = null;
        if (CollectionUtils.isNotEmpty(fileList)) {
            fileIdList = fileService.saveFileList(fileList, certificationOrderFilePath, RECTIFY_ORDER_TABLE_NAME);
            if (fileIdList == null || fileIdList.length() == 0) {
                return null;
            }
        }
        fileIds = delRepeat(fileIds);
        String fs = fileIds;
        if (StringUtils.isNotEmpty(fileIdsdb) && !fileIdsdb.equals(fileIds)) {
            List<Long> removeFileId = new ArrayList<>();
            if (StringUtils.isEmpty(fileIds)) {
                removeFileId = Arrays.stream(fileIdsdb.split(CSV)).map(s -> Long.parseLong(s.trim()))
                        .collect(Collectors.toList());
            } else {
                removeFileId = Arrays.stream(fileIdsdb.split(CSV)).filter(st -> !fs.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.isNotEmpty(fileIds)) {
                files.append(fileIds);
            } else if (StringUtils.isNotEmpty(fileIdList)) {
                files.append(fileIdList);
            }
        } else {
            files.append(fileIds).append(CSV).append(fileIdList);
        }
        return files;
    }


    private String delRepeat(String str) {
        StringBuilder sb = new StringBuilder();
        if (StringUtils.isNotEmpty(str)) {
            List<Long> removeFileId = Arrays.stream(str.split(CSV)).filter(s -> StringUtils.isNotEmpty(s)).map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());
            for (Long l : removeFileId) {
                sb.append(l).append(",");
            }
            sb.delete(sb.length() - 1, sb.length());
            return sb.toString();
        }
        return null;
    }

    @Override
    public IPage<RectifyOrderListVo> getRectifyResultList(ReportOrderDto dto, Page<RectifyOrder> page) {
        Page<RectifyOrderListVo> orderVOLPage = null;
        if (dto.getType() == null || dto.getType().equals(0)) {
            orderVOLPage = this.baseMapper.loadRectifyResultList(dto, getUserId(), null, ratio, page);
        } else if (dto.getType().equals(1)) {
            orderVOLPage = this.baseMapper.loadRectifyResultList(dto, null, getUserDeptId(), ratio, page);
        }
        fillDeptName(orderVOLPage);
        return orderVOLPage;

    }

    @Override
    public RectifyResultOrderVO_D getRectifyResultDetail(Long id) {
        RectifyResultOrderVO_D vo = getVO(getById(id), RectifyResultOrderVO_D.class);
        String rectifyDept = vo.getRectifyDept();
        Boolean flag2 = isNotNull(rectifyDept);
        if (flag2) {
            vo.setRectifyDept(getDeptName(rectifyDept));
        }
        return vo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateRectifyAudit(RectifyOrder rectifyOrder, String executeAdvice) {

        Boolean flag3 = true;

        String auditStatus = rectifyOrder.getAuditStatus();

        CertificationOrder certificationOrder = certificationOrderService.getOne(Wrappers.<CertificationOrder>lambdaQuery().eq(CertificationOrder::getCertificationNumber, rectifyOrder.getCertificationNumber()));
        RectifyOrder order = this.getById(rectifyOrder.getId());
        if (order == null) {
            return false;
        }
        //进入验证环节
        if (FLOW_NEXT.equals(auditStatus)) {
            certificationOrder.setCurrentProcess(VERIFY_PROCESS);

            //由检验记录人进行整改验证
            rectifyOrder.setVerifyPersonId(order.getCertificationPersonId())
                    .setVerifyDept(order.getCertificationDept())
                    .setVerifyPerson(order.getCertificationPerson())
                    .setVerifyStatus(FLOW_CURRENT_PROCESS);
            Messagepush messagePush = getMessagePush(rectifyOrder.getId(), RECTIFY_VERIFY_MESSAGE, QualityControlMessageTopicEnum.VERIFY_PROCESS, QualityControlMessageTypeEnum.MESSAGE_TYPE_QUALITY_ORDER);
            messagePush.setRouteIp(configUtils.getZgyzUrl());
            messagePush.setRouteIpApp(configUtils.getZgyzUrlapp());
            qualityControlMessageRecipientService.setMessageRecipient(messagePush, order.getCertificationPersonId(), null);
        } else if (FLOW_REJECTED.equals(auditStatus)) {
            RejectedRecord rejectedRecord = RejectedRecord.builder()
                    .certificationNumber(rectifyOrder.getCertificationNumber())
                    .executeDept(rectifyOrder.getRectifyDept())
                    .executePerson(rectifyOrder.getRectifyPerson())
                    .executePersonId(rectifyOrder.getRectifyPersonId())
                    .executeTime(rectifyOrder.getRectifyTime())
                    .executeAdvice(executeAdvice)
                    .currentProcess(AUDIT_PROCESS)
                    .createTime(DateUtil.getCurrentTime())
                    .createUser(SecurityUtils.getUserName())
                    .createUserId(SecurityUtils.getUserId()).build();

            flag3 = rejectedRecordService.save(rejectedRecord);

            rectifyOrder.setRectifyStatus(FLOW_CURRENT_PROCESS);
            if (rectifyOrder.getRectifyExceptionStatus() == null || rectifyOrder.getRectifyExceptionStatus() == 0) {
                rectifyOrder.setRectifyExceptionStatus(FLOW_REJECTED_STATUS);
            } else if (rectifyOrder.getRectifyExceptionStatus() == 1) {
                rectifyOrder.setRectifyExceptionStatus(FLOW_OVERTIME_REJECTED_STATUS);
            }
            certificationOrder.setCurrentProcess(DEAL_PROCESS);
            certificationOrder.setOrderExceptionStatus(FLOW_REJECTED_STATUS);
            Messagepush messagePush = getMessagePush(rectifyOrder.getId(), AUDIT_REJECTED_MESSAGE, QualityControlMessageTopicEnum.RECTIFY_PROCESS, QualityControlMessageTypeEnum.MESSAGE_TYPE_QUALITY_ORDER);
            messagePush.setRouteIp(configUtils.getZgczUrl());
            messagePush.setRouteIpApp(configUtils.getZgczUrlapp());
            qualityControlMessageRecipientService.setMessageRecipient(messagePush, order.getRectifyPersonId(), rectifyOrder.getResultTimeLimit());
        }
        Boolean flag1 = updateById(rectifyOrder);
        Boolean flag2 = certificationOrderService.updateById(certificationOrder);
        if (!FLOW_CURRENT_PROCESS.equals(auditStatus)) {
            qualityControlMessageRecipientService.removeDB(rectifyOrder.getId(), QualityControlMessageTopicEnum.AUDIT_PROCESS);
        }
        return flag1 && flag2 && flag3;
    }

    @Override
    public IPage<RectifyOrderListVo> getRectifyAuditList(ReportOrderDto dto, Page page) {
        Page<RectifyOrderListVo> orderVOLPage = null;
        if (dto.getType() == null || dto.getType().equals(0)) {
            orderVOLPage = this.baseMapper.loadRectifyAuditList(dto, getUserId(), null, page);
        } else if (dto.getType().equals(1)) {
            orderVOLPage = this.baseMapper.loadRectifyAuditList(dto, null, getUserDeptId(), page);
        }
        fillDeptName(orderVOLPage);
        return orderVOLPage;
    }

    @Override
    public RectifyAuditOrderVO_D getRectifyAuditDetail(Long id) {
        RectifyAuditOrderVO_D vo = getVO(getById(id), RectifyAuditOrderVO_D.class);
        String auditDept = vo.getAuditDept();
        Boolean flag1 = isNotNull(auditDept);
        if (flag1) {
            vo.setAuditDept(getDeptName(auditDept));
        }
        return vo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateRectifyVerify(RectifyOrder rectifyOrder, String executeAdvice) {

        Boolean flag2 = true;
        RectifyOrder order = this.getById(rectifyOrder.getId());
        if (order == null) {
            return false;
        }
        String verifyStatus = rectifyOrder.getVerifyStatus();

        CertificationOrder certificationOrder = certificationOrderService.getOne(Wrappers.<CertificationOrder>lambdaQuery().eq(CertificationOrder::getCertificationNumber, rectifyOrder.getCertificationNumber()));

        if (FLOW_NEXT.equals(verifyStatus)) {
            certificationOrder.setCurrentProcess(VALIDATE_PROCESS);

            rectifyOrder.setValidateStatus(FLOW_CURRENT_PROCESS);
            //VERIFY_TIME_LIMIT) OR VERIFY_EXCEPTION_STATUS =1 OR VERIFY_EXCEPTION_STATUS
            if (order.getVerifyTimeLimit().getTime() < System.currentTimeMillis()) {
                if (order.getVerifyExceptionStatus().equals(FLOW_REJECTED_STATUS)) {
                    order.setVerifyExceptionStatus(FLOW_OVERTIME_REJECTED_STATUS);
                } else {
                    order.setVerifyExceptionStatus(FLOW_OVERTIME_STATUS);
                }
            }
            //第二版废弃代码
//            Massaudit audit = massauditService.getOne(Wrappers.<Massaudit>lambdaQuery()
//                    .eq(Massaudit::getAuditState, FLOW_AUDIT_DEFAULT)
//                    .eq(Massaudit::getNum, 1)
//                    .eq(Massaudit::getCode, rectifyOrder.getCertificationNumber()));
//
//            if (audit == null) {
//                //添加验证审核部分信息
//                Massaudit massaudit = new Massaudit();
//                massaudit.setAuditDept(baseMapper.getDeptIdByUser(rectifyOrder.getValidatePersonId()))
//                        .setNum(1L)
//                        .setProcess(FLOW_PROCESS_TWO)
//                        .setInitiator(getUserId())
//                        .setAuditState(FLOW_AUDIT_DEFAULT)
//                        .setAuditUser(rectifyOrder.getValidatePersonId())
//                        .setCode(rectifyOrder.getCertificationNumber());
//
//                massauditService.save(massaudit);
//            }

            //第三版代码
            List<Massaudit> lastAuditList = massauditService.list(Wrappers.<Massaudit>lambdaQuery().eq(Massaudit::getNum, 0)
                    .eq(Massaudit::getProcess, FLOW_PROCESS_TWO).eq(Massaudit::getCode, rectifyOrder.getCertificationNumber()));

            if (!lastAuditList.isEmpty()) {
                Massaudit massaudit = lastAuditList.get(0);
                massaudit.setAuditState(FLOW_AUDIT_DEFAULT).setCreateTime(null).setMsg(null).setInitiator(SecurityUtils.getUserId());
                massauditService.save(massaudit);
            }

            Messagepush messagePush = getMessagePush(rectifyOrder.getId(), VERIFICATION_EXAMINE_MESSAGE, QualityControlMessageTopicEnum.VALIDATE_PROCESS, QualityControlMessageTypeEnum.MESSAGE_TYPE_QUALITY_ORDER);
            messagePush.setRouteIp(configUtils.getYzshUrl());
            messagePush.setRouteIpApp(configUtils.getYzshUrlapp());
            qualityControlMessageRecipientService.setMessageRecipient(messagePush, rectifyOrder.getValidatePersonId(), null);
        } else if (FLOW_REJECTED.equals(verifyStatus)) {
            RejectedRecord rejectedRecord = RejectedRecord.builder()
                    .certificationNumber(rectifyOrder.getCertificationNumber())
                    .executeDept(rectifyOrder.getAuditDept())
                    .executePerson(rectifyOrder.getAuditPerson())
                    .executePersonId(rectifyOrder.getAuditPersonId())
                    .executeTime(rectifyOrder.getAuditTime())
                    .executeAdvice(executeAdvice)
                    .currentProcess(VERIFY_PROCESS)
                    .createTime(DateUtil.getCurrentTime())
                    .createUser(SecurityUtils.getUserName())
                    .createUserId(SecurityUtils.getUserId()).build();

            flag2 = rejectedRecordService.save(rejectedRecord);
            //人员冲突置空
            rectifyOrder.setAuditPerson(null);
            rectifyOrder.setAuditPersonId(null);
            rectifyOrder.setAuditStatus(FLOW_CURRENT_PROCESS);
            if (rectifyOrder.getAuditExceptionStatus() == null || rectifyOrder.getAuditExceptionStatus() == 0) {
                rectifyOrder.setAuditExceptionStatus(FLOW_REJECTED_STATUS);
            } else if (rectifyOrder.getAuditExceptionStatus() == 1) {
                rectifyOrder.setAuditExceptionStatus(FLOW_OVERTIME_REJECTED_STATUS);
            }
            certificationOrder.setCurrentProcess(AUDIT_PROCESS);
            certificationOrder.setOrderExceptionStatus(FLOW_REJECTED_STATUS);
            Messagepush messagePush = getMessagePush(rectifyOrder.getId(), AUDIT_REJECTED_MESSAGE, QualityControlMessageTopicEnum.AUDIT_PROCESS, QualityControlMessageTypeEnum.MESSAGE_TYPE_QUALITY_ORDER);
            messagePush.setRouteIp(configUtils.getZgshUrl());
            messagePush.setRouteIpApp(configUtils.getZgshUrlapp());
            qualityControlMessageRecipientService.setMessageRecipient(messagePush, order.getAuditPersonId(), null);
        }
        Boolean flag1 = updateById(rectifyOrder);
        Boolean flag3 = certificationOrderService.updateById(certificationOrder);
        if (!FLOW_CURRENT_PROCESS.equals(verifyStatus)) {
            qualityControlMessageRecipientService.removeDB(rectifyOrder.getId(), QualityControlMessageTopicEnum.VERIFY_PROCESS);
        }
        return flag1 && flag2 && flag3;
    }

    @Override
    public IPage<RectifyOrderListVo> getRectifyVerifyList(ReportOrderDto dto, Page page) {
        Page<RectifyOrderListVo> orderVOLPage = null;
        if (dto.getType() == null || dto.getType().equals(0)) {
            orderVOLPage = this.baseMapper.loadRectifyVerifyList(dto, getUserId(), null, ratio, page);
        } else if (dto.getType().equals(1)) {
            orderVOLPage = this.baseMapper.loadRectifyVerifyList(dto, null, getUserDeptId(), ratio, page);
        }
        fillDeptName(orderVOLPage);
        return orderVOLPage;

    }

    @Override
    public RectifyVerifyOrderVO_D getRectifyVerifyDetail(Long id) {
        RectifyVerifyOrderVO_D vo = getVO(getById(id), RectifyVerifyOrderVO_D.class);
        String verifyDept = vo.getVerifyDept();
        Boolean flag1 = isNotNull(verifyDept);
        if (flag1) {
            vo.setVerifyDept(getDeptName(verifyDept));
        }
        return vo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateRectifyValidate(RectifyOrder rectifyOrder, String executeAdvice) {

        Boolean flag2 = true;
        RectifyOrder order = this.getById(rectifyOrder.getId());
        if (order == null) {
            return false;
        }
        String validateStatus = rectifyOrder.getValidateStatus();
        Long rectifyOrderId = rectifyOrder.getId();
        String certificationNumber = rectifyOrder.getCertificationNumber();

        CertificationOrder certificationOrder = certificationOrderService.getOne(Wrappers.<CertificationOrder>lambdaQuery().eq(CertificationOrder::getCertificationNumber, certificationNumber));

        if (FLOW_FINISHED.equals(validateStatus)) {
            //推送消息给工单上报人、检验记录人
            Messagepush messagePush = getMessagePush(rectifyOrderId, PROCESS_FINISHED_MESSAGE, QualityControlMessageTopicEnum.VALIDATE_PROCESS, QualityControlMessageTypeEnum.MESSAGE_TYPE_QUALITY_ORDER);
            messagePush.setRouteIp(configUtils.getYwjkUrl());
            qualityControlMessageRecipientService.setMessageRecipient(messagePush, rectifyOrder.getDispatchPersonId());
            qualityControlMessageRecipientService.setMessageRecipient(messagePush, rectifyOrder.getCertificationPersonId());

            RectifyOrder rectifyOrderById = getById(rectifyOrder.getId());

            //工单完成时作一次超时和驳回异常判断
            Map<String, Integer> statusMap = getAllStatus(certificationOrder, rectifyOrderById, certificationNumber);

            rectifyOrder.setIssueExceptionStatus(statusMap.get(ISSUE_EXCEPTION_STATUS))
                    .setRectifyExceptionStatus(statusMap.get(RECTIFY_EXCEPTION_STATUS))
                    .setAuditExceptionStatus(statusMap.get(AUDIT_EXCEPTION_STATUS))
                    .setVerifyExceptionStatus(statusMap.get(VERIFY_EXCEPTION_STATUS))
                    .setValidateExceptionStatus(statusMap.get(VALIDATE_EXCEPTION_STATUS));

            certificationOrder.setCertificationExceptionStatus(statusMap.get(CERTIFICATION_EXCEPTION_STATUS))
                    .setOrderExceptionStatus(statusMap.get(ORDER_EXCEPTION_STATUS));
        } else if (FLOW_REJECTED.equals(validateStatus)) {
            RejectedRecord rejectedRecord = RejectedRecord.builder()
                    .certificationNumber(certificationNumber)
                    .executeDept(rectifyOrder.getVerifyDept())
                    .executePerson(rectifyOrder.getVerifyPerson())
                    .executePersonId(rectifyOrder.getVerifyPersonId())
                    .executeTime(rectifyOrder.getVerifyTime())
                    .executeAdvice(executeAdvice)
                    .currentProcess(VALIDATE_PROCESS)
                    .createTime(DateUtil.getCurrentTime())
                    .createUser(SecurityUtils.getUserName())
                    .createUserId(SecurityUtils.getUserId()).build();

            flag2 = rejectedRecordService.save(rejectedRecord);
            if (rectifyOrder.getVerifyExceptionStatus() == null || rectifyOrder.getVerifyExceptionStatus() == 0) {
                rectifyOrder.setVerifyExceptionStatus(FLOW_REJECTED_STATUS);
            } else if (rectifyOrder.getVerifyExceptionStatus() == 1) {
                rectifyOrder.setVerifyExceptionStatus(FLOW_REJECTED_STATUS + 1);
            }
            rectifyOrder.setVerifyStatus(FLOW_CURRENT_PROCESS);
            certificationOrder.setCurrentProcess(VERIFY_PROCESS);
            certificationOrder.setOrderExceptionStatus(FLOW_REJECTED_STATUS);
            Messagepush messagePush = getMessagePush(rectifyOrderId, VERIFY_REJECTED_MESSAGE, QualityControlMessageTopicEnum.VERIFY_PROCESS, QualityControlMessageTypeEnum.MESSAGE_TYPE_QUALITY_ORDER);
            messagePush.setRouteIp(configUtils.getZgyzUrl());
            messagePush.setRouteIpApp(configUtils.getZgyzUrlapp());
            qualityControlMessageRecipientService.setMessageRecipient(messagePush, order.getVerifyPersonId(), null);
        }
        Boolean flag1 = updateById(rectifyOrder);
        Boolean flag3 = certificationOrderService.updateById(certificationOrder);
        if (!FLOW_CURRENT_PROCESS.equals(validateStatus)) {
            qualityControlMessageRecipientService.removeDB(rectifyOrderId, QualityControlMessageTopicEnum.VALIDATE_PROCESS);
        }
        if (FLOW_FINISHED.equals(validateStatus) && IS_CB.equals(certificationOrder.getIsCb())) {
            certificationOrderService.updateReadmeterhis(certificationOrder.getClientNumber(), certificationOrder.getYearMonth());
        }
        return flag1 && flag2 && flag3;
    }

    @Override
    public Boolean updateRectifyValidate(RectifyValidateDto dto) {
        RectifyOrder order = this.getById(dto.getId());
        if (order == null) {
            return false;
        }
        String validateStatus = dto.getValidateStatus();
        Long rectifyOrderId = dto.getId();
        String certificationNumber = dto.getCertificationNumber();

        CertificationOrder certificationOrder = certificationOrderService.getOne(Wrappers.<CertificationOrder>lambdaQuery().eq(CertificationOrder::getCertificationNumber, certificationNumber));

        //查询需当前审核人员审核相关记录
        Massaudit massaudit = massauditService.getOne(Wrappers.<Massaudit>lambdaQuery()
                .eq(Massaudit::getAuditUser, getUserId())
                .eq(Massaudit::getAuditDept, getUserDeptId())
                .eq(Massaudit::getCode, dto.getCertificationNumber())
                .eq(Massaudit::getProcess, FLOW_PROCESS_TWO)
                .eq(Massaudit::getAuditState, FLOW_AUDIT_DEFAULT));

        if (massaudit == null) {
            massaudit = new Massaudit();
            massaudit.setInitiator(dto.getVerifyPersonId())
                    .setAuditUser(getUserId())
                    .setAuditState(FLOW_AUDIT_DEFAULT)
                    .setProcess(FLOW_PROCESS_TWO)
                    .setAuditDept(getUserDeptId())
                    .setNum(1L)
                    .setCode(dto.getCertificationNumber());
            massauditService.save(massaudit);
        }

        if (FLOW_FINISHED.equals(validateStatus)) {

            massaudit.setMsg(dto.getMsg())
                    .setAuditState(FLOW_AUDIT_THROUGH);

            massauditService.updateById(massaudit);

            if (dto.getAuditUser() == null) {
                //推送消息给工单上报人、检验记录人
                Messagepush messagePush = getMessagePush(rectifyOrderId, PROCESS_FINISHED_MESSAGE, QualityControlMessageTopicEnum.VALIDATE_PROCESS, QualityControlMessageTypeEnum.MESSAGE_TYPE_QUALITY_ORDER);
                messagePush.setRouteIp(configUtils.getYwjkUrl());
                qualityControlMessageRecipientService.setMessageRecipient(messagePush, dto.getDispatchPersonId());
                qualityControlMessageRecipientService.setMessageRecipient(messagePush, dto.getCertificationPersonId());
                qualityControlMessageRecipientService.removeDB(rectifyOrderId, QualityControlMessageTopicEnum.VALIDATE_PROCESS);

                RectifyOrder rectifyOrderById = getById(dto.getId());

                //工单完成时作一次超时和驳回异常判断
                Map<String, Integer> statusMap = getAllStatus(certificationOrder, rectifyOrderById, certificationNumber);

                order.setIssueExceptionStatus(statusMap.get(ISSUE_EXCEPTION_STATUS))
                        .setRectifyExceptionStatus(statusMap.get(RECTIFY_EXCEPTION_STATUS))
                        .setAuditExceptionStatus(statusMap.get(AUDIT_EXCEPTION_STATUS))
                        .setVerifyExceptionStatus(statusMap.get(VERIFY_EXCEPTION_STATUS))
                        .setValidateExceptionStatus(statusMap.get(VALIDATE_EXCEPTION_STATUS));

                certificationOrder.setCertificationExceptionStatus(statusMap.get(CERTIFICATION_EXCEPTION_STATUS))
                        .setOrderExceptionStatus(statusMap.get(ORDER_EXCEPTION_STATUS));
            } else {
                //生成下个审核人的部分信息
                Massaudit audit = new Massaudit();
                audit.setParentId(massaudit.getId())
                        .setInitiator(getUserId())
                        .setAuditDept(baseMapper.getDeptIdByUser(dto.getAuditUser()))
                        .setAuditUser(dto.getAuditUser())
                        .setCode(dto.getCertificationNumber())
                        .setProcess(FLOW_PROCESS_TWO)
                        .setNum(massaudit.getNum() + 1)
                        .setAuditState(FLOW_AUDIT_DEFAULT);

                massauditService.save(audit);

                order.setValidateStatus("0");

                //因为这是先清除所有整改下达的，所以先清除，再生成
                qualityControlMessageRecipientService.removeDB(rectifyOrderId, QualityControlMessageTopicEnum.VALIDATE_PROCESS);

                Messagepush messagePush = getMessagePush(rectifyOrderId, RECTIFY_ISSUED_AUDIT_MESSAGE, QualityControlMessageTopicEnum.VALIDATE_PROCESS, QualityControlMessageTypeEnum.MESSAGE_TYPE_QUALITY_ORDER);
                messagePush.setRouteIp(configUtils.getZgshUrl());
                messagePush.setRouteIpApp(configUtils.getZgshUrlapp());
                qualityControlMessageRecipientService.setMessageRecipient(messagePush, dto.getAuditUser(), null);
            }

        } else if (FLOW_REJECTED.equals(validateStatus)) {

            if (massaudit.getNum() == 1) {
                RejectedRecord rejectedRecord = RejectedRecord.builder()
                        .certificationNumber(certificationNumber)
                        .executeDept(dto.getVerifyDept())
                        .executePerson(dto.getVerifyPerson())
                        .executePersonId(dto.getVerifyPersonId())
                        .executeTime(dto.getVerifyTime())
                        .executeAdvice(dto.getExecuteAdvice())
                        .currentProcess(VALIDATE_PROCESS)
                        .createTime(DateUtil.getCurrentTime())
                        .createUser(SecurityUtils.getUserName())
                        .createUserId(SecurityUtils.getUserId()).build();
                rejectedRecordService.save(rejectedRecord);

                massauditService.removeById(massaudit.getId());

                if (dto.getVerifyExceptionStatus() == null || dto.getVerifyExceptionStatus() == 0) {
                    order.setVerifyExceptionStatus(FLOW_REJECTED_STATUS);
                } else if (dto.getVerifyExceptionStatus() == 1) {
                    order.setVerifyExceptionStatus(FLOW_REJECTED_STATUS + 1);
                }
                order.setVerifyStatus(FLOW_CURRENT_PROCESS);
                certificationOrder.setCurrentProcess(VERIFY_PROCESS);
                certificationOrder.setOrderExceptionStatus(FLOW_REJECTED_STATUS);
                Messagepush messagePush = getMessagePush(rectifyOrderId, VERIFY_REJECTED_MESSAGE, QualityControlMessageTopicEnum.VERIFY_PROCESS, QualityControlMessageTypeEnum.MESSAGE_TYPE_QUALITY_ORDER);
                messagePush.setRouteIp(configUtils.getZgyzUrl());
                messagePush.setRouteIpApp(configUtils.getZgyzUrlapp());
                qualityControlMessageRecipientService.setMessageRecipient(messagePush, order.getVerifyPersonId(), null);
            } else {
                //生成下个审核人的部分信息
                Massaudit audit = new Massaudit();
                audit.setParentId(massaudit.getId())
                        .setInitiator(getUserId())
                        .setAuditDept(baseMapper.getDeptIdByUser(massaudit.getInitiator()))
                        .setAuditUser(massaudit.getInitiator())
                        .setCode(dto.getCertificationNumber())
                        .setProcess(FLOW_PROCESS_TWO)
                        .setNum(massaudit.getNum() - 1)
                        .setAuditState(FLOW_AUDIT_DEFAULT);

                order.setValidateStatus("0");

                massauditService.save(audit);
                //因为这是先清除所有整改下达的，所以先清除，再生成
                qualityControlMessageRecipientService.removeDB(rectifyOrderId, QualityControlMessageTopicEnum.ISSUE_PROCESS);

                Messagepush messagePush = getMessagePush(rectifyOrderId, ISSUE_REJECTED_MESSAGE, QualityControlMessageTopicEnum.ISSUE_PROCESS, QualityControlMessageTypeEnum.MESSAGE_TYPE_QUALITY_ORDER);
                messagePush.setRouteIp(configUtils.getZgxdUrl());
                messagePush.setRouteIpApp(configUtils.getZgxdUrlapp());
                qualityControlMessageRecipientService.setMessageRecipient(messagePush, massaudit.getInitiator(), null);
            }
            if (massaudit.getNum() != 1) {
                //记录驳回
                massaudit.setMsg(dto.getExecuteAdvice())
                        .setAuditState(FLOW_AUDIT_REJECT)
                        .setParentId(massaudit.getId());
                massauditService.updateById(massaudit);
            }


        }

        updateById(order);
        certificationOrderService.updateById(certificationOrder);
        if (FLOW_FINISHED.equals(validateStatus) && IS_CB.equals(certificationOrder.getIsCb())) {
            certificationOrderService.updateReadmeterhis(certificationOrder.getClientNumber(), certificationOrder.getYearMonth());
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateRectifyValidate(NewRectifyIssueDto dto, List<MultipartFile> fileList) {
        RectifyOrder rectifyOrder = dto.getRectifyOrder();
        String executeAdvice = dto.getExecuteAdvice();
        List<Massaudit> maudits = dto.getMaudits();

        if (rectifyOrder == null) {
            return false;
        }

        String validateStatus = rectifyOrder.getValidateStatus();
        Long rectifyOrderId = rectifyOrder.getId();

        RectifyOrder rectifyOrderById = getById(rectifyOrderId);

        String certificationNumber = rectifyOrder.getCertificationNumber();

        CertificationOrder certificationOrder = certificationOrderService.getOne(Wrappers.<CertificationOrder>lambdaQuery().eq(CertificationOrder::getCertificationNumber, certificationNumber));

        Long maxAuditLevel = baseMapper.maxAuditLevel(rectifyOrder.getCertificationNumber(), FLOW_PROCESS_TWO);

        if (FLOW_FINISHED.equals(validateStatus)) {

            Long maxId = baseMapper.getMaxId(MASSAUDIT_NAME);
            //如果传入集合不为空，说明是添加审核人
            if (maudits != null && !maudits.isEmpty()) {
                for (int i = 0; i < maudits.size(); i++) {
                    Massaudit massaudit = maudits.get(i);
                    if (i == 0) {
                        massaudit.setInitiator(rectifyOrder.getValidatePersonId());
                    } else {
                        massaudit.setInitiator(maudits.get(i - 1).getAuditUser());
                    }
                    massaudit.setId(maxId);
                    maxId++;
                    massauditService.save(massaudit);
                }
                //获取添加的第一条审核人信息
                Massaudit massaudit = maudits.stream()
                        .sorted(Comparator.comparing(Massaudit::getNum))
                        .collect(Collectors.toList()).get(0);

                rectifyOrder.setValidateStatus(FLOW_CURRENT_PROCESS);

                qualityControlMessageRecipientService.removeDB(rectifyOrderId, QualityControlMessageTopicEnum.VALIDATE_PROCESS);

                Messagepush messagePush = getMessagePush(rectifyOrderId, VALIDATE_MESSAGE, QualityControlMessageTopicEnum.VALIDATE_PROCESS, QualityControlMessageTypeEnum.MESSAGE_TYPE_QUALITY_ORDER);
                messagePush.setRouteIp(configUtils.getYzshUrl());
                messagePush.setRouteIpApp(configUtils.getYzshUrlapp());
                qualityControlMessageRecipientService.setMessageRecipient(messagePush, massaudit.getAuditUser(), null);

            } else {

                Long num = 0L;
                //获取未审核记录
                List<Massaudit> massauditList = massauditService.list(Wrappers.<Massaudit>lambdaQuery()
                        .eq(Massaudit::getCode, rectifyOrder.getCertificationNumber())
                        .eq(Massaudit::getProcess, FLOW_PROCESS_TWO).eq(Massaudit::getAuditState, FLOW_AUDIT_DEFAULT)
                        .orderByAsc(Massaudit::getNum)
                        .orderByAsc(Massaudit::getCreateTime));
                //如果有未审核记录，审核
                if (!massauditList.isEmpty()) {
                    Massaudit massaudit = massauditList.get(0);
                    massaudit.setMsg(executeAdvice);
                    massaudit.setAuditState(FLOW_AUDIT_THROUGH);
                    massaudit.setCreateTime(new Date());
                    massauditService.updateById(massaudit);

                    num = massaudit.getNum();

                    if (num < maxAuditLevel) {

                        rectifyOrder.setValidateStatus(FLOW_CURRENT_PROCESS);

                        //查询下一等级是否有未审核记录
                        List<Massaudit> nextAuditList = massauditService.list(Wrappers.<Massaudit>lambdaQuery()
                                .eq(Massaudit::getCode, rectifyOrder.getCertificationNumber())
                                .eq(Massaudit::getProcess, FLOW_PROCESS_TWO).eq(Massaudit::getAuditState, FLOW_AUDIT_DEFAULT)
                                .eq(Massaudit::getNum, num + 1));

                        Long auditUser;

                        //如果没有生成一条审核记录
                        if (nextAuditList.isEmpty()) {
                            Massaudit nextAudit = massauditService.list(Wrappers.<Massaudit>lambdaQuery()
                                    .eq(Massaudit::getCode, rectifyOrder.getCertificationNumber())
                                    .eq(Massaudit::getProcess, FLOW_PROCESS_TWO)
                                    .eq(Massaudit::getNum, num + 1)).get(0);

                            nextAudit.setMsg(null).setCreateTime(null).setAuditState(FLOW_AUDIT_DEFAULT);

                            massauditService.save(nextAudit);

                            auditUser = nextAudit.getAuditUser();
                        } else {
                            auditUser = nextAuditList.get(0).getAuditUser();
                        }

                        qualityControlMessageRecipientService.removeDB(rectifyOrderId, QualityControlMessageTopicEnum.VALIDATE_PROCESS);

                        Messagepush messagePush = getMessagePush(rectifyOrderId, VALIDATE_MESSAGE, QualityControlMessageTopicEnum.VALIDATE_PROCESS, QualityControlMessageTypeEnum.MESSAGE_TYPE_QUALITY_ORDER);
                        messagePush.setRouteIp(configUtils.getYzshUrl());
                        messagePush.setRouteIpApp(configUtils.getYzshUrlapp());
                        qualityControlMessageRecipientService.setMessageRecipient(messagePush, auditUser, null);
                    }

                } else {
                    //没有未审核记录的话
                    List<Massaudit> mauditList = massauditService.list(Wrappers.<Massaudit>lambdaQuery()
                            .eq(Massaudit::getCode, rectifyOrder.getCertificationNumber())
                            .eq(Massaudit::getProcess, FLOW_PROCESS_TWO)
                            .orderByDesc(Massaudit::getCreateTime));

                    if (!mauditList.isEmpty()) {
                        Massaudit massaudit = mauditList.get(0);
                        //如果最后一条等级是1，并且是驳回的
                        if (massaudit.getNum() == 1 && massaudit.getAuditState().equals(FLOW_AUDIT_REJECT)) {
                            massaudit.setMsg(null);
                            massaudit.setCreateTime(null);
                            massaudit.setAuditState(FLOW_AUDIT_DEFAULT);

                            massauditService.save(massaudit);

                            rectifyOrder.setValidateStatus(FLOW_CURRENT_PROCESS);

                            qualityControlMessageRecipientService.removeDB(rectifyOrderId, QualityControlMessageTopicEnum.VALIDATE_PROCESS);

                            Messagepush messagePush = getMessagePush(rectifyOrderId, VALIDATE_MESSAGE, QualityControlMessageTopicEnum.VALIDATE_PROCESS, QualityControlMessageTypeEnum.MESSAGE_TYPE_QUALITY_ORDER);
                            messagePush.setRouteIp(configUtils.getYzshUrl());
                            messagePush.setRouteIpApp(configUtils.getYzshUrlapp());
                            qualityControlMessageRecipientService.setMessageRecipient(messagePush, massaudit.getAuditUser(), null);

                        }
                    }
                }

                if (num.equals(maxAuditLevel)) {

                    //推送消息给工单上报人、检验记录人
                    Messagepush messagePush = getMessagePush(rectifyOrderId, PROCESS_FINISHED_MESSAGE, QualityControlMessageTopicEnum.VALIDATE_PROCESS, QualityControlMessageTypeEnum.MESSAGE_TYPE_QUALITY_ORDER);
                    messagePush.setRouteIp(configUtils.getYwjkUrl());
                    qualityControlMessageRecipientService.setMessageRecipient(messagePush, rectifyOrderById.getDispatchPersonId());
                    qualityControlMessageRecipientService.setMessageRecipient(messagePush, rectifyOrderById.getCertificationPersonId());
                    //工单完成时作一次超时和驳回异常判断
                    Map<String, Integer> statusMap = getAllStatus(certificationOrder, rectifyOrderById, certificationNumber);

                    rectifyOrder.setIssueExceptionStatus(statusMap.get(ISSUE_EXCEPTION_STATUS))
                            .setRectifyExceptionStatus(statusMap.get(RECTIFY_EXCEPTION_STATUS))
                            .setAuditExceptionStatus(statusMap.get(AUDIT_EXCEPTION_STATUS))
                            .setVerifyExceptionStatus(statusMap.get(VERIFY_EXCEPTION_STATUS))
                            .setValidateExceptionStatus(statusMap.get(VALIDATE_EXCEPTION_STATUS));

                    certificationOrder.setCertificationExceptionStatus(statusMap.get(CERTIFICATION_EXCEPTION_STATUS))
                            .setOrderExceptionStatus(statusMap.get(ORDER_EXCEPTION_STATUS));

                    qualityControlMessageRecipientService.removeDB(rectifyOrderId, QualityControlMessageTopicEnum.VALIDATE_PROCESS);
                }
            }

        } else if (FLOW_REJECTED.equals(validateStatus)) {

            //获取未审核记录
            List<Massaudit> massauditList = massauditService.list(Wrappers.<Massaudit>lambdaQuery()
                    .eq(Massaudit::getCode, rectifyOrder.getCertificationNumber())
                    .eq(Massaudit::getProcess, FLOW_PROCESS_TWO).eq(Massaudit::getAuditState, FLOW_AUDIT_DEFAULT)
                    .orderByAsc(Massaudit::getNum).orderByAsc(Massaudit::getCreateTime));

            if (!massauditList.isEmpty()) {
                Massaudit massaudit = massauditList.get(0);
                massaudit.setMsg(executeAdvice);
                massaudit.setCreateTime(new Date());
                massaudit.setAuditState(FLOW_AUDIT_REJECT);
                massauditService.updateById(massaudit);

                rectifyOrder.setValidateStatus(FLOW_CURRENT_PROCESS);

                qualityControlMessageRecipientService.removeDB(rectifyOrderId, QualityControlMessageTopicEnum.VALIDATE_PROCESS);

                Messagepush messagePush = getMessagePush(rectifyOrderId, VALIDATE_REJECTED_MESSAGE, QualityControlMessageTopicEnum.VALIDATE_PROCESS, QualityControlMessageTypeEnum.MESSAGE_TYPE_QUALITY_ORDER);
                messagePush.setRouteIp(configUtils.getYzshUrl());
                messagePush.setRouteIpApp(configUtils.getYzshUrlapp());

                Long num = massaudit.getNum();

                if (num != 0) {
                    Long nowAuditUser = baseMapper.getNowAuditUser(certificationNumber, FLOW_PROCESS_TWO, num - 1);
                    RectifyOrder order = getById(rectifyOrderId);

                    Massaudit audit = new Massaudit();
                    audit.setNum(num - 1);
                    audit.setProcess(FLOW_PROCESS_TWO);
                    audit.setAuditState(FLOW_AUDIT_DEFAULT);
                    audit.setCode(massaudit.getCode());
                    audit.setInitiator(SecurityUtils.getUserId());
                    //发起人默认为上一级审核人
                    audit.setAuditUser(nowAuditUser != null ? nowAuditUser : order.getValidatePersonId());
                    audit.setAuditDept(baseMapper.getDeptIdByUser(audit.getAuditUser()));

                    massauditService.save(audit);

                    qualityControlMessageRecipientService.setMessageRecipient(messagePush, audit.getAuditUser(), null);
                }
            }

            if (massauditList.isEmpty() || massauditList.get(0).getNum() == 0) {
                RejectedRecord rejectedRecord = RejectedRecord.builder()
                        .certificationNumber(certificationNumber)
                        .executeDept(rectifyOrder.getVerifyDept())
                        .executePerson(rectifyOrder.getVerifyPerson())
                        .executePersonId(rectifyOrder.getVerifyPersonId())
                        .executeTime(rectifyOrder.getVerifyTime())
                        .executeAdvice(executeAdvice)
                        .currentProcess(VALIDATE_PROCESS)
                        .createTime(DateUtil.getCurrentTime())
                        .createUser(SecurityUtils.getUserName())
                        .createUserId(SecurityUtils.getUserId()).build();

                rejectedRecordService.save(rejectedRecord);

                if (rectifyOrder.getVerifyExceptionStatus() == null || rectifyOrder.getVerifyExceptionStatus() == 0) {
                    rectifyOrder.setVerifyExceptionStatus(FLOW_REJECTED_STATUS);
                } else if (rectifyOrder.getVerifyExceptionStatus() == 1) {
                    rectifyOrder.setVerifyExceptionStatus(FLOW_REJECTED_STATUS + 1);
                }

                qualityControlMessageRecipientService.removeDB(rectifyOrderId, QualityControlMessageTopicEnum.VALIDATE_PROCESS);

                rectifyOrder.setVerifyStatus(FLOW_CURRENT_PROCESS);
                certificationOrder.setCurrentProcess(VERIFY_PROCESS);
                certificationOrder.setOrderExceptionStatus(FLOW_REJECTED_STATUS);
                Messagepush messagePush = getMessagePush(rectifyOrderId, VERIFY_REJECTED_MESSAGE, QualityControlMessageTopicEnum.VERIFY_PROCESS, QualityControlMessageTypeEnum.MESSAGE_TYPE_QUALITY_ORDER);
                messagePush.setRouteIp(configUtils.getZgyzUrl());
                messagePush.setRouteIpApp(configUtils.getZgyzUrlapp());
                qualityControlMessageRecipientService.setMessageRecipient(messagePush, rectifyOrderById.getVerifyPersonId(), null);
            }
        }
        updateById(rectifyOrder);
        certificationOrderService.updateById(certificationOrder);

        if (FLOW_FINISHED.equals(validateStatus) && IS_CB.equals(certificationOrder.getIsCb())) {
            certificationOrderService.updateReadmeterhis(certificationOrder.getClientNumber(), certificationOrder.getYearMonth());
        }
        return true;
    }

    @Override
    public IPage<RectifyOrderListVo> getRectifyValidateList(ReportOrderDto dto, Page page) {
        Page<RectifyOrderListVo> orderVOLPage = null;
        if (dto.getType() == null || dto.getType().equals(0)) {
            orderVOLPage = this.baseMapper.loadRectifyValidateList(dto, getUserId(), null, page);
        } else if (dto.getType().equals(1)) {
            orderVOLPage = this.baseMapper.loadRectifyValidateList(dto, null, getUserDeptId(), page);
        }
        fillDeptName(orderVOLPage);

        if (orderVOLPage != null && orderVOLPage.getTotal() != 0) {
            for (RectifyOrderListVo record : orderVOLPage.getRecords()) {

                String number = record.getCertificationNumber();

                List<Massaudit> auditInfo = massauditService.list(Wrappers.<Massaudit>lambdaQuery()
                        .eq(Massaudit::getCode, number)
                        .eq(Massaudit::getProcess, FLOW_PROCESS_TWO)
                        .eq(Massaudit::getAuditState, FLOW_AUDIT_DEFAULT)
                        .orderByAsc(Massaudit::getNum));

                if (auditInfo != null && !auditInfo.isEmpty()) {
                    record.setAuditId(auditInfo.get(0).getAuditUser());
                } else {
                    record.setAuditId(baseMapper.getAuditUser(number, FLOW_PROCESS_TWO));
                }

                Long nowLevel = baseMapper.getNowLevel(number, FLOW_PROCESS_TWO);
                record.setAuditLevel(nowLevel == null ? 0 : nowLevel);
            }
        }

        return orderVOLPage;

    }

    @Override
    public RectifyValidateOrderVO_D getRectifyValidateDetail(Long id) {
        RectifyValidateOrderVO_D vo = getVO(getById(id), RectifyValidateOrderVO_D.class);

        String validateDept = vo.getValidateDept();
        Boolean flag1 = isNotNull(validateDept);
        if (flag1) {
            vo.setValidateDept(getDeptName(validateDept));
        }
        return vo;
    }

    @Override
    public IPage<BusinessMonitorVO_L> getBusinessMonitorList(Date startDate, Date endDate, String number, String currentProcess, Integer orderExceptionStatus, Page<CertificationOrder> page) {
        IPage<BusinessMonitorVO_L> pg = baseMapper.getBusinessMonitorList(startDate, endDate, number, currentProcess, orderExceptionStatus, page);
        Map<String, String> map = new HashMap<>();
        for (BusinessMonitorVO_L vo : pg.getRecords()) {
            String pr = vo.getCertificationProject();
            if (StringUtils.isNotEmpty(pr)) {
                String prName = null;
                if (map.containsKey(pr)) {
                    prName = map.get(pr);
                } else {
                    prName = codeClient.getname(Long.parseLong(pr));
                    map.put(pr, prName);
                }
                vo.setCertificationProjectName(prName);
            }
        }
        return pg;
    }

    @Override
    public BusinessMonitorVO_D getAllDetail(Long id) {
        CertificationOrder certificationOrder = certificationOrderService.getById(id);
        if (certificationOrder == null) {
            return null;
        }
        String certificationNumber = certificationOrder.getCertificationNumber();
        RectifyOrder rectifyOrder = getOne(Wrappers.<RectifyOrder>lambdaQuery()
                .eq(RectifyOrder::getCertificationNumber, certificationNumber));
        //.ne(RectifyOrder::getIssueStatus,FLOW_REJECTED));

        CertificationOrderVO_D certificationOrderVO_d = getVO(certificationOrder, CertificationOrderVO_D.class);

        //将部门id转为部门名称
        String certificationDept = certificationOrderVO_d.getCertificationDept();
        certificationOrderVO_d = isNotNull(certificationDept) ? certificationOrderVO_d.setCertificationDept(getDeptName(certificationDept)) : certificationOrderVO_d;

        if (Objects.nonNull(rectifyOrder)) {
            String issueDept = rectifyOrder.getIssueDept();
            rectifyOrder = isNotNull(issueDept) ? rectifyOrder.setCertificationDept(getDeptName(issueDept)) : rectifyOrder;

            String rectifyDept = rectifyOrder.getRectifyDept();
            rectifyOrder = isNotNull(rectifyDept) ? rectifyOrder.setRectifyDept(getDeptName(rectifyDept)) : rectifyOrder;

            String auditDept = rectifyOrder.getAuditDept();
            rectifyOrder = isNotNull(auditDept) ? rectifyOrder.setAuditDept(getDeptName(auditDept)) : rectifyOrder;

            String verifyDept = rectifyOrder.getVerifyDept();
            rectifyOrder = isNotNull(verifyDept) ? rectifyOrder.setVerifyDept(getDeptName(verifyDept)) : rectifyOrder;

            String validateDept = rectifyOrder.getValidateDept();
            rectifyOrder = isNotNull(validateDept) ? rectifyOrder.setValidateDept(getDeptName(validateDept)) : rectifyOrder;

            RectifyIssueOrderVO_D rectifyIssueOrderVO_d = getVO(rectifyOrder, RectifyIssueOrderVO_D.class);
            RectifyResultOrderVO_D rectifyResultOrderVO_d = getVO(rectifyOrder, RectifyResultOrderVO_D.class);
            RectifyAuditOrderVO_D rectifyAuditOrderVO_d = getVO(rectifyOrder, RectifyAuditOrderVO_D.class);
            RectifyVerifyOrderVO_D rectifyVerifyOrderVO_d = getVO(rectifyOrder, RectifyVerifyOrderVO_D.class);
            RectifyValidateOrderVO_D rectifyValidateOrderVO_d = getVO(rectifyOrder, RectifyValidateOrderVO_D.class);

            return BusinessMonitorVO_D.builder()
                    .certificationOrderVO_d(certificationOrderVO_d)
                    .rectifyIssueOrderVO_d(rectifyIssueOrderVO_d)
                    .rectifyResultOrderVO_d(rectifyResultOrderVO_d)
                    .rectifyAuditOrderVO_d(rectifyAuditOrderVO_d)
                    .rectifyVerifyOrderVO_d(rectifyVerifyOrderVO_d)
                    .rectifyValidateOrderVO_d(rectifyValidateOrderVO_d).build();
        }
        return BusinessMonitorVO_D.builder().certificationOrderVO_d(certificationOrderVO_d).build();
    }

    @Override
    public CertificationOrderVO_D getCertificationOrderDetail(String certificationNumber) {
        CertificationOrderVO_D vo = getVO(certificationOrderService.getOne(Wrappers.<CertificationOrder>lambdaQuery().eq(CertificationOrder::getCertificationNumber, certificationNumber)), CertificationOrderVO_D.class);
        String certificationDept = vo.getCertificationDept();
        Boolean flag1 = isNotNull(certificationDept);
        if (flag1) {
            vo.setCertificationDept(getDeptName(certificationDept));
        }
        return vo;
    }

    /**
     * 定时，扫描异常状态
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void scanAndUpdate() {
        //未完成工单
        List<RectifyOrder> list = list(Wrappers.<RectifyOrder>lambdaQuery().ne(RectifyOrder::getValidateStatus, FLOW_FINISHED));

        if (CollectionUtils.isEmpty(list)) {
            return;
        }

        List<String> certificationNumberList = list.stream().map(RectifyOrder::getCertificationNumber).collect(Collectors.toList());

        certificationNumberList.forEach(certificationNumber -> {
            CertificationOrder certificationOrder = certificationOrderService.getOne(Wrappers.<CertificationOrder>lambdaQuery().eq(CertificationOrder::getCertificationNumber, certificationNumber));

            RectifyOrder rectifyOrder = getOne(Wrappers.<RectifyOrder>lambdaQuery().eq(RectifyOrder::getCertificationNumber, certificationNumber));

            Map<String, Integer> statusMap = getAllStatus(certificationOrder, rectifyOrder, certificationNumber);

            update(null, Wrappers.<RectifyOrder>lambdaUpdate()
                    .set(RectifyOrder::getIssueExceptionStatus, statusMap.get(ISSUE_EXCEPTION_STATUS))
                    .set(RectifyOrder::getRectifyExceptionStatus, statusMap.get(RECTIFY_EXCEPTION_STATUS))
                    .set(RectifyOrder::getAuditExceptionStatus, statusMap.get(AUDIT_EXCEPTION_STATUS))
                    .set(RectifyOrder::getVerifyExceptionStatus, statusMap.get(VERIFY_EXCEPTION_STATUS))
                    .set(RectifyOrder::getValidateExceptionStatus, statusMap.get(VALIDATE_EXCEPTION_STATUS))
                    .eq(RectifyOrder::getCertificationNumber, certificationNumber));

            certificationOrderService.update(null, Wrappers.<CertificationOrder>lambdaUpdate()
                    .set(CertificationOrder::getCertificationExceptionStatus, statusMap.get(CERTIFICATION_EXCEPTION_STATUS))
                    .set(CertificationOrder::getOrderExceptionStatus, statusMap.get(ORDER_EXCEPTION_STATUS))
                    .eq(CertificationOrder::getCertificationNumber, certificationNumber));
        });
    }

    /**
     * 定时扫描，超时发送短信
     */
    @Override
    public void remindOverdueTasks() {
        //所有超时异常工单
        List<CertificationOrder> list = certificationOrderService.list(Wrappers.<CertificationOrder>lambdaQuery().in(CertificationOrder::getOrderExceptionStatus, 1, 3));

        if (CollectionUtils.isEmpty(list)) {
            return;
        }

        list.forEach(l -> {
            Integer certificationExceptionStatus = l.getCertificationExceptionStatus();

            //发送消息给对应人
            if ((certificationExceptionStatus & 1) == 1) {
                Messagepush messagePush_A = getMessagePush(l.getId(), INSPECTION_OVERDUE_MESSAGE, QualityControlMessageTopicEnum.OVERDUE_A, QualityControlMessageTypeEnum.MESSAGE_TYPE_OVERDUE);
                qualityControlMessageRecipientService.setMessageRecipient(messagePush_A, l.getCertificationPersonId(), l.getRectifyTimeLimit());
            }

            RectifyOrder rectifyOrder = getOne(Wrappers.<RectifyOrder>lambdaQuery().eq(RectifyOrder::getCertificationNumber, l.getCertificationNumber()));

            if (Objects.nonNull(rectifyOrder)) {
                Integer issueExceptionStatus = rectifyOrder.getIssueExceptionStatus();
                Integer auditExceptionStatus = rectifyOrder.getAuditExceptionStatus();
                Integer verifyExceptionStatus = rectifyOrder.getVerifyExceptionStatus();

                if ((issueExceptionStatus & 1) == 1) {
                    Messagepush messagePush_B = getMessagePush(rectifyOrder.getId(), ISSUE_OVERDUE_MESSAGE, QualityControlMessageTopicEnum.OVERDUE_B, QualityControlMessageTypeEnum.MESSAGE_TYPE_OVERDUE);
                    qualityControlMessageRecipientService.setMessageRecipient(messagePush_B, rectifyOrder.getIssuePersonId(), l.getRectifyTimeLimit());
                }

                if ((auditExceptionStatus & 1) == 1) {
                    Messagepush messagePush_B = getMessagePush(rectifyOrder.getId(), AUDIT_OVERDUE_MESSAGE, QualityControlMessageTopicEnum.OVERDUE_B, QualityControlMessageTypeEnum.MESSAGE_TYPE_OVERDUE);
                    qualityControlMessageRecipientService.setMessageRecipient(messagePush_B, rectifyOrder.getAuditPersonId(), l.getRectifyTimeLimit());
                }

                if ((verifyExceptionStatus & 1) == 1) {
                    Messagepush messagePush_B = getMessagePush(rectifyOrder.getId(), VERIFY_OVERDUE_MESSAGE, QualityControlMessageTopicEnum.OVERDUE_B, QualityControlMessageTypeEnum.MESSAGE_TYPE_OVERDUE);
                    qualityControlMessageRecipientService.setMessageRecipient(messagePush_B, rectifyOrder.getVerifyPersonId(), l.getRectifyTimeLimit());
                }
            }
        });
    }

    /**
     * 质检工单整改下达汇总列表
     *
     * @param dto 查询条件
     * @return
     */
    @Override
    public List<ReportSummaryVo> getIssueSummary(OrderDto dto) {
        List<ReportSummaryVo> vos = null;
        if (dto.getType() == null || dto.getType().equals(0)) {
            vos = this.baseMapper.getIssueSummary(dto, getUserId(), ratio, null);
        } else if (dto.getType().equals(1)) {
            vos = this.baseMapper.getIssueSummary(dto, null, ratio, getUserDeptId());
        }
        return vos;
    }

    /**
     * 质检工单整改处置汇总列表
     *
     * @param dto 查询条件
     * @return
     */
    @Override
    public List<ReportSummaryVo> getRectifySummary(OrderDto dto) {
        List<ReportSummaryVo> vos = null;
        if (dto.getType() == null || dto.getType().equals(0)) {
            vos = this.baseMapper.getRectifySummary(dto, getUserId(), ratio, null);
        } else if (dto.getType().equals(1)) {
            vos = this.baseMapper.getRectifySummary(dto, null, ratio, getUserDeptId());
        }
        return vos;
    }

    /**
     * 质检工单整改审核汇总列表
     *
     * @param dto 查询条件
     * @return
     */
    @Override
    public List<ReportSummaryVo> getAuditSummary(OrderDto dto) {
        List<ReportSummaryVo> vos = null;
        if (dto.getType() == null || dto.getType().equals(0)) {
            vos = this.baseMapper.getAuditSummary(dto, getUserId(), ratio, null);
        } else if (dto.getType().equals(1)) {
            vos = this.baseMapper.getAuditSummary(dto, null, ratio, getUserDeptId());
        }
        return vos;
    }

    /**
     * 质检工单整改验证汇总列表
     *
     * @param dto 查询条件
     * @return
     */
    @Override
    public List<ReportSummaryVo> getVerifySummary(OrderDto dto) {
        List<ReportSummaryVo> vos = null;
        if (dto.getType() == null || dto.getType().equals(0)) {
            vos = this.baseMapper.getVerifySummary(dto, getUserId(), ratio, null);
        } else if (dto.getType().equals(1)) {
            vos = this.baseMapper.getVerifySummary(dto, null, ratio, getUserDeptId());
        }
        return vos;
    }

    /**
     * 质检工单验证审核汇总列表
     *
     * @param dto 查询条件
     * @return
     */
    @Override
    public List<ReportSummaryVo> getValidateSummary(OrderDto dto) {
        List<ReportSummaryVo> vos = null;
        if (dto.getType() == null || dto.getType().equals(0)) {
            vos = this.baseMapper.getValidateSummary(dto, getUserId(), ratio, null);
        } else if (dto.getType().equals(1)) {
            vos = this.baseMapper.getValidateSummary(dto, null, ratio, getUserDeptId());
        }
        return vos;
    }


    private String getDeptName(String dept) {
        return departmentClient.getById(valueOf(dept)).getResult().getName();
    }

    private Map<String, Integer> getAllStatus(CertificationOrder certificationOrder, RectifyOrder rectifyOrder, String certificationNumber) {
        Integer rejectedCount = rejectedCountConfigService.getById(1L).getRejectedCount();

        //1. 驳回异常的判断
        List<Map<String, Object>> countMap = rejectedRecordService.listMaps(Wrappers.<RejectedRecord>query().select("CURRENT_PROCESS", "COUNT(*) AS COUNT").eq("CERTIFICATION_NUMBER", certificationNumber).groupBy("CURRENT_PROCESS"));

        Integer certificationExceptionStatus = certificationOrder.getCertificationExceptionStatus();
        Integer issueExceptionStatus = rectifyOrder.getIssueExceptionStatus();
        Integer rectifyExceptionStatus = rectifyOrder.getRectifyExceptionStatus();
        Integer auditExceptionStatus = rectifyOrder.getAuditExceptionStatus();
        Integer verifyExceptionStatus = rectifyOrder.getVerifyExceptionStatus();
        Integer validateExceptionStatus = rectifyOrder.getValidateExceptionStatus();
        Integer orderExceptionStatus = certificationOrder.getOrderExceptionStatus();

        Boolean a = false, b = false, c = false, d = false, e = false, f = false;

        for (Map<String, Object> map : countMap) {
            Integer count = 0;
            String currentProcess = null;

            for (Map.Entry<String, Object> entry : map.entrySet()) {
                String key = entry.getKey();
                if ("count".equals(key)) {
                    count = ((BigDecimal) entry.getValue()).intValue();
                } else {
                    currentProcess = (String) entry.getValue();
                }
            }
            //currentProcess匹配环节,count对比驳回设定值
            Boolean isRejected = count >= rejectedCount;

            switch (currentProcess) {
                case INSPECTION_PROCESS:
                    if (isRejected) {
                        certificationExceptionStatus = certificationExceptionStatus | 2;
                        a = true;
                    } else {
                        certificationExceptionStatus = certificationExceptionStatus & (3 - 2);
                    }
                    break;
                case ISSUE_PROCESS:
                    if (isRejected) {
                        issueExceptionStatus = issueExceptionStatus | 2;
                        b = true;
                    } else {
                        issueExceptionStatus = issueExceptionStatus & 1;
                    }
                    break;
                case DEAL_PROCESS:
                    if (isRejected) {
                        rectifyExceptionStatus = rectifyExceptionStatus | 2;
                        c = true;
                    } else {
                        rectifyExceptionStatus = rectifyExceptionStatus & 1;
                    }
                    break;
                case AUDIT_PROCESS:
                    if (isRejected) {
                        auditExceptionStatus = auditExceptionStatus | 2;
                        d = true;
                    } else {
                        auditExceptionStatus = auditExceptionStatus & 1;
                    }
                    break;
                case VERIFY_PROCESS:
                    if (isRejected) {
                        verifyExceptionStatus = verifyExceptionStatus | 2;
                        e = true;
                    } else {
                        verifyExceptionStatus = verifyExceptionStatus & 1;
                    }
                    break;
                case VALIDATE_PROCESS:
                    if (isRejected) {
                        validateExceptionStatus = validateExceptionStatus | 2;
                        f = true;
                    } else {
                        validateExceptionStatus = validateExceptionStatus & 1;
                    }
                    break;
            }
        }
        //对应更新总驳回异常状态
        orderExceptionStatus = a || b || c || d || e || f ? orderExceptionStatus | 2 : orderExceptionStatus & 1;

        //2. 超时异常的判断
        Date inspectionTimeLimit = certificationOrder.getCompletionTimeLimit();
        Date issueTimeLimit = rectifyOrder.getIssueTimeLimit();
        Date resultTimeLimit = rectifyOrder.getResultTimeLimit();
        Date verifyTimeLimit = rectifyOrder.getVerifyTimeLimit();

        Date certificationTime = certificationOrder.getCertificationTime();
        Date issueTime = rectifyOrder.getIssueTime();
        Date auditTime = rectifyOrder.getAuditTime();
        Date verifyTime = rectifyOrder.getVerifyTime();

        Date currentTime = new Date();

        int count = 0;
        //排除已经超时的2种情况
        if ((certificationExceptionStatus | 2) == 2) {
            //a.环节时间非空 环节时间和环节时限对比
            if (Objects.nonNull(certificationTime)) {
                if (certificationTime.compareTo(inspectionTimeLimit) >= 0) {
                    certificationExceptionStatus = certificationExceptionStatus | 1;
                    count++;
                }
            }
            //b.环节时间为空 当前时间和环节时限对比
            else {
                if (currentTime.compareTo(inspectionTimeLimit) >= 0) {
                    certificationExceptionStatus = certificationExceptionStatus | 1;
                    count++;
                }
            }
        }

        if ((issueExceptionStatus | 2) == 2) {
            if (Objects.nonNull(issueTime)) {
                if (issueTime.compareTo(issueTimeLimit) >= 0) {
                    issueExceptionStatus = issueExceptionStatus | 1;
                    count++;
                }
            } else {
                if (currentTime.compareTo(issueTimeLimit) >= 0) {
                    issueExceptionStatus = issueExceptionStatus | 1;
                    count++;
                }
            }
        }

        if ((auditExceptionStatus | 2) == 2) {
            if (Objects.nonNull(auditTime)) {
                if (auditTime.compareTo(resultTimeLimit) >= 0) {
                    auditExceptionStatus = auditExceptionStatus | 1;
                    count++;
                }
            } else {
                if (currentTime.compareTo(resultTimeLimit) >= 0) {
                    auditExceptionStatus = auditExceptionStatus | 1;
                    count++;
                }
            }
        }

        if ((verifyExceptionStatus | 2) == 2) {
            if (Objects.nonNull(verifyTime)) {
                if (verifyTime.compareTo(verifyTimeLimit) >= 0) {
                    verifyExceptionStatus = verifyExceptionStatus | 1;
                    count++;
                }
            } else {
                if (currentTime.compareTo(verifyTimeLimit) >= 0) {
                    verifyExceptionStatus = verifyExceptionStatus | 1;
                    count++;
                }
            }
        }
        //对应更新总超时异常状态
        if ((orderExceptionStatus | 2) == 2) {
            orderExceptionStatus = count > 0 ? orderExceptionStatus | 1 : orderExceptionStatus;
        }

        Map<String, Integer> statusMap = Maps.newHashMap();
        statusMap.put(CERTIFICATION_EXCEPTION_STATUS, certificationExceptionStatus);
        statusMap.put(ISSUE_EXCEPTION_STATUS, issueExceptionStatus);
        statusMap.put(RECTIFY_EXCEPTION_STATUS, rectifyExceptionStatus);
        statusMap.put(AUDIT_EXCEPTION_STATUS, auditExceptionStatus);
        statusMap.put(VERIFY_EXCEPTION_STATUS, verifyExceptionStatus);
        statusMap.put(VALIDATE_EXCEPTION_STATUS, validateExceptionStatus);
        statusMap.put(ORDER_EXCEPTION_STATUS, orderExceptionStatus);
        return statusMap;
    }


    @Override
    public List<RectifySummaryVo> getOrderRectify(OrderReportDto dto) {
        List<RectifySummaryVo> vos = this.baseMapper.loadOrderRectifySummary(dto);
        Map<Long, String> deptMap = new HashMap<>();
        for (RectifySummaryVo vo : vos) {
            vo.setDeptName(deptName(deptMap, vo.getDept()));
        }

        return vos;
    }

    @Override
    public List<Map<String, Object>> getEconomyBenefit(OrderReportDto dto) {
        return this.baseMapper.loadEconomyBenefit(dto);
    }


}
