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

import cn.estsh.i3plus.ext.mes.pcn.api.base.IMesEquipmentExtService;
import cn.estsh.i3plus.ext.mes.pcn.api.busi.IMesEquipmentLogExtService;
import cn.estsh.i3plus.ext.mes.pcn.api.busi.spot.IMesSpotCheckOrderService;
import cn.estsh.i3plus.ext.mes.pcn.apiservice.util.MesPcnException;
import cn.estsh.i3plus.ext.mes.pcn.pojo.constant.MesCommonConstant;
import cn.estsh.i3plus.ext.mes.pcn.pojo.context.MesEquipVariableCollectContext;
import cn.estsh.i3plus.ext.mes.pcn.pojo.model.MesEquipmentSpotCheckModel;
import cn.estsh.i3plus.ext.mes.pcn.pojo.model.MesSpotCheckOrderModel;
import cn.estsh.i3plus.ext.mes.pcn.pojo.util.MesPcnExtConstWords;
import cn.estsh.i3plus.icloud.core.sdk.ICoreUtilCloud;
import cn.estsh.i3plus.mes.pcn.api.iservice.busi.ISyncFuncService;
import cn.estsh.i3plus.mes.pcn.util.DateUtil;
import cn.estsh.i3plus.platform.common.convert.ConvertBean;
import cn.estsh.i3plus.platform.common.exception.ImppExceptionEnum;
import cn.estsh.i3plus.platform.common.tool.TimeTool;
import cn.estsh.i3plus.pojo.base.bean.DdlPackBean;
import cn.estsh.i3plus.pojo.base.bean.ListPager;
import cn.estsh.i3plus.pojo.base.common.Pager;
import cn.estsh.i3plus.pojo.base.common.PagerHelper;
import cn.estsh.i3plus.pojo.base.enumutil.CommonEnumUtil;
import cn.estsh.i3plus.pojo.base.tool.DdlPreparedPack;
import cn.estsh.i3plus.pojo.mes.bean.*;
import cn.estsh.i3plus.pojo.mes.model.GenSerialNoModel;
import cn.estsh.i3plus.pojo.mes.repository.*;
import cn.estsh.i3plus.pojo.mes.util.MesExtEnumUtil;
import cn.estsh.impp.framework.boot.auth.AuthUtil;
import cn.estsh.impp.framework.boot.exception.ImppBusiException;
import cn.estsh.impp.framework.boot.exception.ImppExceptionBuilder;
import cn.estsh.impp.framework.boot.util.ValidatorBean;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.ListUtils;
import org.springframework.beans.BeanUtils;
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;
import java.util.stream.Stream;

/**
 * @Description :
 * @Reference :
 * @Author :
 * @CreateDate : 2024-05-15 20:50
 * @Modify:
 **/
@Service
@Slf4j
public class MesSpotCheckOrderService implements IMesSpotCheckOrderService {

    @Autowired
    private MesSpotCheckOrderRepository spotCheckOrderRepository;

    @Autowired
    private MesSpotCheckOrderResultRepository spotCheckOrderResultRepository;

    @Autowired
    private MesSpotCheckOrderPartRepository spotCheckOrderPartRepository;

    @Autowired
    private MesProduceSnRepository produceSnRepository;

    @Autowired
    private ISyncFuncService syncFuncService;

    @Autowired
    private MesEquipmentSpotCheckRepository equipmentSpotCheckRepository;

    @Autowired
    private MesEquipmentSpotCheckDetailRepository equipmentSpotCheckDetailRepository;

    @Autowired
    private MesEquipmentSpotCheckPartRepository equipmentSpotCheckPartRepository;

    @Autowired
    private ICoreUtilCloud sysOrderNoRuleCloud;

    @Autowired
    private IMesEquipmentLogExtService mesEquipmentLogExtService;

    @Autowired
    private IMesEquipmentExtService mesEquipmentExtService;
    @Autowired
    private MesEquipmentRepository mesEquipmentRepository;

    @Autowired
    private MesEquipmentSpotCheckTagRepository mesEquipmentSpotCheckTagRepository;

    @Override
    public ListPager<MesSpotCheckOrder> querySpotCheckOrder(MesSpotCheckOrder spotCheckOrder, Pager pager) {

        DdlPackBean packBean = getDdlPackBean(spotCheckOrder);
        pager = PagerHelper.getPager(pager, spotCheckOrderRepository.findByHqlWhereCount(packBean));
        DdlPreparedPack.getOrderByPack(new Object[]{CommonEnumUtil.ASC_OR_DESC.DESC.getValue(),CommonEnumUtil.ASC_OR_DESC.DESC.getValue()}, new String[]{"status","createDatetime"}, packBean);
        List<MesSpotCheckOrder> resultList = spotCheckOrderRepository.findByHqlWherePage(packBean, pager);
        if (CollectionUtils.isEmpty(resultList)) return new ListPager<>(resultList, pager);

        List<String> equipmentCodeList = (resultList.stream().filter(o -> (null != o && !StringUtils.isEmpty(o.getEquipCode())))
                .map(MesSpotCheckOrder::getEquipCode).collect(Collectors.toList())).stream().filter(o -> !StringUtils.isEmpty(o)).distinct().collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(equipmentCodeList)) {
            DdlPackBean ddlPackBean = DdlPackBean.getDdlPackBean(spotCheckOrder.getOrganizeCode());
            if (equipmentCodeList.size() == 1)  DdlPreparedPack.getStringEqualPack(equipmentCodeList.get(0), MesPcnExtConstWords.EQUIPMENT_CODE, ddlPackBean);
            else DdlPreparedPack.getInPackList(equipmentCodeList, MesPcnExtConstWords.EQUIPMENT_CODE, ddlPackBean);
            List<MesEquipment> mesEquipments = mesEquipmentRepository.findByHqlWhere(ddlPackBean);
            Map<String, List<MesEquipment>> equipMap = mesEquipments.stream().collect(Collectors.groupingBy(MesEquipment::getEquipmentCode));
            if (!CollectionUtils.isEmpty(equipMap)) {
                resultList.stream().filter(o -> (null != o && !StringUtils.isEmpty(o.getEquipCode())))
                        .forEach(o -> o.setEquipId(equipMap.containsKey(o.getEquipCode()) ? equipMap.get(o.getEquipCode()).get(0).getEquipId() : null));
            }
        }

        List<MesSpotCheckOrder> resultList2Create = resultList.stream().filter(o -> (null != o && o.getStatus().compareTo(MesExtEnumUtil.SPOT_CHECK_ORDER_STATUS.CREATE.getValue()) == 0)).collect(Collectors.toList());
        List<MesSpotCheckOrder> resultList2Other = resultList.stream().filter(o -> (null != o && o.getStatus().compareTo(MesExtEnumUtil.SPOT_CHECK_ORDER_STATUS.CREATE.getValue()) != 0)).collect(Collectors.toList());

        if (!CollectionUtils.isEmpty(resultList2Create)) resultList2Create = resultList2Create.stream().filter(o -> null != o).sorted(Comparator.comparing(MesSpotCheckOrder::getCreateDatetime).reversed()).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(resultList2Other)) resultList2Other = resultList2Other.stream().filter(o -> null != o).sorted(Comparator.comparing(MesSpotCheckOrder::getModifyDatetime).reversed()).collect(Collectors.toList());

        resultList.clear();
        if (!CollectionUtils.isEmpty(resultList2Create)) resultList.addAll(resultList2Create);
        if (!CollectionUtils.isEmpty(resultList2Other)) resultList.addAll(resultList2Other);

        return new ListPager<>(resultList, pager);

    }

    @Override
    public List<MesEquipmentSpotCheckModel> findEquipmentSpotCheck(MesEquipmentSpotCheck spotCheckOrder) {
        List<MesEquipmentSpotCheck> mesEquipmentSpotCheckList = queryEquipmentSpotCheck(spotCheckOrder);
        if(CollectionUtils.isEmpty(mesEquipmentSpotCheckList)){
            return null;
        }
        Map<String, List<MesEquipmentSpotCheck>> mesEquipmentSpotCheckMap = mesEquipmentSpotCheckList.stream().filter(t->!StringUtils.isEmpty(t.getEquipCode())).collect(Collectors.groupingBy(MesEquipmentSpotCheck::getEquipCode));
        if(Objects.isNull(mesEquipmentSpotCheckMap)){
            return null;
        }
        List<MesEquipmentSpotCheckModel> mesEquipmentSpotCheckModelList = new ArrayList<>();
        for (Map.Entry<String, List<MesEquipmentSpotCheck>> mesEquipmentSpotCheckEntry : mesEquipmentSpotCheckMap.entrySet()) {
            MesEquipmentSpotCheck next = mesEquipmentSpotCheckEntry.getValue().iterator().next();
            MesEquipmentSpotCheckModel mesEquipmentSpotCheckModel = new MesEquipmentSpotCheckModel();
            BeanUtils.copyProperties(next,mesEquipmentSpotCheckModel);
            Map<Integer, List<MesEquipmentSpotCheck>> listMap = mesEquipmentSpotCheckEntry.getValue().stream().filter(t->!StringUtils.isEmpty(t.getSpotCheckOrderType())).collect(Collectors.groupingBy(MesEquipmentSpotCheck::getSpotCheckOrderType));
            for (Map.Entry<Integer, List<MesEquipmentSpotCheck>> entry : listMap.entrySet()) {
                MesEquipmentSpotCheckModel.MesEquipmentSpotCheckDataModel mesEquipmentSpotCheckDataModel = new MesEquipmentSpotCheckModel.MesEquipmentSpotCheckDataModel();
                mesEquipmentSpotCheckDataModel.setSpotCheckOrderType(entry.getKey());
                mesEquipmentSpotCheckDataModel.setSpotCheckList(entry.getValue());
                mesEquipmentSpotCheckModel.getSpotCheckDataModelList().add(mesEquipmentSpotCheckDataModel);
            }
            mesEquipmentSpotCheckModelList.add(mesEquipmentSpotCheckModel);
        }
        return mesEquipmentSpotCheckModelList;
    }

    @Override
    public List<MesEquipmentSpotCheck> queryEquipmentSpotCheck(MesEquipmentSpotCheck bean) {

        DdlPackBean packBean = DdlPackBean.getDdlPackBean(bean.getOrganizeCode(), bean.getIsValid());
        DdlPreparedPack.getOrderByPack(new Object[]{CommonEnumUtil.ASC_OR_DESC.DESC.getValue()}, new String[]{"createDatetime"}, packBean);
        DdlPreparedPack.getStringEqualPack(bean.getSpotCheckCode(), "spotCheckCode", packBean);
        DdlPreparedPack.getStringLikerPack(bean.getSpotCheckName(), "spotCheckName", packBean);
        DdlPreparedPack.getStringEqualPack(bean.getWorkCenterCode(), "workCenterCode", packBean);
        DdlPreparedPack.getStringEqualPack(bean.getWorkCellCode(), "workCellCode", packBean);
        DdlPreparedPack.getStringEqualPack(bean.getEquipCode(), "equipCode", packBean);
        DdlPreparedPack.getNumEqualPack(bean.getSpotCheckOrderType(), "spotCheckOrderType", packBean);

        return equipmentSpotCheckRepository.findByHqlWhere(packBean);
    }

    @Override
    public MesSpotCheckOrderModel scanProduceSn(MesSpotCheckOrderModel model, String org) {

        //校验点检单
        checkSpotCheckOrder(model.getSpotCheckOrder());
        //校验设备信息
        if (MesExtEnumUtil.SPOT_CHECK_ORDER_TYPE.PROCESS_PARAMETER_INSPECTION.getValue() == model.getSpotCheckOrder().getSpotCheckOrderType() ||
                MesExtEnumUtil.SPOT_CHECK_ORDER_TYPE.EQUIPMENT_INSPECTION.getValue() == model.getSpotCheckOrder().getSpotCheckOrderType()) {
            checkEquipment(model, org);
            return model;
        } else {
            //校验是否重复扫描
            if(model.getOrderPartList().stream().anyMatch(t -> !StringUtils.isEmpty(t.getSn()) && Objects.equals(model.getProduceSn(), t.getSn()))){
                MesPcnException.throwMesBusiException("条码【%s】已扫描，请勿重复扫描", model.getProduceSn());
            }
            //检查条码
            MesProduceSn produceSn = checkProduceSn(model.getProduceSn(), org);

            boolean flg = false;
            for (MesSpotCheckOrderPart spotCheckOrderPart : model.getOrderPartList()) {

                if (spotCheckOrderPart.getPartNo().equals(produceSn.getPartNo()) && StringUtils.isEmpty(spotCheckOrderPart.getSn())) {
                    flg = true;
                    spotCheckOrderPart.setSn(model.getProduceSn());
                    break;
                }
            }

            if (!flg) {
                throw new ImppBusiException(String.format("扫描的条码【%s】对应的物料号【%s】在点检单中未匹配到待匹配的数据", produceSn.getProductSn(), produceSn.getPartNo()));
            }

            return model;
        }
    }

    /**
     * 查询点检数据
     *
     * @param model
     * @param org
     * @return
     */
    @Override
    public MesSpotCheckOrderModel queryEquipInfo(MesSpotCheckOrderModel model, String org) {

        //校验点检单
        checkSpotCheckOrder(model.getSpotCheckOrder());

        //点检单类型为产品首检，产品末检时 需要判断单据的条码是否都扫描完成
        if (Stream.of(MesExtEnumUtil.EQUIPMENT_CHECK_ORDER_TYPE.FIRST_INSPECTION.getValue(),MesExtEnumUtil.EQUIPMENT_CHECK_ORDER_TYPE.END_INSPECTION.getValue()).collect(Collectors.toList()).contains(model.getSpotCheckOrder().getSpotCheckOrderType())) {
            Optional<MesSpotCheckOrderPart> orderPartOptional = model.getOrderPartList().stream().filter(k -> !StringUtils.isEmpty(k.getSn())).findFirst();
            if (!orderPartOptional.isPresent()) {
                throw new ImppBusiException("未扫描条码，请扫描条码后再查询设备数据，请检查数据");
            }
        }
        //根据设备代码获取EQUIP_ID
        MesEquipment mesEquipment = mesEquipmentExtService.getMesEquipment(org, model.getSpotCheckOrder().getEquipCode());

        //是否允许开始点检
        allowSpotCheckOrder(model.getSpotCheckOrder(), org, mesEquipment.getEquipId());

        Map<Long, List<MesEquipVariableCollectContext>> setMap = null;
        //实际值地址数据Map
        Map<Long, List<MesEquipVariableCollectContext>> realMap = null;
        //获取实际值值设备数据
        List<MesEquipVariableCollectContext> realEquipmentLogList = new ArrayList<>();
        if(!Objects.isNull(mesEquipment) && !StringUtils.isEmpty(mesEquipment.getEquipId())){
            //获取设定值设备变量ID
            List<Long> setEquipVariableIdList =
                    model.getOrderResultList().stream().filter(k -> k.getSpotCheckItemType() == MesExtEnumUtil.SPOT_CHECK_ITEM_TYPE.AUTO.getValue()).map(MesSpotCheckOrderResult::getSetEquipVariableId).collect(Collectors.toList());

            //获取实际值设备变量ID
            List<Long> realEquipVariableIdList =
                    model.getOrderResultList().stream().filter(k -> k.getSpotCheckItemType() == MesExtEnumUtil.SPOT_CHECK_ITEM_TYPE.AUTO.getValue()).map(MesSpotCheckOrderResult::getRealEquipVariableId).collect(Collectors.toList());

            //获取设定值设备数据
            List<MesEquipVariableCollectContext> setEquipmentLogList = new ArrayList<>();
            for (List<Long> tmp : ListUtils.partition(setEquipVariableIdList, MesCommonConstant.MAX_PAGER_SIZE)) {
                List<MesEquipVariableCollectContext> equipmentLogCollectList = mesEquipmentLogExtService.getEquipmentLogCollectList(org, mesEquipment.getEquipId(), MesExtEnumUtil.EQUIP_VARIABLE_NEED_NEW_VALUE.TRUE.getValue(), MesExtEnumUtil.EQUIP_VARIABLE_TYPE.PROCESS_FINISH.getValue(), tmp);
                if(!CollectionUtils.isEmpty(equipmentLogCollectList)){
                    setEquipmentLogList.addAll(equipmentLogCollectList);
                }
            }
            //设定值地址数据Map
            setMap = setEquipmentLogList.stream().collect(Collectors.groupingBy(MesEquipVariableCollectContext::getEquipVariableId));

            for (List<Long> tmp : ListUtils.partition(realEquipVariableIdList, MesCommonConstant.MAX_PAGER_SIZE)) {
                List<MesEquipVariableCollectContext> equipmentLogCollectList = mesEquipmentLogExtService.getEquipmentLogCollectList(org, mesEquipment.getEquipId(), MesExtEnumUtil.EQUIP_VARIABLE_NEED_NEW_VALUE.TRUE.getValue(), MesExtEnumUtil.EQUIP_VARIABLE_TYPE.PROCESS_FINISH.getValue(), tmp);
                if(!CollectionUtils.isEmpty(equipmentLogCollectList)){
                    realEquipmentLogList.addAll(equipmentLogCollectList);
                }
            }
            //实际值地址数据Map
            realMap = realEquipmentLogList.stream().collect(Collectors.groupingBy(MesEquipVariableCollectContext::getEquipVariableId));
        }

        for (MesSpotCheckOrderResult result : model.getOrderResultList()) {

            //只获取自动的地址
            if (result.getSpotCheckItemType() == MesExtEnumUtil.SPOT_CHECK_ITEM_TYPE.AUTO.getValue()) {

                //获取设定值地址数据
                if (!Objects.isNull(setMap) && setMap.containsKey(result.getSetEquipVariableId())) {
                    String value = setMap.get(result.getSetEquipVariableId()).get(0).getEquipVariableValue();
                    result.setSpotCheckSetValue(value);
                    result.setSetValueRecordType(MesExtEnumUtil.SPOT_VALUE_RECORD_TYPE.EQUIPMENT_INPUT.getValue());

                }
//                else {
//                    result.setSetValueRecordType(MesExtEnumUtil.SPOT_VALUE_RECORD_TYPE.ARTIFICIAL_INPUT.getValue());
//                }
                //获取实际值地址数据
                if (!Objects.isNull(realMap) && realMap.containsKey(result.getRealEquipVariableId())) {
                    String value = realMap.get(result.getRealEquipVariableId()).get(0).getEquipVariableValue();
                    result.setSpotCheckRealValue(value);
                    //根据获取的值判断是否是设备自定义参数 或者认为录入参数
                    //没有值，则判断设备bad 导致人工手填
                    if (StringUtils.isEmpty(value)) {
                        //实际录入方式 设置为认为录入参数
                        result.setRealValueRecordType(MesExtEnumUtil.SPOT_VALUE_RECORD_TYPE.ARTIFICIAL_INPUT.getValue());
                    } else {
                        //实际录入方式 设置为设备自定义参数
                        result.setRealValueRecordType(MesExtEnumUtil.SPOT_VALUE_RECORD_TYPE.EQUIPMENT_INPUT.getValue());
                    }
                } else {
                    //若实际值表中没有数据，则
                    //实际录入方式 设置为设备自定义参数
                    result.setRealValueRecordType(MesExtEnumUtil.SPOT_VALUE_RECORD_TYPE.EQUIPMENT_INPUT.getValue());
                }

            } else {
                //手动获取 设置为认为录入参数
                result.setRealValueRecordType(MesExtEnumUtil.SPOT_VALUE_RECORD_TYPE.ARTIFICIAL_INPUT.getValue());
            }

        }

        return model;
    }

    /**
     * 点检单完成
     *
     * @param model
     * @param org
     */
    @Override
    public void saveCheck(MesSpotCheckOrderModel model, String org) {

        //校验点检单
        MesSpotCheckOrder spotCheckOrder = checkSpotCheckOrder(model.getSpotCheckOrder());

        //点检单类型为产品首检，产品末检时 需要判断单据的条码是否都扫描完成
        if (Stream.of(MesExtEnumUtil.EQUIPMENT_CHECK_ORDER_TYPE.FIRST_INSPECTION.getValue(),MesExtEnumUtil.EQUIPMENT_CHECK_ORDER_TYPE.END_INSPECTION.getValue()).collect(Collectors.toList()).contains(model.getSpotCheckOrder().getSpotCheckOrderType())) {
            Optional<MesSpotCheckOrderPart> orderPartOptional = model.getOrderPartList().stream().filter(k -> !StringUtils.isEmpty(k.getSn())).findFirst();
            if (!orderPartOptional.isPresent()) {
                throw new ImppBusiException("未扫描条码，请扫描条码后再查询设备数据，请检查数据");
            }
        }
        model.getOrderPartList().forEach(k -> {
            k.setSystemSyncStatus(CommonEnumUtil.FALSE);
            k.setSystemSyncDatetime("");
            ConvertBean.serviceModelUpdate(k, AuthUtil.getSessionUser().getUserName());
        });
        spotCheckOrderPartRepository.saveAll(model.getOrderPartList());

        Integer orderResult = MesExtEnumUtil.SPOT_CHECK_ORDER_RESULT_TYPE.OK.getValue();
        // 点检单的结果
        for (MesSpotCheckOrderResult result : model.getOrderResultList()) {

            if (StringUtils.isEmpty(result.getSpotCheckRealValue())) {
                throw new ImppBusiException(String.format("点检单明细未填写完成，请继续质检", result.getSpotCheckRealValue()));
            }
            if (Objects.equals(result.getSpotCheckResult(), "NOK") && Objects.equals(MesExtEnumUtil.SPOT_CHECK_ORDER_RESULT_TYPE.OK.getValue(), orderResult)) {
                // 如果有NOK的则不用管，全OK才是OK，否则就是NOK
                orderResult = MesExtEnumUtil.SPOT_CHECK_ORDER_RESULT_TYPE.NOK.getValue();
            }
            result.setSpotCheckTime(TimeTool.getNowTime(true));
            result.setSystemSyncStatus(CommonEnumUtil.FALSE);
            result.setSystemSyncDatetime("");
            ConvertBean.serviceModelUpdate(result, AuthUtil.getSessionUser().getUserName());
        }

        spotCheckOrderResultRepository.saveAll(model.getOrderResultList());

        spotCheckOrder.setSpotCheckOrderResult(orderResult);
        spotCheckOrder.setSpotCheckTime(TimeTool.getNowTime(true));
        spotCheckOrder.setSystemSyncStatus(CommonEnumUtil.FALSE);
        spotCheckOrder.setSystemSyncDatetime("");
        spotCheckOrder.setSpotCheckUser(AuthUtil.getSessionUser().getUserName());
        spotCheckOrder.setStatus(MesExtEnumUtil.SPOT_CHECK_ORDER_STATUS.COMPLETE.getValue());
        ConvertBean.serviceModelUpdate(spotCheckOrder, AuthUtil.getSessionUser().getUserName());
        spotCheckOrderRepository.save(spotCheckOrder);
    }

    /**
     * 重新点检-根据原单据生成新点检单
     *
     * @param model
     * @param org
     */
    @Override
    public void saveReCheck(MesSpotCheckOrderModel model, String org) {

        //校验点检单
        DdlPackBean ddlPackBean = DdlPackBean.getDdlPackBean(org);
        DdlPreparedPack.getNumEqualPack(model.getSpotCheckOrder().getId(),"id",ddlPackBean);
        MesSpotCheckOrder spotCheckOrder = spotCheckOrderRepository.getByProperty(ddlPackBean);
        if(Objects.isNull(spotCheckOrder)){
            throw new ImppBusiException(String.format("点检单【%s】不存在", model.getSpotCheckOrder().getId()));
        }
        if (spotCheckOrder.getStatus() != MesExtEnumUtil.SPOT_CHECK_ORDER_STATUS.CREATE.getValue() && spotCheckOrder.getStatus() != MesExtEnumUtil.SPOT_CHECK_ORDER_STATUS.COMPLETE.getValue()) {
            throw new ImppBusiException(String.format("【%s】单据状态为【%s】，请选择状态为【%s】或【%s】的单据",
                    model.getSpotCheckOrder().getId(), MesExtEnumUtil.SPOT_CHECK_ORDER_STATUS.valueOfDescription(spotCheckOrder.getStatus()),
                    MesExtEnumUtil.SPOT_CHECK_ORDER_STATUS.CREATE.getDescription(), MesExtEnumUtil.SPOT_CHECK_ORDER_STATUS.COMPLETE.getDescription()));
        }

        //生成新点检单
        MesSpotCheckOrder spotCheckOrderTemp = new MesSpotCheckOrder();
        BeanUtils.copyProperties(spotCheckOrder, spotCheckOrderTemp, "id");

        //生成单据号
        GenSerialNoModel genSerialNoModel = new GenSerialNoModel(MesCommonConstant.SPOT_CHECK_ORDER_NO_RULE);
        String orderNo = (String) syncFuncService.syncSerialNo(genSerialNoModel, AuthUtil.getSessionUser().getUserName(), AuthUtil.getOrganizeCode(), MesPcnExtConstWords.ONE).getResultList().iterator().next();

        //保存新点检单
        spotCheckOrderTemp.setSpotCheckOrderNo(orderNo);
        spotCheckOrderTemp.setStatus(MesExtEnumUtil.SPOT_CHECK_ORDER_STATUS.CREATE.getValue());
        spotCheckOrderTemp.setSpotCheckOrderResult(0);
        spotCheckOrderTemp.setSpotCheckTime("");
        spotCheckOrderTemp.setSpotCheckUser("");
        spotCheckOrderTemp.setSystemSyncStatus(CommonEnumUtil.FALSE);
        spotCheckOrderTemp.setSystemSyncDatetime("");
        ConvertBean.serviceModelInitialize(spotCheckOrderTemp, AuthUtil.getSessionUser().getUserName());
        spotCheckOrderTemp = spotCheckOrderRepository.insert(spotCheckOrderTemp);

        //查询点检明细
        DdlPackBean packBean = DdlPackBean.getDdlPackBean(spotCheckOrder.getOrganizeCode());
        DdlPreparedPack.getNumEqualPack(spotCheckOrder.getId(), "pid", packBean);
        List<MesSpotCheckOrderResult> orderResultList = spotCheckOrderResultRepository.findByHqlWhere(packBean);

        //查询新点检明细
        List<MesSpotCheckOrderResult> orderResultNewList = new ArrayList<>();
        MesSpotCheckOrder finalOrderTemp = spotCheckOrderTemp;
        orderResultList.forEach(k -> {
            MesSpotCheckOrderResult result = new MesSpotCheckOrderResult();
            BeanUtils.copyProperties(k, result, "id");
            result.setPid(finalOrderTemp.getId());
            result.setSpotCheckOrderNo(finalOrderTemp.getSpotCheckOrderNo());
            result.setSpotCheckRealValue("");
            result.setIsTolerance(0);
            result.setSpotCheckTime("");
            result.setSystemSyncStatus(CommonEnumUtil.FALSE);
            result.setSystemSyncDatetime("");
            ConvertBean.serviceModelInitialize(result, AuthUtil.getSessionUser().getUserName());
            orderResultNewList.add(result);
        });


        //查询点检零件
        DdlPackBean partPackBean = DdlPackBean.getDdlPackBean(spotCheckOrder.getOrganizeCode());
        DdlPreparedPack.getNumEqualPack(spotCheckOrder.getId(), "spotCheckOrderId", partPackBean);
        List<MesSpotCheckOrderPart> orderPartList = spotCheckOrderPartRepository.findByHqlWhere(partPackBean);


        if (!CollectionUtils.isEmpty(orderPartList)) {
            //保存新点检单零件
            List<MesSpotCheckOrderPart> spotCheckOrderPartList = new ArrayList<>();

            orderPartList.forEach(k -> {
                MesSpotCheckOrderPart spotCheckOrderPart = new MesSpotCheckOrderPart();
                BeanUtils.copyProperties(k, spotCheckOrderPart, "id");
                spotCheckOrderPart.setSpotCheckOrderId(finalOrderTemp.getId());
                spotCheckOrderPart.setSn("");
                spotCheckOrderPart.setSystemSyncStatus(CommonEnumUtil.FALSE);
                spotCheckOrderPart.setSystemSyncDatetime("");
//                ConvertBean.serviceModelInitialize(spotCheckOrderPart, "LML");
                ConvertBean.serviceModelInitialize(spotCheckOrderPart, AuthUtil.getSessionUser().getUserName());
                spotCheckOrderPartList.add(spotCheckOrderPart);
            });

            spotCheckOrderPartRepository.saveAll(spotCheckOrderPartList);
        }

        //保存新点检单明细
        spotCheckOrderResultRepository.saveAll(orderResultNewList);
        //保存旧点检单
        if (spotCheckOrder.getStatus() != MesExtEnumUtil.SPOT_CHECK_ORDER_STATUS.COMPLETE.getValue()) {
            spotCheckOrder.setStatus(MesExtEnumUtil.SPOT_CHECK_ORDER_STATUS.CLOSE.getValue());
        }

//        ConvertBean.serviceModelUpdate(spotCheckOrder, "LML");
        ConvertBean.serviceModelUpdate(spotCheckOrder, AuthUtil.getSessionUser().getUserName());
        spotCheckOrderRepository.save(spotCheckOrder);


    }

    @Override
    public MesSpotCheckOrder insert(MesSpotCheckOrder bean) {
//        onInsertBean(bean);

        // 数据校验
        ValidatorBean.checkNotNull(bean.getSpotCheckId(), "点检方案不能为空");

        DdlPackBean packBean = DdlPackBean.getDdlPackBean(bean.getOrganizeCode());
        DdlPreparedPack.getNumEqualPack(bean.getSpotCheckId(), "spotCheckId", packBean);
        DdlPreparedPack.getNumEqualPack(MesExtEnumUtil.SPOT_CHECK_ORDER_STATUS.CREATE.getValue(), "status", packBean);
        boolean flg = spotCheckOrderRepository.isExitByHql(packBean);
        if (flg) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                    .setErrorDetail("存在相同配置状态为【%s】的点检单 id：【%s】，请检查数据", MesExtEnumUtil.SPOT_CHECK_ORDER_STATUS.CREATE.getDescription(), bean.getSpotCheckId())
                    .build();
        }

        bean.setTaskResource(MesCommonConstant.SPOT_CHECK_ORDER_TASK_RESOURCE);
        bean.setStatus(MesExtEnumUtil.SPOT_CHECK_ORDER_STATUS.CREATE.getValue());
        //查询点检方案  点检单点检方案  spotCheckId-id关联
        DdlPackBean ddlPackBean = DdlPackBean.getDdlPackBean(bean.getOrganizeCode());
        DdlPreparedPack.getNumEqualPack(bean.getSpotCheckId(),"id",ddlPackBean);
        MesEquipmentSpotCheck equipmentSpotCheck = equipmentSpotCheckRepository.getByProperty(ddlPackBean);

        if (StringUtils.isEmpty(equipmentSpotCheck)) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                    .setErrorDetail("【%s】点检方案不存在，请检查数据", bean.getSpotCheckId())
                    .build();
        }

        if (equipmentSpotCheck.getTriggerMode() == MesExtEnumUtil.EQUIPMENT_SPOT_CHECK_TRIGGER_MODE.TIME.getValue()) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                    .setErrorDetail("【%s】点检方案触发方式为【%s】，请勿手动创建", bean.getSpotCheckId(), MesExtEnumUtil.EQUIPMENT_SPOT_CHECK_TRIGGER_MODE.TIME.getDescription())
                    .build();
        }

        //查询点检明细 主表明细表 spotCheckId-pid关联
        packBean = DdlPackBean.getDdlPackBean(bean.getOrganizeCode());
        DdlPreparedPack.getNumEqualPack(bean.getSpotCheckId(), "pid", packBean);
        List<MesEquipmentSpotCheckDetail> detailList = equipmentSpotCheckDetailRepository.findByHqlWhere(packBean);

        if (CollectionUtils.isEmpty(detailList)) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                    .setErrorDetail("【%s】点检方案明细不存在，请检查数据", bean.getSpotCheckId())
                    .build();
        }

        //查询点检零件 主表零件表 spotCheckId-pid关联
        List<MesEquipmentSpotCheckPart> equipmentSpotCheckPartList = equipmentSpotCheckPartRepository.findByHqlWhere(packBean);

        if (CollectionUtils.isEmpty(equipmentSpotCheckPartList) &&
                equipmentSpotCheck.getSpotCheckOrderType() == MesExtEnumUtil.SPOT_CHECK_ORDER_TYPE.FIRST_PRODUCT_INSPECTION.getValue()) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                    .setErrorDetail("【%s】点检方案类型为【%s】配置零件号为空，请检查数据", bean.getSpotCheckId(), MesExtEnumUtil.SPOT_CHECK_ORDER_TYPE.FIRST_PRODUCT_INSPECTION.getDescription())
                    .build();
        }

        //生成单号
        GenSerialNoModel genSerialNoModel = new GenSerialNoModel(MesCommonConstant.SPOT_CHECK_ORDER_NO_RULE);
        String orderNo = (String) syncFuncService.syncSerialNo(genSerialNoModel, AuthUtil.getSessionUser().getUserName(), AuthUtil.getOrganizeCode(), MesPcnExtConstWords.ONE).getResultList().iterator().next();
        //保存单据
        BeanUtils.copyProperties(equipmentSpotCheck, bean, MesPcnExtConstWords.BASE_BEAN_FIELDS);
//        bean.setSpotCheckOrderNo("SPOT_CHECK_ORDER_NO_0003");
        bean.setSpotCheckOrderNo(orderNo);
        bean.setSystemSyncStatus(CommonEnumUtil.FALSE);
        bean.setSystemSyncDatetime("");
        ConvertBean.serviceModelInitialize(bean, AuthUtil.getSessionUser().getUserName());
        bean = spotCheckOrderRepository.insert(bean);

        //保存单据明细
        List<MesSpotCheckOrderResult> spotCheckOrderResults = new ArrayList<>();
        MesSpotCheckOrder finalBean = bean;
        detailList.forEach(k -> {
            MesSpotCheckOrderResult result = new MesSpotCheckOrderResult();
            BeanUtils.copyProperties(k, result, MesPcnExtConstWords.BASE_BEAN_FIELDS);
            result.setSpotCheckOrderNo(finalBean.getSpotCheckOrderNo());
            result.setPid(finalBean.getId());
            result.setWorkCenterCode(finalBean.getWorkCenterCode());
            result.setWorkCellCode(finalBean.getWorkCellCode());
            result.setSpotCheckItemId(k.getId());
            result.setTaskItemName(k.getSpotCheckItemName());
            result.setSpotCheckStandardValue(k.getStandardValue());
            result.setSystemSyncStatus(CommonEnumUtil.FALSE);
            result.setSystemSyncDatetime("");
            ConvertBean.serviceModelInitialize(result, AuthUtil.getSessionUser().getUserName());
//            ConvertBean.serviceModelInitialize(result, "LML");
            spotCheckOrderResults.add(result);
        });

        //保存单据零件
        if (!CollectionUtils.isEmpty(equipmentSpotCheckPartList)) {

            List<MesSpotCheckOrderPart> spotCheckOrderPartList = new ArrayList<>();
            equipmentSpotCheckPartList.forEach(k -> {
                MesSpotCheckOrderPart spotCheckOrderPart = new MesSpotCheckOrderPart();
                spotCheckOrderPart.setSpotCheckOrderId(finalBean.getId());
                BeanUtils.copyProperties(k, spotCheckOrderPart, MesPcnExtConstWords.BASE_BEAN_FIELDS);
                spotCheckOrderPart.setSystemSyncStatus(CommonEnumUtil.FALSE);
                spotCheckOrderPart.setSystemSyncDatetime("");
                ConvertBean.serviceModelInitialize(spotCheckOrderPart, AuthUtil.getSessionUser().getUserName());
//                ConvertBean.serviceModelInitialize(spotCheckOrderPart, "LML");
                spotCheckOrderPartList.add(spotCheckOrderPart);
            });
//            spotCheckOrderPartService.insertBatch(spotCheckOrderPartList);
            spotCheckOrderPartRepository.saveAll(spotCheckOrderPartList);
        }

//        spotCheckOrderResultService.insertBatch(spotCheckOrderResults);
        spotCheckOrderResultRepository.saveAll(spotCheckOrderResults);

        return bean;
    }

    @Override
    public MesSpotCheckOrderModel querySpotCheckOrderResult(MesSpotCheckOrder spotCheckOrder) {

        //校验点检单
        checkSpotCheckOrder(spotCheckOrder);

        //查询点检明细
        DdlPackBean packBean = DdlPackBean.getDdlPackBean(spotCheckOrder.getOrganizeCode());
        DdlPreparedPack.getNumEqualPack(spotCheckOrder.getId(), "pid", packBean);
        DdlPreparedPack.getOrderByPack(new Object[]{CommonEnumUtil.ASC_OR_DESC.ASC.getValue()}, new String[]{"seqCode"}, packBean);

        List<MesSpotCheckOrderResult> orderResultList = spotCheckOrderResultRepository.findByHqlWhere(packBean);

        //查询点检零件
        DdlPackBean partPackBean = DdlPackBean.getDdlPackBean(spotCheckOrder.getOrganizeCode());
        DdlPreparedPack.getNumEqualPack(spotCheckOrder.getId(), "spotCheckOrderId", partPackBean);
        List<MesSpotCheckOrderPart> orderPartList = spotCheckOrderPartRepository.findByHqlWhere(partPackBean);

        MesSpotCheckOrderModel model = new MesSpotCheckOrderModel();
        model.setOrderResultList(orderResultList);
        model.setOrderPartList(orderPartList);
        return model;
    }

    private DdlPackBean getDdlPackBean(MesSpotCheckOrder spotCheckOrder) {
        String createDateTime = TimeTool.pareDateToString(DateUtil.addDays(new Date(), -(Objects.isNull(spotCheckOrder.getDays()) ? MesPcnExtConstWords.SEVEN : spotCheckOrder.getDays())));
        DdlPackBean packBean = DdlPackBean.getDdlPackBean(spotCheckOrder.getOrganizeCode());
        DdlPreparedPack.getStringLikerPack(spotCheckOrder.getWorkCenterCode(), "workCenterCode", packBean);
        DdlPreparedPack.getStringLikerPack(spotCheckOrder.getWorkCellCode(), "workCellCode", packBean);
        DdlPreparedPack.getStringLikerPack(spotCheckOrder.getSpotCheckOrderNo(), "spotCheckOrderNo", packBean);
        DdlPreparedPack.getStringEqualPack(spotCheckOrder.getEquipCode(), "equipCode", packBean);
        packBean.setWhereAppend(packBean.getWhereAppend() + String.format(" and (model.status = %s or (model.status = %s and model.createDatetime >= '%s'))", MesExtEnumUtil.SPOT_CHECK_ORDER_STATUS.CREATE.getValue(), MesExtEnumUtil.SPOT_CHECK_ORDER_STATUS.COMPLETE.getValue(), createDateTime));
        return packBean;
    }

    /**
     * 校验点检单
     *
     * @param spotCheckOrder
     * @return
     */
    private MesSpotCheckOrder checkSpotCheckOrder(MesSpotCheckOrder spotCheckOrder) {
        DdlPackBean packBean = DdlPackBean.getDdlPackBean(spotCheckOrder.getOrganizeCode());
        DdlPreparedPack.getNumEqualPack(spotCheckOrder.getId(),"id",packBean);
        MesSpotCheckOrder result = spotCheckOrderRepository.getByProperty(packBean);
        if(Objects.isNull(result)){
            throw new ImppBusiException(String.format("单据【%s】信息不存在", spotCheckOrder.getSpotCheckOrderNo()));
        }
        if (result.getStatus() != MesExtEnumUtil.SPOT_CHECK_ORDER_STATUS.CREATE.getValue()) {
            throw new ImppBusiException(String.format("【%s】单据状态为【%s】，请选择状态为【%s】的单据",
                    spotCheckOrder.getId(), MesExtEnumUtil.SPOT_CHECK_ORDER_STATUS.valueOfDescription(result.getStatus()),
                    MesExtEnumUtil.SPOT_CHECK_ORDER_STATUS.CREATE.getDescription()));
        }
        return result;
    }


    private MesProduceSn checkProduceSn(String serialNumber, String org) {
        //根据扫描的条码查询条码是否存在
        DdlPackBean packBean = DdlPackBean.getDdlPackBean(org);
        DdlPreparedPack.getStringEqualPack(serialNumber, "productSn", packBean);
        DdlPreparedPack.getOrderByPack(new Object[]{CommonEnumUtil.ASC_OR_DESC.DESC.getValue()}, new String[]{"createDatetime"}, packBean);
        MesProduceSn produceSn = produceSnRepository.getByProperty(packBean);

        //若不存在则提示条码不存在
        if (StringUtils.isEmpty(produceSn)) {
            throw new ImppBusiException(String.format("【%s】此条码不存在，请检查数据", serialNumber));
        }

        //根据条码状态判断 是不是已下线条码
        //若不是已下线的条码则提示 条码状态 请选择已下线的条码
        // 2024-11-12 激光打码和打印条码，也能够执行
        /*if (produceSn.getSnStatus() != MesExtEnumUtil.PRODUCE_SN_STATUS.OFFLINE.getValue()) {
            throw new ImppBusiException(String.format("【%s】此条码状态为【%s】,请选择状态为【%s】状态的条码", serialNumber, MesExtEnumUtil.PRODUCE_SN_STATUS.valueOfDescription(produceSn.getSnStatus()),
                    MesExtEnumUtil.PRODUCE_SN_STATUS.OFFLINE.getDescription()));
        }*/

        //是否需要判断条码质量状态
        List<Integer> statusList = Stream.of(MesExtEnumUtil.PRODUCE_QC_STATUS.QUALIFIED.getValue(), MesExtEnumUtil.PRODUCE_QC_STATUS.SUSPICIOUS_TO_QUALIFIED.getValue()).collect(Collectors.toList());
        if (!statusList.contains(produceSn.getQcStatus())){
            throw new ImppBusiException(String.format("【%s】此条码质量状态为【%s】,请选择【%s】状态的条码", serialNumber, MesExtEnumUtil.PRODUCE_QC_STATUS.valueOfDescription(produceSn.getQcStatus()),
                    MesExtEnumUtil.PRODUCE_QC_STATUS.QUALIFIED.getDescription()));
        }
        return produceSn;
    }

    private void checkEquipment(MesSpotCheckOrderModel model, String org) {
        MesEquipment mesEquipment = mesEquipmentExtService.getMesEquipment(org, model.getSpotCheckOrder().getEquipCode());
        if (Objects.isNull(mesEquipment)) {
            throw new ImppBusiException(String.format("点检单对应的设备【%s】信息不存在", model.getSpotCheckOrder().getEquipCode()));
        }
        if (StringUtils.isEmpty(mesEquipment.getEquipId()) || !model.getProduceSn().equals(mesEquipment.getEquipId() + "")) {
            throw new ImppBusiException(String.format("点检单对应的设备编号【%s】和扫描的设备编号【%s】不匹配，请检查数据", mesEquipment.getEquipId(), model.getProduceSn()));
        }
    }

    @Override
    public void deleteBatchIds(Long[] ids, String userName, String organizeCode) {
        for (Long id : ids) {
            DdlPackBean ddlPackBean = DdlPackBean.getDdlPackBean(organizeCode);
            DdlPreparedPack.getNumEqualPack(id, MesPcnExtConstWords.ID, ddlPackBean);
            MesSpotCheckOrder spotCheckOrder = spotCheckOrderRepository.getByProperty(ddlPackBean);
            if (null == spotCheckOrder) continue;
            if (!StringUtils.isEmpty(spotCheckOrder.getStatus()) && spotCheckOrder.getStatus().compareTo(MesExtEnumUtil.SPOT_CHECK_ORDER_STATUS.COMPLETE.getValue()) == 0 &&
                    !StringUtils.isEmpty(spotCheckOrder.getSpotCheckOrderResult()) && spotCheckOrder.getSpotCheckOrderResult().compareTo(MesExtEnumUtil.SPOT_CHECK_ORDER_RESULT_TYPE.OK.getValue()) == 0) {
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                        .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                        .setErrorDetail("【%s】点检单状态为【%s】,且点检结果为OK,不允许修改，请检查数据", spotCheckOrder.getSpotCheckId(), MesExtEnumUtil.SPOT_CHECK_ORDER_STATUS.valueOfDescription(spotCheckOrder.getStatus()))
                        .build();
            }

            spotCheckOrder.setSystemSyncStatus(CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue());
            spotCheckOrder.setIsDeleted(CommonEnumUtil.TRUE_OR_FALSE.TRUE.getValue());
            ConvertBean.serviceModelUpdate(spotCheckOrder, userName);
            //获取点检方案明细
            DdlPackBean packBean = DdlPackBean.getDdlPackBean(organizeCode);
            DdlPreparedPack.getNumEqualPack(id, MesPcnExtConstWords.PID, packBean);
            List<MesSpotCheckOrderResult> detailList = spotCheckOrderResultRepository.findByHqlWhere(packBean);
            if (!CollectionUtils.isEmpty(detailList)) {
                detailList.forEach(k -> {
                    k.setIsDeleted(CommonEnumUtil.TRUE_OR_FALSE.TRUE.getValue());
                    k.setSystemSyncStatus(CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue());
                    k.setSystemSyncDatetime("");
                    ConvertBean.serviceModelUpdate(k, userName);
                });
                spotCheckOrderResultRepository.saveAll(detailList);
            }

            //获取点检方案零件 主表零件表 spotCheckId-pid关联
            //获取点检单零件号
            DdlPackBean orderPartPackBean = DdlPackBean.getDdlPackBean(organizeCode);
            DdlPreparedPack.getNumEqualPack(id, MesPcnExtConstWords.SPOT_CHECK_ORDER_ID, orderPartPackBean);
            List<MesSpotCheckOrderPart> oldOrderPartList = spotCheckOrderPartRepository.findByHqlWhere(orderPartPackBean);
            if (!CollectionUtils.isEmpty(oldOrderPartList)) {
                oldOrderPartList.forEach(k -> {
                    k.setIsDeleted(CommonEnumUtil.TRUE_OR_FALSE.TRUE.getValue());
                    k.setSystemSyncStatus(CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue());
                    k.setSystemSyncDatetime("");
                    ConvertBean.serviceModelUpdate(k, userName);
                });
                spotCheckOrderPartRepository.saveAll(oldOrderPartList);
            }

        }
    }

    private void allowSpotCheckOrder(MesSpotCheckOrder spotCheckOrder, String org, Integer equipId) {
        if(Objects.isNull(spotCheckOrder) || StringUtils.isEmpty(spotCheckOrder.getSpotCheckCode()) || StringUtils.isEmpty(org)){
            return;
        }
        DdlPackBean packBean = DdlPackBean.getDdlPackBean(org);
        DdlPreparedPack.getStringEqualPack(spotCheckOrder.getSpotCheckCode(),"spotCheckCode",packBean);
        MesEquipmentSpotCheckTag equipmentSpotCheckTag = mesEquipmentSpotCheckTagRepository.getByProperty(packBean);
        if(Objects.isNull(equipmentSpotCheckTag)){
            return;
        }
        List<MesEquipVariableCollectContext> equipmentLogCollectList = mesEquipmentLogExtService.getEquipmentLogCollectList(org, equipId, MesExtEnumUtil.EQUIP_VARIABLE_NEED_NEW_VALUE.TRUE.getValue(), MesExtEnumUtil.EQUIP_VARIABLE_TYPE.PROCESS_FINISH.getValue(), Stream.of(equipmentSpotCheckTag.getEquipVariableId()).collect(Collectors.toList()));
        if(CollectionUtils.isEmpty(equipmentLogCollectList)){
            throw new ImppBusiException(String.format("点检项目代码【%s】设备地址【%s】未查询到设备返回值，请检查数据！", spotCheckOrder.getSpotCheckCode(),equipmentSpotCheckTag.getTagName()));
        }
        if (!equipmentLogCollectList.iterator().next().getEquipVariableValue().equals(equipmentSpotCheckTag.getSuccessValue())) {
            throw new ImppBusiException(String.format("点检项目代码【%s】设备地址【%s】设备返回值【%s】与理论成功值【%s】不匹配，请检查数据！", spotCheckOrder.getSpotCheckCode(),equipmentSpotCheckTag.getTagName(),equipmentLogCollectList.iterator().next().getEquipVariableValue(),equipmentSpotCheckTag.getSuccessValue()));
        }
    }

    @Override
    public List<MesSpotCheckOrder> getSpotCheckOrderList(String organizeCode, String workCenterCode, String equipmentCode, List<Long> spotCheckIdList) {
        if (StringUtils.isEmpty(organizeCode) || StringUtils.isEmpty(workCenterCode) || StringUtils.isEmpty(equipmentCode) || CollectionUtils.isEmpty(spotCheckIdList)) return null;
        DdlPackBean packBean = DdlPackBean.getDdlPackBean(organizeCode);
        DdlPreparedPack.getStringEqualPack(workCenterCode, MesPcnExtConstWords.WORK_CENTER_CODE, packBean);
        DdlPreparedPack.getStringEqualPack(equipmentCode, MesPcnExtConstWords.EQUIP_CODE, packBean);
        DdlPreparedPack.getNumEqualPack(MesExtEnumUtil.SPOT_CHECK_ORDER_STATUS.CREATE.getValue(), MesPcnExtConstWords.STATUS, packBean);
        if (spotCheckIdList.size() == 1) DdlPreparedPack.getNumEqualPack(spotCheckIdList.get(0), MesPcnExtConstWords.SPOT_CHECK_ID, packBean);
        else DdlPreparedPack.getInPackList(spotCheckIdList, MesPcnExtConstWords.SPOT_CHECK_ID, packBean);
        return spotCheckOrderRepository.findByHqlWhere(packBean);
    }

    @Override
    public List<MesSpotCheckOrderResult> getSpotCheckOrderResultList(String organizeCode, List<Long> spotCheckOrderIdList) {
        if (StringUtils.isEmpty(organizeCode) || CollectionUtils.isEmpty(spotCheckOrderIdList)) return null;
        DdlPackBean packBean = DdlPackBean.getDdlPackBean(organizeCode);
        if (spotCheckOrderIdList.size() == 1) DdlPreparedPack.getNumEqualPack(spotCheckOrderIdList.get(0), MesPcnExtConstWords.PID, packBean);
        else DdlPreparedPack.getInPackList(spotCheckOrderIdList, MesPcnExtConstWords.PID, packBean);
        return spotCheckOrderResultRepository.findByHqlWhere(packBean);
    }

    @Override
    public List<MesSpotCheckOrderResult> getSpotCheckOrderResultAutoItemTypeList(String organizeCode, List<Long> spotCheckOrderIdList) {
        List<MesSpotCheckOrderResult> spotCheckOrderResultList = getSpotCheckOrderResultList(organizeCode, spotCheckOrderIdList);
        return CollectionUtils.isEmpty(spotCheckOrderIdList) ? null :
                spotCheckOrderResultList.stream().filter(o -> (null != o && !StringUtils.isEmpty(o.getSpotCheckItemType()) &&
                        o.getSpotCheckItemType().compareTo(MesExtEnumUtil.SPOT_CHECK_ITEM_TYPE.AUTO.getValue()) == 0)).collect(Collectors.toList());
    }

}
