package com.casic.missiles.service.Impl.business;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.casic.missiles.core.base.service.IBaseExportService;
import com.casic.missiles.core.model.auth.AuthUser;
import com.casic.missiles.core.page.PageFactory;
import com.casic.missiles.core.shiro.ShiroKit;
import com.casic.missiles.dto.ReturnDTO;
import com.casic.missiles.dto.ReturnUtil;
import com.casic.missiles.dto.business.dispatch.*;
import com.casic.missiles.dto.business.labExecutive.HandOutLabExecutiveDTO;
import com.casic.missiles.enums.BusinessExceptionEnum;
import com.casic.missiles.enums.ExportEnum;
import com.casic.missiles.enums.business.MeasureStatusEnum;
import com.casic.missiles.enums.business.MeasureTypeEnum;
import com.casic.missiles.enums.sample.CurrentSegmentEnum;
import com.casic.missiles.enums.sample.SampleStatusEnum;
import com.casic.missiles.enums.workbench.MessageSourceModuleEnum;
import com.casic.missiles.enums.workbench.MessageTypeEnum;
import com.casic.missiles.exception.BusinessException;
import com.casic.missiles.mapper.business.BusinessCertificateReportMapper;
import com.casic.missiles.mapper.business.BusinessLabExecutiveInfoMapper;
import com.casic.missiles.mapper.business.BusinessOrderSampleRelationMapper;
import com.casic.missiles.mapper.customer.CustomerSampleMapper;
import com.casic.missiles.mapper.meter.MeterOrganizeMapper;
import com.casic.missiles.mapper.meter.MeterStaffMapper;
import com.casic.missiles.mapper.sys.UserInfoMapper;
import com.casic.missiles.mapper.workbench.WorkbenchRemindMessageMapper;
import com.casic.missiles.model.business.BusinessCertificateReport;
import com.casic.missiles.model.business.BusinessLabExecutiveInfo;
import com.casic.missiles.model.business.BusinessOrderSampleRelation;
import com.casic.missiles.model.customer.CustomerSampleInfo;
import com.casic.missiles.model.meter.MeterStaff;
import com.casic.missiles.model.system.UserInfo;
import com.casic.missiles.model.workbench.WorkbenchRemindMessage;
import com.casic.missiles.service.business.IBusinessDispatchService;
import com.casic.missiles.service.system.IMessagePushService;
import com.casic.missiles.utils.DictCodeUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author cz
 */
@Service
@Slf4j
@AllArgsConstructor
public class IBusinessDispatchServiceImpl extends ServiceImpl<BusinessOrderSampleRelationMapper, BusinessOrderSampleRelation> implements IBusinessDispatchService, SampleStatusEnum, CurrentSegmentEnum, MeasureTypeEnum {
    private final BusinessOrderSampleRelationMapper orderSampleRelationMapper;
    private WorkbenchRemindMessageMapper remindMessageMapper;
    private CustomerSampleMapper customerSampleMapper;
    private final BusinessCertificateReportMapper certificateReportMapper;
    private final BusinessLabExecutiveInfoMapper labExecutiveInfoMapper;
    private final IBaseExportService iBaseExportService;
    private final MeterOrganizeMapper meterOrganizeMapper;
    private final MeterStaffMapper meterStaffMapper;
    private final UserInfoMapper userInfoMapper;
    private final IMessagePushService messagePushService;

    /**
     * 终止、回退、收入、归还、催办按钮
     * 列表返回只需要控制已收入回退按钮显示的权限即可，其中回退在没有任何实验室进行的情况，可以进行设备的回退
     */
    @Override
    public Page<DeviceDispatchVO> listPage(Page<DeviceDispatchVO> page, DeviceDispatchDTO request) {
        //查询委托书和样品关联表中的各状态的样品
        Page<DeviceDispatchVO> dispatchVoPage = orderSampleRelationMapper.getSampleListByStatus(page, request);
        log.info("设备收发-当前查询样品状态为：{}", request.getSampleStatus());
        List<DeviceDispatchVO> records = dispatchVoPage.getRecords();
        if (CollectionUtils.isEmpty(records)) {
            return new Page<>();
        }
        doPopulateDispatch(records, request);
        return dispatchVoPage;
    }

    /**
     * 分发列表填充
     */
    private void doPopulateDispatch(List<DeviceDispatchVO> dispatchVOPage, DeviceDispatchDTO request) {
        dispatchVOPage.forEach(
                dispatchVO -> {
                    dispatchVO.setIsSelfMeasure(true);
                    Long orderId = dispatchVO.getOrderId();
                    Long sampleId = dispatchVO.getSampleId();
                    String sampleStatus = dispatchVO.getSampleStatus();
                    //先过滤超期状态下的外包
                    if (!StringUtils.isEmpty(request.getSampleStatus()) && BE_OVERDUE.equals(request.getSampleStatus()) && notSelfMeasure(dispatchVO)) {
                        return;
                    }
                    switch (sampleStatus) {
                        //待分发状态，当前检定环节:待分配，已出具证书：无，出具证书总数:无
                        case TO_HANDOUT:
                            doDispatchVoPopulation(dispatchVO, sampleId, orderId, TO_HANDOUT);
                            break;
                        //检测中状态，当前检定环节:具体实验室，已出具证书：查询证书报告表，证书总数：具体实验室
                        case IN_MEASURE:
                            doDispatchVoPopulation(dispatchVO, sampleId, orderId, IN_MEASURE);
                            break;
                        //检测完状态，当前检定环节:完成，已出具证书：无，出具证书总数:无
                        case MEASURE_COMPLETE:
                            doDispatchVoPopulation(dispatchVO, sampleId, orderId, MEASURE_COMPLETE);
                            break;
                        case TO_GIVE_BACK:
                            doDispatchVoPopulation(dispatchVO, sampleId, orderId, TO_GIVE_BACK);
                            break;
                        case GIVE_BACK_COMPLETE:
                            doDispatchVoPopulation(dispatchVO, sampleId, orderId, GIVE_BACK_COMPLETE);
                            break;
                        //超期样品(即检测超期，未在应检完时间检完),当前检定环节:待分配/具体实验室，已出具证书：查询证书报告表(具体实验室)，出具证书总数：具体实验室
                        case BE_OVERDUE:
                            HandOutLabExecutiveDTO overLabExecutiveDTO = getHandOutLabExecutiveDTO(orderId, sampleId);
                            Long deptId = Optional.of(overLabExecutiveDTO.getMeasureDeptId()).orElse(null);
                            dispatchVO.setAlreadyCertifications(getAlreadyCertificateNum(dispatchVO, deptId));
                            dispatchVO.setRequireCertifications(overLabExecutiveDTO.getRequireCertifications());
                            // 判断样品是完成或接收状态，直接显示即可
                            if (checkSampleFinishStatus(dispatchVO)) {
                                return;
                            }
                            dispatchVO.setCurrentSegment(overLabExecutiveDTO.getDeptName());
                            break;
                        default:
                            break;
                    }
                }
        );
    }

    @Override
    public void exportSampleDispatchList(DeviceDispatchDTO request, HttpServletResponse response) {
        try {
            Page<DeviceDispatchVO> deviceDispatchVOPage;
            if (!CollectionUtils.isEmpty(request.getIds())) {
                initDeviceDispatchDTOEmpty(request);
            } else {
                request.setIds(null);
            }
            Page<DeviceDispatchVO> page = PageFactory.defaultPage();
            page.setCurrent(1);
            page.setSearchCount(false);
            page.setSize(Integer.MAX_VALUE);
            deviceDispatchVOPage = listPage(page, request);
            iBaseExportService.exportExcel(response, DeviceDispatchVO.class, deviceDispatchVOPage.getRecords(), ExportEnum.DISPATCH_DATA.getSheetName());
        } catch (Exception e) {
            log.error("样品导出出现异常，异常信息为{}", e);
        }
    }


    /**
     * 根据sampleId，orderId,进行状态更新
     */
    @Override
    @Transactional
    public ReturnDTO batchStatusChange(List<DeviceStatusChangeDTO> deviceReceiveDTOList) {
        Boolean updateFlag = true;
        for (DeviceStatusChangeDTO deviceStatusChangeDTO : deviceReceiveDTOList) {
            updateFlag &= statusChange(deviceStatusChangeDTO);
        }
        if (updateFlag) {
            return ReturnUtil.success();
        }
        throw new BusinessException(BusinessExceptionEnum.HANDLE_FAILED);
    }

    /**
     * 根据sampleId，orderId,进行状态更新
     */
    @Transactional
    public Boolean statusChange(DeviceStatusChangeDTO deviceReceiveDTO) {
        //涉及实际送达时间，需判断前置为待收入转入的
        boolean incomeStatusFlag = incomeStatusChange(deviceReceiveDTO);
        //涉及归还时间
        boolean giveBackStatusFlag = giveBackStatusChange(deviceReceiveDTO);
        //完成状态
        toGiveBackStatusChange(deviceReceiveDTO);
        //状态变更
        Integer updateFlag = this.statusChangeUpdator(deviceReceiveDTO, false);
        if (updateFlag > 0 && incomeStatusFlag && giveBackStatusFlag) {
            return true;
        }
        throw new BusinessException(BusinessExceptionEnum.HANDLE_FAILED);
    }


    @Override
    @Transactional
    public ReturnDTO statusBatchChange(DeviceBatchStatusChangeDTO deviceBatchStatusChangeDTO) {
        boolean batchUpdateFlag = true;
        for (DeviceStatusChangeDTO deviceStatusChangeDTO : deviceBatchStatusChangeDTO.getDeviceStatusChangeDTOS()) {
            Assert.isFalse(Objects.isNull(deviceStatusChangeDTO.getOrderId()) || Objects.isNull(deviceStatusChangeDTO.getSampleId()), () -> {
                throw new BusinessException(BusinessExceptionEnum.ID_NULL);
            });
            deviceStatusChangeDTO.setStatus(deviceBatchStatusChangeDTO.getStatus());
            deviceStatusChangeDTO.setReason(deviceBatchStatusChangeDTO.getReason());
            batchUpdateFlag &= statusChange(deviceStatusChangeDTO);
        }
        if (batchUpdateFlag) {
            return ReturnUtil.success();
        }
        throw new BusinessException(BusinessExceptionEnum.HANDLE_FAILED);
    }

    /**
     * 终止操作，不仅更新状态，同时进行实验室状态原因的更新
     */
    @Override
    @Transactional
    public ReturnDTO forcedTerminate(List<DeviceStatusChangeDTO> deviceReceiveDTO) {
        boolean batchUpdateFlag = true;
        for (DeviceStatusChangeDTO deviceStatusChangeDTO : deviceReceiveDTO) {
            Integer updateFlag = this.statusChangeUpdator(deviceStatusChangeDTO, true);
            //实验室状态数据的更新
            updateLabExecutiveInfo(deviceStatusChangeDTO, MeasureStatusEnum.TERMINATED);
            batchUpdateFlag &= updateFlag > 0;
        }
        if (batchUpdateFlag) {
            return ReturnUtil.success();
        }
        throw new BusinessException(BusinessExceptionEnum.HANDLE_FAILED);
    }


    /**
     * 1、查询是否绑定
     * 2、未绑定进行绑定，已绑定抛出绑定异常
     */
    @Override
    @Transactional
    public ReturnDTO bindLabel(LabelBindDTO labelBindDTO) throws Exception {
        //查询委托书和样品关联表中的各状态的样品
        Long id = orderSampleRelationMapper.isBindLabel(labelBindDTO.getLabel());
        if (ObjectUtils.isEmpty(id)) {
            Integer updateFlag = orderSampleRelationMapper.bindLabel(labelBindDTO);
            if (updateFlag > 0) {
                return ReturnUtil.success();
            }
            throw new BusinessException(BusinessExceptionEnum.HANDLE_FAILED);
        }
        throw new BusinessException(BusinessExceptionEnum.LABEL_ALREADY_BIND);
    }

    /**
     * 进行已收入分页的当前环节回填、出具证书回填
     */
    private void doDispatchVoPopulation(DeviceDispatchVO dispatchVO, Long sampleId, Long orderId, String currentSegment) {
        HandOutLabExecutiveDTO handOutLabExecutiveDTO = getHandOutLabExecutiveDTO(orderId, sampleId);
        Integer measureNumberStatus = labExecutiveInfoMapper.getMeasureNumberStatus(orderId, sampleId);
        //证书，当前环节的回填
        if (!Objects.isNull(handOutLabExecutiveDTO)) {
            dispatchVO.setRequireCertifications(handOutLabExecutiveDTO.getRequireCertifications());
            dispatchVO.setCurrentSegment(handOutLabExecutiveDTO.getDeptName());
            Long measureDeptId = handOutLabExecutiveDTO.getMeasureDeptId();
            dispatchVO.setAlreadyCertifications(getAlreadyCertificateNum(dispatchVO, measureDeptId));
        } else {
            dispatchVO.setAlreadyCertifications(0);
            dispatchVO.setRequireCertifications(ObjectUtils.isEmpty(measureNumberStatus) ? 0 : measureNumberStatus);
        }
        //处于检测中、检测完、待检测的实验室大于0，不可以进行回退,否则可以进行回退
        if (!ObjectUtils.isEmpty(measureNumberStatus) && measureNumberStatus > 0) {
            dispatchVO.setFallbackState(0);
        } else {
            dispatchVO.setFallbackState(1);
        }
        if (TO_HANDOUT.equals(currentSegment)) {
            dispatchVO.setCurrentSegment(TO_ALLOCATE);
        }
        if (MEASURE_COMPLETE.equals(currentSegment) || TO_GIVE_BACK.equals(currentSegment) || GIVE_BACK_COMPLETE.equals(currentSegment)) {
            dispatchVO.setCurrentSegment(COMPLETE);
            //产品：完成状态的不展示证书出具信息
            dispatchVO.setRequireCertifications(null);
            dispatchVO.setAlreadyCertifications(null);
        }
    }

    private void updateLabExecutiveInfo(DeviceStatusChangeDTO deviceStatusChangeDTO, String measureStatus) {
        QueryWrapper<BusinessLabExecutiveInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("sample_id", deviceStatusChangeDTO.getSampleId());
        queryWrapper.eq("order_id", deviceStatusChangeDTO.getOrderId());
        queryWrapper.and(QueryWrapper -> QueryWrapper.eq("measure_status", MeasureStatusEnum.TO_ALLOCATE)
                .or().eq("measure_status", MeasureStatusEnum.TO_MEASURE)
                .or().eq("measure_status", MeasureStatusEnum.IN_MEASURE));
        BusinessLabExecutiveInfo businessLabExecutiveInfo = new BusinessLabExecutiveInfo();
        businessLabExecutiveInfo.setMeasureStatus(measureStatus);
        businessLabExecutiveInfo.setRemark(deviceStatusChangeDTO.getReason());
        labExecutiveInfoMapper.update(businessLabExecutiveInfo, queryWrapper);
    }


    @Override
    public ReturnDTO remindWorker(DeviceStatusChangeDTO deviceStatusChangeDTO) {
        BusinessLabExecutiveInfo labExecutiveInfo = getLabExecutiveInfo(deviceStatusChangeDTO);
        if (labExecutiveInfo != null) {
            WorkbenchRemindMessage remindMessage = initWorkbenchRemindMessage(labExecutiveInfo);
            int remindMessageAddFlag = remindMessageMapper.insert(remindMessage);
            if (remindMessageAddFlag > 0) {
                Boolean sendFlag = messagePushService.pushToUser(remindMessage);
                return ReturnUtil.success();
            }
        } else {
            throw new BusinessException(BusinessExceptionEnum.URGER_IS_EMPTY);
        }
        throw new BusinessException(BusinessExceptionEnum.HANDLE_FAILED);
    }

    private BusinessLabExecutiveInfo getLabExecutiveInfo(DeviceStatusChangeDTO deviceStatusChangeDTO) {
        QueryWrapper<BusinessLabExecutiveInfo> queryWrapper = new QueryWrapper<BusinessLabExecutiveInfo>();
        queryWrapper.eq("sample_id", deviceStatusChangeDTO.getSampleId());
        queryWrapper.eq("order_id", deviceStatusChangeDTO.getOrderId());
        queryWrapper.and(QueryWrapper -> QueryWrapper.eq("measure_status", MeasureStatusEnum.TO_ALLOCATE)
                .or().eq("measure_status", MeasureStatusEnum.TO_MEASURE)
                .or().eq("measure_status", IN_MEASURE));
        List<BusinessLabExecutiveInfo> businessLabExecutiveInfo = labExecutiveInfoMapper.selectList(queryWrapper);
        return businessLabExecutiveInfo.isEmpty() ? null : businessLabExecutiveInfo.get(0);
    }

    /**
     * 消息催办
     * 1、待办人为当前实验室工作人员，
     * 2、业务主键id业务主键将要跳转的页面id
     * 3、当前工作人员id的或部门的id
     * 4、创建人为当前催办人
     * 5、消息类型为超出检定时间催办提醒
     * 6、消息主题为代办人或者待办部门
     * 7、消息标题待办提醒，内容为样品
     */
    public WorkbenchRemindMessage initWorkbenchRemindMessage(BusinessLabExecutiveInfo labExecutiveInfo) {
        WorkbenchRemindMessage remindMessage = new WorkbenchRemindMessage();
        remindMessage.setRemindDeptId(labExecutiveInfo.getMeasureDeptId());
        remindMessage.setMessageType(MessageTypeEnum.OVERTIME_MEASURE.getCode());
        remindMessage.setMessageSourceModule(MessageSourceModuleEnum.BUSINESS.getCode());
        remindMessage.setMessageTitle(MessageTypeEnum.OVERTIME_MEASURE.getValue());
        //检测人不为空，且检测状态不为待分配消息催办到我的检测
        if (!Objects.isNull(labExecutiveInfo.getMeasurePersonId()) && !MeasureStatusEnum.TO_ALLOCATE.equals(labExecutiveInfo.getMeasureStatus())) {
            MeterStaff meterStaff = meterStaffMapper.selectById(labExecutiveInfo.getMeasurePersonId());
            if (ObjectUtils.isEmpty(meterStaff)) {
                throw new BusinessException(BusinessExceptionEnum.URGER_IS_EMPTY);
            }
            QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
            wrapper.eq("account", meterStaff.getAccount());
            UserInfo userInfo = userInfoMapper.selectOne(wrapper);
            if (ObjectUtil.isEmpty(userInfo)) {
                throw new BusinessException(BusinessExceptionEnum.NOT_FOUND_USER_INFO);
            }
            remindMessage.setRemindId(userInfo.getId());
            remindMessage.setMessageTopic("我的检测");
        } else {
            remindMessage.setMessageTopic("部门检测");
            //催办给部门组长(计量组织表负责人)
            Long directorId = null;
            if (Objects.nonNull(labExecutiveInfo.getMeasureDeptId())) {
                directorId = meterOrganizeMapper.selectDeptDirectorByDeptId(labExecutiveInfo.getMeasureDeptId());
            }
            if (Objects.nonNull(directorId)) {
                remindMessage.setRemindId(directorId);
            } else {
                throw new BusinessException(BusinessExceptionEnum.UNABLE_TO_URGE);
            }
        }
        CustomerSampleInfo customerSampleInfo = customerSampleMapper.selectById(labExecutiveInfo.getSampleId());
        if (null != customerSampleInfo) {
            remindMessage.setMessageTitle(customerSampleInfo.getSampleName() + "样品检测已经超出期限");
            remindMessage.setMessageContent(customerSampleInfo.getSampleNo() + customerSampleInfo.getSampleName());
            remindMessage.setBusinessCode(customerSampleInfo.getSampleNo());
        }
        remindMessage.setBusinessId(labExecutiveInfo.getSampleId());
        remindMessage.setRelationBusinessId(labExecutiveInfo.getOrderId());
        AuthUser authUser = ShiroKit.getUser();
        remindMessage.setCreateUser(authUser.getId());
        remindMessage.setCreateUserName(authUser.getName());
        return remindMessage;
    }

    private Integer getAlreadyCertificateNum(DeviceDispatchVO dispatchVO, Long measureDeptId) {
        Long aLong = certificateReportMapper.selectCount(getCertificateReportWrapper(dispatchVO, measureDeptId));
        return aLong.intValue();
    }

    private HandOutLabExecutiveDTO getHandOutLabExecutiveDTO(Long orderId, Long sampleId) {
        List<HandOutLabExecutiveDTO> labExecutiveList = labExecutiveInfoMapper.selectListByInMeasureStatus(orderId, sampleId);
        if (CollectionUtils.isEmpty(labExecutiveList)) {
            log.info("任务分发-检测中状态不存在当前进行检测的实验室，orderId：{}，sampleId：{}", orderId, sampleId);
            return null;
        }
        Optional<HandOutLabExecutiveDTO> handOutLabExecutiveDTOOptional = labExecutiveList.stream().findFirst();
        return handOutLabExecutiveDTOOptional.orElse(null);
    }

    /**
     * 构建证书的查询条件
     */
    private QueryWrapper<BusinessCertificateReport> getCertificateReportWrapper(DeviceDispatchVO dispatchVO, Long
            deptId) {
        QueryWrapper<BusinessCertificateReport> wrapper = new QueryWrapper<>();
        wrapper.eq("order_id", dispatchVO.getOrderId());
        wrapper.eq("sample_id", dispatchVO.getSampleId());
        wrapper.eq("measure_dept_id", deptId);
        return wrapper;
    }

    /**
     * 更新检测完成后，执行当前正在进行数据
     */
    private Integer statusChangeUpdator(DeviceStatusChangeDTO statusChangeDTO, Boolean terminateFlag) {
        QueryWrapper<BusinessOrderSampleRelation> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id", statusChangeDTO.getOrderId());
        queryWrapper.eq("sample_id", statusChangeDTO.getSampleId());
        if (terminateFlag) {
            //若是终止，需要对应待分发、检测中、检测完三个状态的变更
            queryWrapper.and(wrapper -> wrapper.eq("sample_status", TO_HANDOUT).or().eq("sample_status", IN_MEASURE).or().eq("sample_status", MEASURE_COMPLETE));
        }
        BusinessOrderSampleRelation businessOrderSampleRelation = new BusinessOrderSampleRelation();
        businessOrderSampleRelation.setSampleStatus(statusChangeDTO.getStatus());
        //回退操作更新实验室数据状态
        if ("1".equals(statusChangeDTO.getStatus())) {
            updateLabExecutiveInfo(statusChangeDTO, MeasureStatusEnum.TERMINATED);
        }
        return this.orderSampleRelationMapper.update(businessOrderSampleRelation, queryWrapper);
    }

    /**
     * 判断不是自检,即外包和外检，进行环节设定
     */
    private boolean notSelfMeasure(DeviceDispatchVO dispatchVO) {
        if (!ObjectUtils.isEmpty(dispatchVO.getMeasureType())) {
            if (!INSIDE_MEASURE.equals(String.valueOf(dispatchVO.getMeasureType()))) {
                String currentSegment = OUT_UNDERTAKE;
                dispatchVO.setCurrentSegment(currentSegment);
                dispatchVO.setIsSelfMeasure(false);
                return true;
            }
        }
        return false;
    }

    /**
     * 其他条件的置为空
     */
    private void initDeviceDispatchDTOEmpty(DeviceDispatchDTO request) {
        request.setSampleName(null);
        request.setSampleNo(null);
        request.setOrderNo(null);
        request.setCustomerNo(null);
        request.setIsUrgent(null);
        request.setSampleBelong(null);
        request.setSampleStatus(null);
        request.setStartTime(null);
        request.setEndTime(null);
    }

    /**
     * 判断样品是完成或接收状态，进行当前阶段环节的设置
     */
    private Boolean checkSampleFinishStatus(DeviceDispatchVO dispatchVO) {
        if (TO_RECEIVE.equals(dispatchVO.getSampleStatus())) {
            dispatchVO.setCurrentSegment(TO_INCOME);
            return true;
        }
        if (TO_HANDOUT.equals(dispatchVO.getSampleStatus())) {
            dispatchVO.setCurrentSegment(TO_ALLOCATE);
            return true;
        }
        return false;
    }

    private boolean incomeStatusChange(DeviceStatusChangeDTO statusChangeDTO) {
        if (statusChangeDTO.getStatus().equals(TO_HANDOUT)) {
            QueryWrapper<BusinessOrderSampleRelation> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("order_id", statusChangeDTO.getOrderId());
            queryWrapper.eq("sample_id", statusChangeDTO.getSampleId());
            List<BusinessOrderSampleRelation> orderSampleRelationList = this.orderSampleRelationMapper.selectList(queryWrapper);
            Optional<BusinessOrderSampleRelation> orderSampleRelationOptional = orderSampleRelationList.stream().findFirst();
            if (orderSampleRelationOptional.isPresent()) {
                BusinessOrderSampleRelation businessOrderSampleRelation = orderSampleRelationOptional.get();
                if (businessOrderSampleRelation.getSampleStatus().equals(TO_RECEIVE)) {
                    BusinessOrderSampleRelation businessOrderSample = new BusinessOrderSampleRelation();
                    businessOrderSample.setRealDeliverTime(DateUtil.format(new Date(), "yyyy-MM-dd"));
                    int updateFlag = this.orderSampleRelationMapper.update(businessOrderSample, queryWrapper);
                    return updateFlag > 0 ? true : false;
                }
            }
        }
        return true;
    }

    /**
     * 是归还状态，填写归还时间
     *
     * @param statusChangeDTO
     * @return
     */
    private boolean giveBackStatusChange(DeviceStatusChangeDTO statusChangeDTO) {
        if (statusChangeDTO.getStatus().equals(GIVE_BACK_COMPLETE)) {
            QueryWrapper<BusinessOrderSampleRelation> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("order_id", statusChangeDTO.getOrderId());
            queryWrapper.eq("sample_id", statusChangeDTO.getSampleId());
            BusinessOrderSampleRelation businessOrderSample = new BusinessOrderSampleRelation();
            businessOrderSample.setReturnTime(DateUtil.format(new Date(), "yyyy-MM-dd"));
            int updateFlag = this.orderSampleRelationMapper.update(businessOrderSample, queryWrapper);
            return updateFlag > 0 ? true : false;
        }
        return true;
    }

    private void toGiveBackStatusChange(DeviceStatusChangeDTO statusChangeDTO) {
        if (statusChangeDTO.getStatus().equals(TO_GIVE_BACK)) {
            QueryWrapper<BusinessOrderSampleRelation> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("order_id", statusChangeDTO.getOrderId());
            queryWrapper.eq("sample_id", statusChangeDTO.getSampleId());
            List<BusinessOrderSampleRelation> orderSampleRelationList = this.orderSampleRelationMapper.selectList(queryWrapper);
            Optional<BusinessOrderSampleRelation> orderSampleRelationOptional = orderSampleRelationList.stream().findFirst();
            if (orderSampleRelationOptional.isPresent()) {
                BusinessOrderSampleRelation businessOrderSampleRelation = orderSampleRelationOptional.get();
                if (businessOrderSampleRelation.getSampleStatus().equals(TO_HANDOUT)
                        || businessOrderSampleRelation.getSampleStatus().equals(IN_MEASURE)
                        || businessOrderSampleRelation.getSampleStatus().equals(MEASURE_COMPLETE)) {
                    if (statusChangeDTO.getStatus().equals(COMPLETE)) {
                        this.updateLabExecutiveInfo(statusChangeDTO, MeasureStatusEnum.MEASURE_COMPLETE);
                    }
                }
            }
        }
    }


}
