package cn.estsh.i3plus.ext.mes.pcn.apiservice.serviceimpl.busi;

import cn.estsh.i3plus.ext.mes.pcn.api.busi.IMesShippingLoadingCheckService;
import cn.estsh.i3plus.ext.mes.pcn.api.busi.IMesSortShippingCheckService;
import cn.estsh.i3plus.ext.mes.pcn.apiservice.aspect.MonitorLog;
import cn.estsh.i3plus.ext.mes.pcn.pojo.constant.MesCommonConstant;
import cn.estsh.i3plus.ext.mes.pcn.pojo.model.MesShippingLoadingCheckModel;
import cn.estsh.i3plus.ext.mes.pcn.pojo.util.MesPcnExtConstWords;
import cn.estsh.i3plus.platform.common.convert.ConvertBean;
import cn.estsh.i3plus.platform.common.tool.TimeTool;
import cn.estsh.i3plus.pojo.base.bean.DdlPackBean;
import cn.estsh.i3plus.pojo.base.enumutil.CommonEnumUtil;
import cn.estsh.i3plus.pojo.base.tool.DdlPreparedPack;
import cn.estsh.i3plus.pojo.base.util.StringUtil;
import cn.estsh.i3plus.pojo.mes.bean.MesJisShipping;
import cn.estsh.i3plus.pojo.mes.bean.MesPartShippingGroup;
import cn.estsh.i3plus.pojo.mes.bean.shipping.MesLoadingList;
import cn.estsh.i3plus.pojo.mes.bean.shipping.MesLoadingListDetail;
import cn.estsh.i3plus.pojo.mes.bean.shipping.MesShippingOrderManagement;
import cn.estsh.i3plus.pojo.mes.repository.*;
import cn.estsh.i3plus.pojo.mes.util.MesExtEnumUtil;
import cn.estsh.impp.framework.boot.exception.ImppBusiException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description :
 * @Reference :
 * @Author :
 * @CreateDate : 2024-04-26 15:38
 * @Modify:
 **/
@Service
@Slf4j
public class MesShippingLoadingCheckService implements IMesShippingLoadingCheckService {

    @Autowired
    private MesLoadingListRepository vehiclesOrderRepository;
    @Autowired
    private MesLoadingListDetailRepository vehiclesOrderDetailRepository;

    @Autowired
    private MesShippingOrderManagementRepository shippingOrderManagementRepository;
    @Autowired
    private MesShippingOrderManagementDetailRepository shippingOrderManagementDetailRepository;
    @Autowired
    private MesJisShippingRepository jisShippingRepository;

    @Autowired
    private MesPartShippingGroupService mesPartShippingGroupService;

    @Autowired
    private IMesSortShippingCheckService mesSortShippingCheckService;


    @Override
    public MesShippingLoadingCheckModel doLoadingOrderNoQuery(MesLoadingList loadingList) {

        //校验装车单
        MesLoadingList loadingListResult = checkLoadingList(loadingList.getOrderCode(), loadingList.getOrganizeCode(),loadingList.getIsPass(),loadingList.getModifyUser());
        if(Objects.isNull(loadingListResult)){
            return null;
        }
        //若生成装车单，则一定有装车单明细
        DdlPackBean orderDetailPackBean = DdlPackBean.getDdlPackBean(loadingList.getOrganizeCode());
        DdlPreparedPack.getNumEqualPack(loadingListResult.getId(), "pid", orderDetailPackBean);
        DdlPreparedPack.getNumberSmallerPack(MesExtEnumUtil.LOADING_ORDER_DETAIL_SHIPPING_STATUS.CLOSE.getValue(),"status",orderDetailPackBean);
        DdlPreparedPack.getOrderByPack(new Object[]{CommonEnumUtil.ASC_OR_DESC.ASC.getValue()}, new String[]{"seq"}, orderDetailPackBean);
        List<MesLoadingListDetail> detailList = vehiclesOrderDetailRepository.findByHqlWhere(orderDetailPackBean);

        //是否逆转
        if (Objects.equals(loadingListResult.getIsReverse(), MesCommonConstant.TRUE_INTEGER)) {
            // 逆转
            for (int i = 0; i < detailList.size(); i += loadingListResult.getReverseQuantity()) {
                if (i + loadingListResult.getReverseQuantity() - 1 < detailList.size()) {
                    Collections.reverse(detailList.subList(i, i + loadingListResult.getReverseQuantity()));
                }
            }
        }

        MesShippingLoadingCheckModel model = new MesShippingLoadingCheckModel();
        Long count = detailList.stream().filter(k -> k.getStatus() == MesExtEnumUtil.LOADING_ORDER_DETAIL_SHIPPING_STATUS.SHIPPINGED.getValue() || k.getStatus() == MesExtEnumUtil.LOADING_ORDER_DETAIL_SHIPPING_STATUS.SKIP.getValue()).count();
        model.setIsScanCount(count.intValue());
        model.setOrderCode(loadingList.getOrderCode());

        //查询最近扫描完成的装车单号
        DdlPackBean recentlyOrderPackBean = DdlPackBean.getDdlPackBean(loadingList.getOrganizeCode());
        DdlPreparedPack.getNumEqualPack(MesExtEnumUtil.MES_LOADING_STATUS.SCANNED.getValue(), "status", recentlyOrderPackBean);
        DdlPreparedPack.getOrderByPack(new Object[]{CommonEnumUtil.ASC_OR_DESC.DESC.getValue()}, new String[]{"modifyDatetime"}, recentlyOrderPackBean);
        MesLoadingList recentlyVehiclesOrder = vehiclesOrderRepository.getByProperty(recentlyOrderPackBean);

        if (!StringUtils.isEmpty(recentlyVehiclesOrder)) {

            model.setRecentlyScanVehiclesOrder(recentlyVehiclesOrder.getOrderCode());
        }

        detailList.forEach(k -> {
            if (k.getStatus() == MesExtEnumUtil.LOADING_ORDER_DETAIL_SHIPPING_STATUS.SHIPPINGED.getValue() || k.getStatus() == MesExtEnumUtil.LOADING_ORDER_DETAIL_SHIPPING_STATUS.SKIP.getValue()){
                k.setScanSn(k.getStatus() == MesExtEnumUtil.LOADING_ORDER_DETAIL_SHIPPING_STATUS.SKIP.getValue()?"":k.getShippingCode());
                k.setTempStatus(MesCommonConstant.TRUE_INTEGER);
                k.setTempStatusVal(k.getStatus() == MesExtEnumUtil.LOADING_ORDER_DETAIL_SHIPPING_STATUS.SKIP.getValue()?MesPcnExtConstWords.SHIP_PASS:"扫描完成");
            }
        });

        model.setDetailList(detailList);

        return model;
    }

    @Override
    public MesLoadingList queryLoadingOrderNoByAutoPushOrder(String shippingGroupNo, String org) {


        List<Integer> statusList = new ArrayList<>();
        statusList.add(MesExtEnumUtil.MES_LOADING_STATUS.CREATE.getValue());
        statusList.add(MesExtEnumUtil.MES_LOADING_STATUS.PUBLISH.getValue());
        statusList.add(MesExtEnumUtil.MES_LOADING_STATUS.CREATE_ASN.getValue());
        statusList.add(MesExtEnumUtil.MES_LOADING_STATUS.LOADING.getValue());

        //查询最近需要扫描的装车单号
        DdlPackBean orderPackBean = DdlPackBean.getDdlPackBean(org);
        DdlPreparedPack.getInPackList(statusList, "status", orderPackBean);
        DdlPreparedPack.getOrderByPack(new Object[]{CommonEnumUtil.ASC_OR_DESC.ASC.getValue()}, new String[]{"seq"}, orderPackBean);
        MesLoadingList loadingList = vehiclesOrderRepository.getByProperty(orderPackBean);

        return loadingList;
    }

    @Override
    public MesShippingLoadingCheckModel saveVehiclesOrderAndDetail(MesShippingLoadingCheckModel model, String organizeCode, String userInfo) {

        //校验装车单
        DdlPackBean orderPackBean = DdlPackBean.getDdlPackBean(organizeCode);
        DdlPreparedPack.getStringEqualPack(model.getOrderCode(), "orderCode", orderPackBean);
        MesLoadingList loadingList = vehiclesOrderRepository.getByProperty(orderPackBean);
        if (StringUtils.isEmpty(loadingList)) {
            throw new ImppBusiException(String.format("【%s】此装车单不存在，请检查数据！", model.getOrderCode()));
        }
        //MesLoadingList loadingList = checkLoadingList(model.getOrderCode(), organizeCode,model.getIsPass(),userInfo);

        //根据扫描的发运单以及前端传的发运单明细，进行匹配，若没有找到扫描的发运单，则提示扫描的发运单号不在此装车单中，请检查数据！。
        //1 跳过
        if(!Objects.isNull(model.getIsPass()) && Objects.equals(MesPcnExtConstWords.ONE,model.getIsPass())){
            Optional<MesLoadingListDetail> loadingListDetailOptional = model.getDetailList().stream().filter(t -> !Objects.equals(t.getTempStatus(), MesCommonConstant.TRUE_INTEGER)).findFirst();
            if(loadingListDetailOptional.isPresent()){
                MesLoadingListDetail loadingListDetail = loadingListDetailOptional.get();
                updateLoadingListDetail(model, userInfo, loadingList, loadingListDetail,MesPcnExtConstWords.SHIP_PASS,MesExtEnumUtil.LOADING_ORDER_DETAIL_SHIPPING_STATUS.SKIP.getValue(),userInfo);
            }else{
                throw new ImppBusiException(String.format("【%s】明细已全部扫描完成，请检查数据！", loadingList.getOrderCode()));
            }
        }else{
            //校验发运单是否存在
            checkLoadingList(model, organizeCode, loadingList);
            //查询零件发运组
            MesPartShippingGroup loadingShippingGroup = getMesPartShippingGroup(organizeCode, loadingList.getPartShippingGroupCode());
            final boolean isFirstInstall = mesPartShippingGroupService.isFirstInstall(loadingShippingGroup, loadingList);
            boolean scanflg = false;
            for (MesLoadingListDetail loadingListDetail : model.getDetailList()) {
                if (loadingListDetail.getShippingCode().equals(model.getShippingCode())) {
                    if (Objects.equals(loadingListDetail.getTempStatus(), MesCommonConstant.TRUE_INTEGER)) {
                        throw new ImppBusiException(String.format("【%s】此发运单已经%s，请检查数据！", model.getShippingCode(),loadingListDetail.getTempStatusVal()));
                    }
                    DdlPackBean packBean = DdlPackBean.getDdlPackBean(organizeCode);
                    DdlPreparedPack.getStringEqualPack(loadingListDetail.getShippingCode(),"shippingCode",packBean);
                    MesShippingOrderManagement orderManagement = shippingOrderManagementRepository.getByProperty(packBean);
                    if (orderManagement == null) {
                        throw new ImppBusiException(String.format("发运单【%s】信息不存在，请检查数据！", loadingListDetail.getShippingCode()));
                    }
                    //查询零件发运组
                    MesPartShippingGroup shippingGroup = getMesPartShippingGroup(organizeCode, orderManagement.getShippingGroupCode());

                    //校验发运单明细顺序
                    if(!StringUtils.isEmpty(shippingGroup.getIsEnableLoadingFailSafe()) && CommonEnumUtil.VALID == shippingGroup.getIsEnableLoadingFailSafe()){
                        List<MesLoadingListDetail> shippingGroupLoading = new ArrayList<>();
                        for (MesLoadingListDetail detail : model.getDetailList()) {
                            if (detail.getShippingId() != null) {
                                MesShippingOrderManagement shippingOrder = shippingOrderManagementRepository.getById(detail.getShippingId());
                                if (shippingOrder != null && Objects.equals(shippingOrder.getShippingGroupCode(), shippingGroup.getShippingGroupCode())) {
                                    shippingGroupLoading.add(detail);
                                }
                            }
                        }
                        Optional<MesLoadingListDetail> detail = shippingGroupLoading.stream().filter(k -> k.getShippingCode().compareTo(loadingListDetail.getShippingCode()) < 0 && !Objects.equals(k.getTempStatus(), MesCommonConstant.TRUE_INTEGER)).findFirst();
                        if(detail.isPresent()){
                            throw new ImppBusiException(String.format("装车单【%s】启用明细顺序防错，发运单【%s】前还有未扫描的发运单，请检查数据！", loadingList.getOrderCode(), model.getShippingCode()));
                        }
                    }

                    //判断是否需要排序校验 默认排序则需要校验
                    if (!StringUtils.isEmpty(loadingList.getScanSeqWay()) && loadingList.getScanSeqWay() == MesExtEnumUtil.SHIPPING_GROUP_SCAN_CONFIRM_SEQ_MODE.SHIPPING_GROUP_SCAN_CONFIRM_SEQ_MODE_10.getValue()) {
                        //获取明细中最小的

                        long minSeq = model.getDetailList().stream().filter(k -> StringUtils.isEmpty(k.getScanSn()) && !Objects.equals(k.getTempStatus(), MesCommonConstant.TRUE_INTEGER)).mapToLong(MesLoadingListDetail::getSeq).min().getAsLong();
                        //若扫描的不是最小顺序 则报错
                        if (minSeq != loadingListDetail.getSeq()) {
                            throw new ImppBusiException(String.format("【%s】此发运单扫描顺序错误，请检查数据！", model.getShippingCode()));
                        }
                    }

                    //根据扫描的装车单找到是否先装车配置
                    //若配置为否，则查询装车单中所有的发运单是否都进行【排序发运校验】完成，若【排序发运校验】没完成，则提示，先进行排序发运校验。
                    if (!isFirstInstall) {
                        if (orderManagement == null || orderManagement.getStatus() != MesExtEnumUtil.SHIPPING_ORDER_STATUS.SHIPPED.getValue()) {
                            throw new ImppBusiException(String.format("【%s】此装车单中发运单为【%s】，还未做完【排序发运校验】，请检查数据", model.getShippingCode(), loadingListDetail.getShippingCode()));
                        }
                    }

                    //更新页面状态
                    updateLoadingListDetail(model, userInfo, loadingList, loadingListDetail,"扫描完成",MesExtEnumUtil.LOADING_ORDER_DETAIL_SHIPPING_STATUS.SHIPPINGED.getValue(),userInfo);
                    scanflg = true;
                    break;
                }
            }
            if (!scanflg) {
                throw new ImppBusiException(String.format("【%s】扫描的发运单号不在【%s】此装车单中，请检查数据！", model.getShippingCode(), model.getOrderCode()));
            }
        }

        Long count = model.getDetailList().stream().filter(k -> Objects.equals(k.getTempStatus(), MesCommonConstant.TRUE_INTEGER)).count();
        model.setIsScanCount(count.intValue());

        //全部扫描完成
        if (count.intValue() == model.getDetailList().size()) {

            //若装车单状态为创建或发布已生成ASN 则写入开始扫描时间
            if (loadingList.getStatus() == MesExtEnumUtil.MES_LOADING_STATUS.CREATE.getValue() ||
                    loadingList.getStatus() == MesExtEnumUtil.MES_LOADING_STATUS.PUBLISH.getValue() ||
                    loadingList.getStatus() == MesExtEnumUtil.MES_LOADING_STATUS.CREATE_ASN.getValue()) {
                loadingList.setStartScanTime(TimeTool.getNowTime(true));
            }
            loadingList.setEndScanTime(TimeTool.getNowTime(true));
            //装车单主表
            loadingList.setStatus(MesExtEnumUtil.MES_LOADING_STATUS.SCANNED.getValue());
            loadingList.setSystemSyncStatus(CommonEnumUtil.FALSE);
            ConvertBean.serviceModelUpdate(loadingList, userInfo);
            //不记忆的数据持久化
            if (!Objects.equals(loadingList.getIsEnableMemory(), MesCommonConstant.TRUE_INTEGER)) {
                //装车单明细
                List<MesLoadingListDetail> vehiclesOrderDetailList = model.getDetailList();
                vehiclesOrderDetailList.forEach(k -> {
                    k.setSystemSyncStatus(CommonEnumUtil.FALSE);
                    ConvertBean.serviceModelUpdate(k, userInfo);
                });

                vehiclesOrderDetailRepository.saveAll(vehiclesOrderDetailList);
            }

            List<MesShippingOrderManagement> shippingOrderList = new ArrayList<>();
            model.getDetailList().forEach(k -> {
                DdlPackBean packBean = DdlPackBean.getDdlPackBean(organizeCode);
                DdlPreparedPack.getNumEqualPack(k.getShippingId(),"id",packBean);
                MesShippingOrderManagement orderManagement = shippingOrderManagementRepository.getByProperty(packBean);
                if (orderManagement != null) {
                    orderManagement.setStatus(MesExtEnumUtil.SHIPPING_ORDER_STATUS.LOADING.getValue());
                    orderManagement.setSystemSyncStatus(CommonEnumUtil.FALSE);
                    ConvertBean.serviceModelUpdate(orderManagement, userInfo);
                    shippingOrderList.add(orderManagement);
                }
            });
            shippingOrderManagementRepository.saveAll(shippingOrderList);

            update(loadingList);
        }
        return model;
    }

    private void checkLoadingList(MesShippingLoadingCheckModel model, String organizeCode, MesLoadingList loadingList) {
        DdlPackBean orderDetailPackBean = DdlPackBean.getDdlPackBean(organizeCode);
        DdlPreparedPack.getNumEqualPack(loadingList.getId(), "pid", orderDetailPackBean);
        DdlPreparedPack.getStringEqualPack(model.getShippingCode(), "shippingCode", orderDetailPackBean);
        MesLoadingListDetail vehiclesOrderDetail = vehiclesOrderDetailRepository.getByProperty(orderDetailPackBean);
        if (StringUtils.isEmpty(vehiclesOrderDetail)) {
            throw new ImppBusiException(String.format("【%s】此发运单不存在或还未生成装车单明细，请检查数据！", model.getShippingCode()));
        }
    }

    private void updateLoadingListDetail(MesShippingLoadingCheckModel model, String userInfo, MesLoadingList loadingList, MesLoadingListDetail loadingListDetail, String tempStatusVal, Integer status,String userName) {
        if(MesExtEnumUtil.LOADING_ORDER_DETAIL_SHIPPING_STATUS.SHIPPINGED.getValue() == status){
            loadingListDetail.setScanSn(model.getShippingCode());
        }else{
            loadingListDetail.setRemark(tempStatusVal);
        }
        loadingListDetail.setTempStatus(MesCommonConstant.TRUE_INTEGER);
        loadingListDetail.setTempStatusVal(tempStatusVal);
        loadingListDetail.setStatus(status);
        //根据是否启动记忆判断 若启用记忆，则根据保存数据库
        if (Objects.equals(loadingList.getIsEnableMemory(), MesCommonConstant.TRUE_INTEGER)) {
            //若装车单状态为创建或发布已生成ASN 则写入开始扫描时间
            if (loadingList.getStatus() == MesExtEnumUtil.MES_LOADING_STATUS.CREATE.getValue() ||
                    loadingList.getStatus() == MesExtEnumUtil.MES_LOADING_STATUS.PUBLISH.getValue() ||
                    loadingList.getStatus() == MesExtEnumUtil.MES_LOADING_STATUS.CREATE_ASN.getValue()) {
                loadingList.setStartScanTime(TimeTool.getNowTime(true));
            }

            loadingList.setStatus(MesExtEnumUtil.MES_LOADING_STATUS.LOADING.getValue());
            ConvertBean.serviceModelUpdate(loadingList, userInfo);
            update(loadingList);

            ConvertBean.serviceModelUpdate(loadingListDetail, userInfo);
            update(loadingListDetail);
        }
    }

    private MesPartShippingGroup getMesPartShippingGroup(String org, String partShippingGroupCode) {
        MesPartShippingGroup shippingGroup = mesPartShippingGroupService.getMesPartShippingGroup(org, partShippingGroupCode);
        if(Objects.isNull(shippingGroup)){
            throw new ImppBusiException(String.format("零件发运组【%s】信息不存在，请检查数据！", partShippingGroupCode));
        }
        return shippingGroup;
    }

    /**
     * 校验装车单
     *
     * @param orderCode
     * @param org
     */
    public MesLoadingList checkLoadingList(String orderCode, String org,Integer isPass,String userName) {

        //校验装车单是否存在
        DdlPackBean orderPackBean = DdlPackBean.getDdlPackBean(org);
        DdlPreparedPack.getStringEqualPack(orderCode, "orderCode", orderPackBean);
        MesLoadingList loadingList = vehiclesOrderRepository.getByProperty(orderPackBean);
        if (StringUtils.isEmpty(loadingList)) {
            throw new ImppBusiException(String.format("【%s】此装车单不存在，请检查数据！", orderCode));
        }
        //校验装车单状态 必须是未装车条码
        if (loadingList.getStatus() != MesExtEnumUtil.MES_LOADING_STATUS.CREATE.getValue() &&
                loadingList.getStatus() != MesExtEnumUtil.MES_LOADING_STATUS.PUBLISH.getValue() &&
                loadingList.getStatus() != MesExtEnumUtil.MES_LOADING_STATUS.CREATE_ASN.getValue() &&
                loadingList.getStatus() != MesExtEnumUtil.MES_LOADING_STATUS.LOADING.getValue()) {
            throw new ImppBusiException(String.format("【%s】此装车单状态为【%s】,请选择状态为【%s】或状态【%s】或状态【%s】或状态【%s】的装车单", loadingList.getOrderCode(),
                    MesExtEnumUtil.MES_LOADING_STATUS.valueOfDescription(loadingList.getStatus()),
                    MesExtEnumUtil.MES_LOADING_STATUS.CREATE.getDescription(),
                    MesExtEnumUtil.MES_LOADING_STATUS.PUBLISH.getDescription(),
                    MesExtEnumUtil.MES_LOADING_STATUS.CREATE_ASN.getDescription(),
                    MesExtEnumUtil.MES_LOADING_STATUS.LOADING.getDescription()));
        }
        //跳过
        if (Objects.equals(MesPcnExtConstWords.THREE, isPass)) {
            //跳过的单据和明细，系统默认是完成的
            loadingList.setStatus(MesExtEnumUtil.MES_LOADING_STATUS.SCANNED.getValue());
            loadingList.setRemark(MesPcnExtConstWords.SHIP_PASS);
            ConvertBean.serviceModelUpdate(loadingList, userName);
            vehiclesOrderRepository.update(loadingList);
            //明细跳过
            updateLoadingList(loadingList, userName);
            return null;
        }
        //增加发运顺序卡控，查询是否存在小于当前装车单对应的seq，且发运状态在（“创建”，“已确认”，“已生成ASN”，“装车中”）的装车单数据
        List<Integer> loadingListStatusList = new ArrayList<>();
        loadingListStatusList.add(MesExtEnumUtil.MES_LOADING_STATUS.CREATE.getValue());
        loadingListStatusList.add(MesExtEnumUtil.MES_LOADING_STATUS.PUBLISH.getValue());
        loadingListStatusList.add(MesExtEnumUtil.MES_LOADING_STATUS.CREATE_ASN.getValue());
        loadingListStatusList.add(MesExtEnumUtil.MES_LOADING_STATUS.LOADING.getValue());
        List<Integer> statusList = new ArrayList<>();
        statusList.add(MesExtEnumUtil.MES_LOADING_STATUS.SCANNED.getValue());
        statusList.add(MesExtEnumUtil.MES_LOADING_STATUS.ASN.getValue());
        //最后一个扫描完成的装车单信息
        orderPackBean = DdlPackBean.getDdlPackBean(loadingList.getOrganizeCode());
        DdlPreparedPack.getStringSmallerNotEqualPack(loadingList.getSeq(), "seq", orderPackBean);
        DdlPreparedPack.getStringEqualPack(loadingList.getPartShippingGroupCode(),"partShippingGroupCode",orderPackBean);
        DdlPreparedPack.getInPackList(statusList, "status", orderPackBean);
        DdlPreparedPack.getOrderBy("seq",CommonEnumUtil.ASC_OR_DESC.DESC.getValue(),orderPackBean);
        MesLoadingList mesLoadingList = vehiclesOrderRepository.getByProperty(orderPackBean);
        orderPackBean = DdlPackBean.getDdlPackBean(org);
        DdlPreparedPack.getStringSmallerNotEqualPack(loadingList.getSeq(), "seq", orderPackBean);
        if(!Objects.isNull(mesLoadingList)){
            DdlPreparedPack.getStringBiggerNotEqualPack(mesLoadingList.getSeq(), "seq", orderPackBean);
        }
        DdlPreparedPack.getStringEqualPack(loadingList.getPartShippingGroupCode(),"partShippingGroupCode",orderPackBean);
        DdlPreparedPack.getInPackList(loadingListStatusList, "status", orderPackBean);
        boolean exit = vehiclesOrderRepository.isExitByHql(orderPackBean);
        if (exit) {
            //1强过
            if((!Objects.isNull(isPass) && Objects.equals(MesPcnExtConstWords.ONE,isPass))) {
                loadingList.setRemark(MesPcnExtConstWords.STRONGER_PASS);
                ConvertBean.serviceModelUpdate(loadingList,userName);
                vehiclesOrderRepository.update(loadingList);
            }else {
                throw new ImppBusiException(String.format("【%s】装车单对应排序【%s】前存在未扫描发运的装车单，请检查数据！",
                        orderCode, loadingList.getSeq()));
            }
        }
        return loadingList;
    }
    @Override
    @MonitorLog
    public MesLoadingList insert(MesLoadingList item) {
        return vehiclesOrderRepository.insert(item);
    }

    @Override
    @MonitorLog
    public void update(MesLoadingList item) {
        vehiclesOrderRepository.update(item);
    }

    @Override
    @MonitorLog
    public void update(MesLoadingListDetail item) {
        vehiclesOrderDetailRepository.update(item);
    }

    private void updateLoadingList(MesLoadingList loadingList, String userName) {
        List<MesLoadingListDetail> mesLoadingListDetailList = getMesLoadingListList(loadingList.getId(), loadingList.getOrganizeCode());
        if (CollectionUtils.isEmpty(mesLoadingListDetailList)) return;
        List<String> shippingCodeList = mesLoadingListDetailList.stream().map(MesLoadingListDetail::getShippingCode).distinct().collect(Collectors.toList());
        //关闭装发运单明细
        List<MesShippingOrderManagement> mesShippingOrderManagementList = getMesShippingOrderManagementList(loadingList.getOrganizeCode(), shippingCodeList);
        if (!CollectionUtils.isEmpty(mesShippingOrderManagementList)) {
            List<MesJisShipping> shippingList = new ArrayList<>();
            //发送数据给wms
            for (MesShippingOrderManagement mesShippingOrderManagement : mesShippingOrderManagementList) {
                List<MesJisShipping> mesJisShippings = mesSortShippingCheckService.getMesJisShippings(mesShippingOrderManagement, null, userName);
                if (!CollectionUtils.isEmpty(mesJisShippings)) {
                    shippingList.addAll(mesJisShippings);
                }
            }
            if (!CollectionUtils.isEmpty(shippingList)) {
                jisShippingRepository.saveAll(shippingList);
            }
            //关闭发运单明细
            closeShippingOrderDetails(loadingList.getOrganizeCode(), userName, mesShippingOrderManagementList.stream().map(MesShippingOrderManagement::getId).collect(Collectors.toList()));
        }
        //关闭发运单
        closeShippingOrder(loadingList.getOrganizeCode(), userName, mesShippingOrderManagementList.stream().map(MesShippingOrderManagement::getId).collect(Collectors.toList()));
        //明细跳过
        updateLoadingDetails(loadingList.getOrganizeCode(), userName, loadingList.getId());
    }

    private void closeShippingOrderDetails(String organizeCode, String userName, List<Long> idList) {
        if (CollectionUtils.isEmpty(idList) || StringUtils.isEmpty(organizeCode)) return;
        DdlPackBean packBean = DdlPackBean.getDdlPackBean(organizeCode);
        DdlPreparedPack.getInPackList(idList, "pid", packBean);
        shippingOrderManagementDetailRepository.updateByProperties(new String[]{"modifyUser", "modifyDatetime", "status", "remark"},
                new Object[]{userName, TimeTool.getNowTime(true), MesExtEnumUtil.SHIPPING_ORDER_DETAIL_SHIPPING_STATUS.SKIP.getValue(), MesPcnExtConstWords.SHIP_PASS}, packBean);
    }

    private List<MesShippingOrderManagement> getMesShippingOrderManagementList(String organizeCode, List<String> shippingCodeList) {
        DdlPackBean packBean = DdlPackBean.getDdlPackBean(organizeCode);
        DdlPreparedPack.getInPackList(shippingCodeList, "shippingCode", packBean);
        return shippingOrderManagementRepository.findByHqlWhere(packBean);
    }

    private void closeShippingOrder(String organizeCode, String userName, List<Long> idList) {
        if (CollectionUtils.isEmpty(idList) || StringUtils.isEmpty(organizeCode)) return;
        DdlPackBean packBean = DdlPackBean.getDdlPackBean(organizeCode);
        DdlPreparedPack.getInPackList(idList, "id", packBean);
        shippingOrderManagementRepository.updateByProperties(new String[]{"modifyUser", "modifyDatetime", "status", "remark"},
                new Object[]{userName, TimeTool.getNowTime(true), MesExtEnumUtil.SHIPPING_ORDER_STATUS.SHIPPED.getValue(), MesPcnExtConstWords.SHIP_PASS}, packBean);
    }

    private List<MesLoadingListDetail> getMesLoadingListList(long id, String organizeCode) {
        DdlPackBean packBean = DdlPackBean.getDdlPackBean(organizeCode);
        DdlPreparedPack.getNumEqualPack(id, "pid", packBean);
        DdlPreparedPack.getNumberSmallerPack(MesExtEnumUtil.LOADING_ORDER_DETAIL_SHIPPING_STATUS.CLOSE.getValue(), "status", packBean);
        return vehiclesOrderDetailRepository.findByHqlWhere(packBean);
    }

    private void updateLoadingDetails(String organizeCode, String userName, long id) {
        if (StringUtil.isEmptyAndNull(id) || StringUtils.isEmpty(organizeCode)) return;
        DdlPackBean packBean = DdlPackBean.getDdlPackBean(organizeCode);
        DdlPreparedPack.getNumEqualPack(id, "pid", packBean);
        vehiclesOrderDetailRepository.updateByProperties(new String[]{"modifyUser", "modifyDatetime", "status", "remark"},
                new Object[]{userName, TimeTool.getNowTime(true), MesExtEnumUtil.LOADING_ORDER_DETAIL_SHIPPING_STATUS.SKIP.getValue(), MesPcnExtConstWords.SHIP_PASS}, packBean);
    }

}
