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

import cn.estsh.i3plus.ext.mes.pcn.api.base.IMesPartService;
import cn.estsh.i3plus.ext.mes.pcn.api.base.IMesProdOrgExtService;
import cn.estsh.i3plus.ext.mes.pcn.api.busi.*;
import cn.estsh.i3plus.ext.mes.pcn.apiservice.dao.IMesNcProcessingDao;
import cn.estsh.i3plus.ext.mes.pcn.pojo.model.*;
import cn.estsh.i3plus.ext.mes.pcn.pojo.util.MesPcnExtConstWords;
import cn.estsh.i3plus.mes.pcn.api.iservice.busi.ISyncFuncService;
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.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.base.util.StringUtil;
import cn.estsh.i3plus.pojo.mes.bean.*;
import cn.estsh.i3plus.pojo.mes.bean.nc.MesPartInspection;
import cn.estsh.i3plus.pojo.mes.bean.nc.MesPartInspectionDetail;
import cn.estsh.i3plus.pojo.mes.bean.nc.MesPartInspectionPerson;
import cn.estsh.i3plus.pojo.mes.bean.rework.MesReworkTask;
import cn.estsh.i3plus.pojo.mes.bean.rework.MesReworkTaskDetail;
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.exception.ImppBusiException;
import cn.estsh.impp.framework.boot.util.ResultBean;
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-05-10 15:59
 * @Modify:
 **/
@Service
@Slf4j
public class MesNcProcessingService implements IMesNcProcessingService {

    @Autowired
    private IMesProdOrgExtService prodOrgExtService;

    @Autowired
    private MesDefectRecordRepository defectRecordRepository;

    @Autowired
    private MesPartRepository partRepository;

    @Autowired
    private MesPartTypePictureRepository partTypePictureRepository;

    @Autowired
    private MesPartTypeDefectRepository partTypeDefectRepository;

    @Autowired
    private MesLocationConfigRepository locationConfigRepository;

    @Autowired
    private IMesConfigService configService;

    @Autowired
    private ISyncFuncService syncFuncService;

    @Autowired
    private MesMoveRepository moveRepository;

    @Autowired
    private IMesNcProcessingDao ncProcessingDao;
    @Autowired
    private MesProduceSnRepository produceSnRepository;

    @Autowired
    private MesPartInspectionRepository partInspectionRepository;

    @Autowired
    private MesPartInspectionDetailRepository partInspectionDetailRepository;
    @Autowired
    private MesReworkTaskRepository reworkTaskRepository;
    @Autowired
    private MesReworkTaskDetailRepository reworkTaskDetailRepository;

    @Autowired
    private MesDefectTypeRepository defectTypeRepository;

    @Autowired
    private MesOrgRepository mesOrgRDao;

    @Autowired
    private MesProductVersionRepository productVersionRepository;

    @Autowired
    private IMesProduceSnExtService produceSnExtService;

    @Autowired
    private IMesWorkOrderExtService workOrderExtService;

    @Autowired
    private MesWorkOrderRepository workOrderRepository;

    @Autowired
    private MesWorkOrderPartRepository workOrderPartRepository;

    @Autowired
    private MesPartProdGroupRepository mesPartProdGroupRao;

    @Autowired
    private MesProductionRecordRepository productionRecordRepository;

    @Autowired
    private IMesPartService mesPartService;

    @Autowired
    private IMesMoveRuleRepository mesMoveRuleRepository;

    @Autowired
    private MesPartInspectionPersonRepository mesPartInspectionPersonRepository;


    @Override
    public ListPager<MesPartInspection> queryPartInspectionByPager(MesPartInspection partInspection, Pager pager) {

        DdlPackBean packBean = DdlPackBean.getDdlPackBean(partInspection.getOrganizeCode());
        DdlPreparedPack.getStringEqualPack(partInspection.getSn(), "sn", packBean);
        DdlPreparedPack.getStringEqualPack(partInspection.getPartNo(), "partNo", packBean);
        DdlPreparedPack.getStringLikerPack(partInspection.getPartName(), "partName", packBean);
        DdlPreparedPack.getStringEqualPack(partInspection.getLotNo(), "lotNo", packBean);
        DdlPreparedPack.getNegativeNumEqualPack(partInspection.getQty(), "qty", packBean);
        DdlPreparedPack.getNumEqualPack(MesExtEnumUtil.PART_INSPECTION_STATUS.FAIL.getValue(), "inspectionStatus", packBean);
        DdlPreparedPack.getNumEqualPack(MesExtEnumUtil.PART_INSPECTION_NC_STATUS.CREATE.getValue(), "ncStatus", packBean);
        DdlPreparedPack.getNumEqualPack(partInspection.getRefundFlag(), "refundFlag", packBean);
        DdlPreparedPack.getStringEqualPack(partInspection.getCreateUser(), "createUser", packBean);
        DdlPreparedPack.getOrderByPack(new Object[]{CommonEnumUtil.ASC_OR_DESC.DESC.getValue()}, new String[]{"createDatetime"}, packBean);
        pager = PagerHelper.getPager(pager, partInspectionRepository.findByHqlWhereCount(packBean));

        List<MesPartInspection> resultList = partInspectionRepository.findByHqlWherePage(packBean, pager);

        return new ListPager<>(resultList, pager);
    }

    @Override
    public MesNcProcessingModel queryPartInspection(MesPartInspection partInspection) {

        DdlPackBean packBean = DdlPackBean.getDdlPackBean(partInspection.getOrganizeCode());
        DdlPreparedPack.getNumEqualPack(partInspection.getId(), "pid", packBean);
        List<MesPartInspectionDetail> detailList = partInspectionDetailRepository.findByHqlWhere(packBean);

        //检查物料
        MesPart part = null;
        if (partInspection.getSourceType() == MesExtEnumUtil.PART_INSPECTION_SOURCE_TYPE.SINGLE.getValue()) {

            //检查条码
            MesProduceSn produceSn = checkProduceSn(partInspection.getSn(), partInspection.getOrganizeCode());

            //检查物料
            part = checkPart(produceSn, partInspection.getOrganizeCode());

        } else {
            //检查物料
            part = checkPartByPartNo(partInspection.getPartNo(), partInspection.getOrganizeCode());
        }


        //构造返回结果
        MesNcProcessingModel model = getModel(part, detailList, partInspection.getOrganizeCode());
        model.setPartInspection(partInspection);
        return model;

    }

    @Override
    public List<MesDefectType> queryPerson(String org) {
        DdlPackBean packBean = DdlPackBean.getDdlPackBean(org);
        DdlPreparedPack.getNumEqualPack(MesExtEnumUtil.DEFECT_CATEGORY.RESPONSIBILITY.getValue(), "defectType", packBean);
        return defectTypeRepository.findByHqlWhere(packBean);
    }

    @Override
    public ListPager<MesNcProcessingPartAndLotModel> queryPartLot(String partNo, String lotNo, String org, Pager pager) {

        pager = PagerHelper.getPager(pager, ncProcessingDao.queryDefectRecordByPagerCount(partNo, lotNo, org));

        List<MesNcProcessingPartAndLotModel> modelList = ncProcessingDao.queryDefectRecordByPager(partNo, lotNo, org, pager);

        return new ListPager(modelList, pager);
    }

    @Override
    public void saveNc(MesNcProcessingInputModel model, String org, boolean isOrder) {
        if(!Objects.isNull(model.getPart())){
            model.setPart(mesPartService.getMesPartSapByPartNo(model.getPart().getPartNo(), org));
        }
        if (model.getPartInspection().getSourceType() == MesExtEnumUtil.PART_INSPECTION_SOURCE_TYPE.SINGLE.getValue()) {
            Integer type = model.getType();
            MesDefectType person = StringUtil.isEmpty(model.getPerson())?new MesDefectType():model.getPerson();

            //保存数据
            saveDate(model, model.getPart(), type, person, org,model.getInventoryLocationCode(),isOrder);
        } else {
            //保存数据
            saveLotDate(model, model.getPart(), org, isOrder);
        }
    }

    @Override
    public List<String> queryPartInspectionCreateUser(String organizeCode) {
        return ncProcessingDao.queryPartInspectionCreateUser(organizeCode);
    }

    /**
     * 检查物料
     *
     * @param produceSn
     * @param org
     * @return
     */
    private MesPart checkPart(MesProduceSn produceSn, String org) {

        DdlPackBean packBean = DdlPackBean.getDdlPackBean(org);
        DdlPreparedPack.getStringEqualPack(produceSn.getPartNo(), "partNo", packBean);
        MesPart part = partRepository.getByProperty(packBean);

        //若不存在则提示物料信息不存在
        if (StringUtils.isEmpty(part)) {
            throw new ImppBusiException(String.format("【%s】此条码对应【%s】物料号不存在，请检查数据", produceSn.getProductSn(), produceSn.getPartNo()));
        }

        //根据条码查询零件类型（partType）
        if (StringUtils.isEmpty(part.getPartTypeCode())) {
            throw new ImppBusiException(String.format("【%s】此条码对应【%s】物料号未维护零件类型，请检查数据", produceSn.getProductSn(), produceSn.getPartNo()));
        }


        return part;
    }

    private MesPart checkPartByPartNo(String partNo, String org) {

        DdlPackBean packBean = DdlPackBean.getDdlPackBean(org);
        DdlPreparedPack.getStringEqualPack(partNo, "partNo", packBean);
        MesPart part = partRepository.getByProperty(packBean);

        //若不存在则提示物料信息不存在
        if (StringUtils.isEmpty(part)) {
            throw new ImppBusiException(String.format("【%s】物料号不存在，请检查数据", partNo));
        }

        return part;
    }


    private MesPartTypePicture checkPartTypePicture(MesPart part, String org) {

        DdlPackBean packBean = DdlPackBean.getDdlPackBean(org);
        DdlPreparedPack.getStringEqualPack(part.getPartTypeCode(), "partTypeCode", packBean);

        return partTypePictureRepository.getByProperty(packBean);
    }

    private List<MesPartTypeDefect> checkPartTypeDefect(MesPart part, String org) {

        DdlPackBean packBean = DdlPackBean.getDdlPackBean(org);
        DdlPreparedPack.getStringEqualPack(part.getPartTypeCode(), "partTypeCode", packBean);
        List<MesPartTypeDefect> partTypeDefectList = partTypeDefectRepository.findByHqlWhere(packBean);

        if (CollectionUtils.isEmpty(partTypeDefectList)) {
            throw new ImppBusiException(String.format("未配置【%s】零件类型缺陷类型对应关系，请检查数据", part.getPartTypeCode()));
        }

        return partTypeDefectList;
    }

    private List<MesLocationConfig> checkLocationConfig(String org) {

        DdlPackBean packBean = DdlPackBean.getDdlPackBean(org);
        DdlPreparedPack.getOrderByPack(new Object[]{CommonEnumUtil.ASC_OR_DESC.ASC.getValue(), CommonEnumUtil.ASC_OR_DESC.ASC.getValue()}, new String[]{"rowLocation", "columnLocation"}, packBean);
        List<MesLocationConfig> configList = locationConfigRepository.findByHqlWhere(packBean);

        if (CollectionUtils.isEmpty(configList)) {
            throw new ImppBusiException(String.format("未配置位置，请检查数据"));
        }

        return configList;
    }


    /**
     * 构造返回数据
     *
     * @param part
     * @param detailList
     * @param org
     * @return
     */
    private MesNcProcessingModel getModel(MesPart part, List<MesPartInspectionDetail> detailList, String org) {
        //todo 图片暂时放空
        //检查零件类型与图片对应关系
        MesPartTypePicture partTypePicture = checkPartTypePicture(part, org);

        //位置
        List<MesLocationConfig> locationConfigList = checkLocationConfig(org);

        Map<String, List<MesPartInspectionDetail>> defectRecordMap = detailList.stream().collect(Collectors.groupingBy(k -> k.getDefectLocation()));


//        Map<String, List<MesPartInspectionDetail>> defectMap = detailList.stream().collect(Collectors.groupingBy(k -> k.getDefectTypeCode()));

        //位置是否标黄Map,key：位置，value：标黄标识
        locationConfigList.forEach(k -> {
            if (defectRecordMap.containsKey(k.getDefectLocation())) {
                k.setIsflg(true);
            }
        });

//        List<MesNcProcessingViewModel> defectModelList = new ArrayList<>();
//        defectMap.forEach((k, v) -> {
//            MesNcProcessingViewModel model = new MesNcProcessingViewModel();
//            model.setDefectTypeCode(k);
//            model.setQty(v.size());
//            model.setDefectTypeName(v.get(0).getDefectTypeName());
//            defectModelList.add(model);
//        });

        MesNcProcessingModel model = new MesNcProcessingModel();
        model.setDetailList(detailList);
        model.setPartTypePicture(partTypePicture);
        model.setLocationConfigList(locationConfigList);
        return model;
    }

    /**
     * 保存数据
     *
     * @param part
     * @param model
     * @param type
     * @param person
     * @param org
     */
    private void saveDate(MesNcProcessingInputModel model, MesPartSap part, Integer type, MesDefectType person, String org,String areaCode, boolean isOrder) {

        String workCenterCode = null == model.getPartInspection() ? null : model.getPartInspection().getWorkCenterCode();
        assert model.getPartInspection() != null;
        model.getPartInspection().setQmsSync(CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue());
        MesProduceSn sn = getProduceSn(model.getSn(), org);
        //武汉 会输入客户条码 todo 更新工单对应qcStatus
        boolean isWorkOrderQcStatus=false;
        if (!StringUtil.isEmpty(sn)){
            model.setCustSn(sn.getCustSn());
            model.setSn(sn.getProductSn());
            //排序产线 更新工单的 qcStatus
            MesWorkCenter centerDb = prodOrgExtService.getWorkCenterDb(org, sn.getWorkCenterCode());
            if (!StringUtil.isEmpty(centerDb)){
                isWorkOrderQcStatus= centerDb.getCenterType() == MesExtEnumUtil.WORK_CENTER_TYPE.SORT.getValue();
            }
        }
        // 是否头零件模式
        boolean headModel = true;
        if (!StringUtil.isEmpty(model.getSn())) {
            // 判断是头零件还是散件   查询加工记录
            DdlPackBean productionPackBean = DdlPackBean.getDdlPackBean(org);
            DdlPreparedPack.getStringEqualPack(model.getSn(), "productSn", productionPackBean);
            DdlPreparedPack.getNumNOEqualPack(MesExtEnumUtil.REPORT_STATUS.REPORT_STATUS_30.getValue(), "reportStatus", productionPackBean);
            DdlPreparedPack.getNumEqualPack(MesExtEnumUtil.MES_REPORT_TYPE.CUSTOMER_SUPPLY_MOVE.getValue(), "reportType", productionPackBean);
            MesProductionRecord record = productionRecordRepository.getByProperty(productionPackBean);
            if (record != null) {
                headModel = false;
            }
        }

        // 如果是散件模式，需要查询出对应明细
        List<MesPartModel> mesPartModels = new ArrayList<>();
        if (!headModel) {
            DdlPackBean partPackBean = DdlPackBean.getDdlPackBean(org);
            DdlPreparedPack.getStringEqualPack(model.getSn(), "workOrderNo", partPackBean);
            List<MesWorkOrderPart> workOrderParts = workOrderPartRepository.findByHqlWhere(partPackBean);
            if (!CollectionUtils.isEmpty(workOrderParts)) {
                DdlPackBean partProdBean = DdlPackBean.getDdlPackBean(org);
                DdlPreparedPack.getStringEqualPack(sn.getWorkCenterCode(), "workCenterCode", partProdBean);
                List<MesPartProdGroup> mesPartProdGroupList = mesPartProdGroupRao.findByHqlTopWhere(partProdBean, 1);
                for (MesWorkOrderPart workOrderPart : workOrderParts) {
                    MesPart partInfo = mesPartService.getMesPartByPartNo(workOrderPart.getPartNo(), org);
                    String esd = partInfo.getEsd();

                    // 查询移库规则
                    DdlPackBean movePackBean = DdlPackBean.getDdlPackBean(org);
                    DdlPreparedPack.getStringEqualPack(esd, "srcType", movePackBean);
                    DdlPreparedPack.getStringEqualPack(mesPartProdGroupList.get(0).getPartProdGroupCode(), "code", movePackBean);
                    List<MesMoveRule> moveRules = mesMoveRuleRepository.findByHqlWhere(movePackBean);
                    if (!CollectionUtils.isEmpty(moveRules)) {
                        MesPartModel mesPartModel = new MesPartModel();
                        mesPartModel.setPartNo(workOrderPart.getPartNo());
                        mesPartModel.setLocateNo(moveRules.get(0).getErpDestLocateNo());
                        mesPartModels.add(mesPartModel);
                    }
                }
            }
        }
        String source = configService.getCfgValue(org, "LGORT");
        String refundSource = configService.getCfgValue(org, "REFUND");
        if (!StringUtils.isEmpty(model.getProductVersion())) {
            DdlPackBean ddlPackBean = DdlPackBean.getDdlPackBean();
            DdlPreparedPack.getStringEqualPack(model.getPart().getPartNo(), "partNo", ddlPackBean);
            DdlPreparedPack.getStringEqualPack(model.getPartInspection().getWorkCenterCode(), "workCenterCode", ddlPackBean);
            DdlPreparedPack.getStringEqualPack(model.getProductVersion(), "productVersion", ddlPackBean);

            MesProductVersion version = productVersionRepository.getByProperty(ddlPackBean);
            if (version != null) {
                source = version.getReceiveInventoryPoint();
            }
        }


        if (type == MesExtEnumUtil.NC_TYPE.NORMAL.getValue()) {
            //批次不需要校验条码
            if (model.getPartInspection().getSourceType() == MesExtEnumUtil.PART_INSPECTION_SOURCE_TYPE.SINGLE.getValue()) {
                checkProduceSn(sn, model.getSn());
                //更新条码质量状态
                sn.setQcStatus(MesExtEnumUtil.PRODUCE_QC_STATUS.SUSPICIOUS_TO_QUALIFIED.getValue());
                ConvertBean.serviceModelUpdate(sn, model.getUserName());
                produceSnExtService.update(sn);
                //更新工单对应qcStatus
                if(isWorkOrderQcStatus){
                    MesWorkOrder workOrder = getWorkOrder(org,sn.getWorkOrderNo());
                    if (!StringUtil.isEmpty(workOrder)){
                        workOrder.setQcStatus(MesExtEnumUtil.PRODUCE_QC_STATUS.SUSPICIOUS_TO_QUALIFIED.getValue());
                        ConvertBean.serviceModelUpdate(workOrder, model.getUserName());
                        workOrderRepository.update(workOrder);
                    }
                }
            }

            //更新检验单
            if (model.getType() != 10 && model.getType() != 40) {
                model.getPartInspection().setDefectTypeId(person.getId());
            }
            model.getPartInspection().setInspectionStatus(MesExtEnumUtil.PART_INSPECTION_STATUS.QUALIFIED.getValue());
            model.getPartInspection().setNcStatus(MesExtEnumUtil.PART_INSPECTION_NC_STATUS.NORMAL.getValue());
            ConvertBean.serviceModelUpdate(model.getPartInspection(), model.getUserName());
            String sourceValue = configService.getCfgValue(org, "UMLGO");

            if (model.getOptType() == 2) {
                sourceValue = refundSource;
                model.getPartInspection().setRefundFlag(CommonEnumUtil.TRUE_OR_FALSE.TRUE.getValue());
            }

            partInspectionRepository.save(model.getPartInspection());

            String target = configService.getCfgValue(org, "LGORT");
            DdlPackBean ddlPackBean = DdlPackBean.getDdlPackBean();
            DdlPreparedPack.getStringEqualPack(model.getPart().getPartNo(), "partNo", ddlPackBean);

            MesProductVersion version = productVersionRepository.getByProperty(ddlPackBean);
            if (version != null) {
                target = version.getReceiveInventoryPoint();
            }



            if (!headModel && !CollectionUtils.isEmpty(mesPartModels) && mesPartModels.size() > 0) {
                List<MesMove> moveList = new ArrayList<>();
                for (MesPartModel mesPartModel : mesPartModels) {
                    //移库 转正常、放行：8000移至2000
                    MesMove move = createMove(model, sourceValue, mesPartModel.getLocateNo(), org, null == sn ? workCenterCode : sn.getWorkCenterCode(), MesExtEnumUtil.MOVE_TYPE.NORMAL_MOVE, mesPartModel.getPartNo());
                    ConvertBean.serviceModelInitialize(move, model.getUserName());
                    moveList.add(move);
                }
                moveRepository.saveAll(moveList);

            } else {
                //移库 转正常、放行：8000移至2000
                MesMove move = createMove(model, sourceValue, target, org, null == sn ? workCenterCode : sn.getWorkCenterCode(), MesExtEnumUtil.MOVE_TYPE.NORMAL_MOVE);
                ConvertBean.serviceModelInitialize(move, model.getUserName());
                moveRepository.save(move);
            }

        } else if (type == MesExtEnumUtil.NC_TYPE.REWORK.getValue()) {

            //生成返工单 根据责任方库区对应关系，选择哪个责任方，就移动到哪个库区（8000移至8002/8003）；
            GenSerialNoModel serialNoModel = new GenSerialNoModel("NC_REWORK");
            serialNoModel.setPartNo(part.getPartNo());
            ResultBean rb = syncFuncService.syncSerialNo(serialNoModel, model.getPartInspection().getModifyUser(), org, 1);
            String rework = "";
            if (null != rb && !CollectionUtils.isEmpty(rb.getResultList())) {
                rework = (rb.getResultList().get(0)).toString();
            }

            MesReworkTask reworkTask = new MesReworkTask();
            reworkTask.setQty(model.getPartInspection().getQty());
            reworkTask.setSn(model.getPartInspection().getSn());
            reworkTask.setReworkOrder(rework);
            reworkTask.setStatus(MesExtEnumUtil.REWORK_TASK_STATUS.CREATE.getValue());
            reworkTask.setPartNo(model.getPartInspection().getPartNo());
            reworkTask.setPartName(model.getPartInspection().getPartName());
            reworkTask.setPartInspectionId(model.getPartInspection().getId());
            reworkTask.setOrganizeCode(org);
            reworkTask.setResponsibleParty(model.getOnlyPerson());
            reworkTask.setDisassembleType(disassembleType(model, org, sn));
            reworkTask.setLotNo(model.getPartInspection().getLotNo());
            reworkTask.setType(model.getPartInspection().getSourceType());
            ConvertBean.serviceModelInitialize(reworkTask, model.getUserName());
            reworkTaskRepository.insert(reworkTask);

            //生成返工单明细
            List<MesReworkTaskDetail> taskDetailList = new ArrayList<>();
            for (MesPartInspectionDetail detail : model.getPartInspectionDetailList()) {

                MesReworkTaskDetail taskDetail = new MesReworkTaskDetail();
                taskDetail.setPid(reworkTask.getId());
                taskDetail.setStatus(MesExtEnumUtil.REWORK_TASK_DETAIL_STATUS.REWORK_TASK_DETAIL_STATUS_10.getValue());
                taskDetail.setPartInspectionDetailId(detail.getId());
                taskDetail.setOrganizeCode(org);
                ConvertBean.serviceModelInitialize(taskDetail, model.getUserName());
                taskDetailList.add(taskDetail);

            }

            reworkTaskDetailRepository.saveAll(taskDetailList);

            model.getPartInspection().setDefectTypeId(person.getId());
            model.getPartInspection().setNcStatus(MesExtEnumUtil.PART_INSPECTION_NC_STATUS.REWORK.getValue());
            model.getPartInspection().setReworkTaskId(reworkTask.getId());
            ConvertBean.serviceModelUpdate(model.getPartInspection(),model.getUserName());
            String sourceValue = configService.getCfgValue(org, "UMLGO");

            if (model.getOptType() == 2) {
                sourceValue = refundSource;
                model.getPartInspection().setRefundFlag(CommonEnumUtil.TRUE_OR_FALSE.TRUE.getValue());
            }
            partInspectionRepository.save(model.getPartInspection());

            if (!headModel && !CollectionUtils.isEmpty(mesPartModels) && mesPartModels.size() > 0) {
                List<MesMove> moveList = new ArrayList<>();
                for (MesPartModel mesPartModel : mesPartModels) {
                    MesMove move = createMove(model, sourceValue, areaCode, org, null == sn ? workCenterCode : sn.getWorkCenterCode(), MesExtEnumUtil.MOVE_TYPE.RETURN_MOVE, mesPartModel.getPartNo());
                    ConvertBean.serviceModelInitialize(move, model.getUserName());
                    moveList.add(move);
                }
                moveRepository.saveAll(moveList);
            } else {
                MesMove move = createMove(model, sourceValue, areaCode, org, null == sn ? workCenterCode : sn.getWorkCenterCode(), MesExtEnumUtil.MOVE_TYPE.RETURN_MOVE);
                ConvertBean.serviceModelInitialize(move, model.getUserName());
                moveRepository.save(move);
            }

        } else if (type == MesExtEnumUtil.NC_TYPE.SCRAP.getValue()) {
            //批次不需要校验条码
            if (model.getPartInspection().getSourceType() == MesExtEnumUtil.PART_INSPECTION_SOURCE_TYPE.SINGLE.getValue()) {
                checkProduceSn(sn, model.getSn());
                //更新条码质量状态
                sn.setQcStatus(MesExtEnumUtil.PRODUCE_QC_STATUS.SCRAP.getValue());
                ConvertBean.serviceModelUpdate(sn, model.getUserName());
                produceSnExtService.update(sn);
                //更新工单对应qcStatus
                if(isWorkOrderQcStatus){
                    MesWorkOrder workOrder = getWorkOrder(org,sn.getWorkOrderNo());
                    if (!StringUtil.isEmpty(workOrder)){
                        workOrder.setQcStatus(MesExtEnumUtil.PRODUCE_QC_STATUS.SCRAP.getValue());
                        ConvertBean.serviceModelUpdate(workOrder, model.getUserName());
                        workOrderRepository.update(workOrder);
                    }
                }
            }

            //更新检验单
//            DdlPackBean packBean = DdlPackBean.getDdlPackBean(org);
//            DdlPreparedPack.getStringEqualPack(areaCode, "inventoryLocationCode", packBean);
//            MesOrg mesOrg = mesOrgRDao.getByProperty(packBean);
            //报废时设置责任人
            model.getPartInspection().setResponsibleParty(model.getOnlyPerson());
            model.getPartInspection().setDefectTypeId(person.getId());
            model.getPartInspection().setNcStatus(MesExtEnumUtil.PART_INSPECTION_NC_STATUS.SCRAP.getValue());
            model.getPartInspection().setRejectQty(model.getPartInspection().getQty());
            ConvertBean.serviceModelUpdate(model.getPartInspection(), model.getUserName());

            if (model.getOptType() == 2) {
                model.getPartInspection().setRefundFlag(CommonEnumUtil.TRUE_OR_FALSE.TRUE.getValue());
            }

            partInspectionRepository.save(model.getPartInspection());
            if (isOrder) {
                String sourceValue = source;
                if (model.getOptType() == 2) {
                    sourceValue = refundSource;
                }

                if (!headModel && !CollectionUtils.isEmpty(mesPartModels) && mesPartModels.size() > 0) {
                        List<MesMove> moveList = new ArrayList<>();

                        for (MesPartModel mesPartModel : mesPartModels) {
                            MesMove move = createMove(model, sourceValue, configService.getCfgValue(org, "SCRAP"), org, null == sn ? workCenterCode : sn.getWorkCenterCode(), MesExtEnumUtil.MOVE_TYPE.SCRAP_MOVE,mesPartModel.getPartNo());
                            ConvertBean.serviceModelInitialize(move,model.getUserName());
                            moveList.add(move);
                        }
                    moveRepository.saveAll(moveList);
                } else {
                    MesMove move = createMove(model, sourceValue, configService.getCfgValue(org, "SCRAP"), org, null == sn ? workCenterCode : sn.getWorkCenterCode(), MesExtEnumUtil.MOVE_TYPE.SCRAP_MOVE);
                    ConvertBean.serviceModelInitialize(move,model.getUserName());
                    moveRepository.save(move);
                }

            } else {
                String sourceValue = configService.getCfgValue(org, "UMLGO");
                if (model.getOptType() == 2) {
                    sourceValue = refundSource;
                }
                if (!headModel) {
                    if (!CollectionUtils.isEmpty(mesPartModels) && mesPartModels.size() > 0) {
                        List<MesMove> moveList = new ArrayList<>();

                        for (MesPartModel mesPartModel : mesPartModels) {
                            //移库 转报废 根据责任方库区对应关系的主数据，选择哪个责任方，就移动到哪个库区（8000移至8002/8003）
                            MesMove move = createMove(model, sourceValue, areaCode, org, null == sn ? workCenterCode : sn.getWorkCenterCode(), MesExtEnumUtil.MOVE_TYPE.SCRAP_MOVE, mesPartModel.getPartNo());
                            ConvertBean.serviceModelInitialize(move,model.getUserName());
                            moveList.add(move);
                        }
                        moveRepository.saveAll(moveList);

                    }
                } else {
                    //移库 转报废 根据责任方库区对应关系的主数据，选择哪个责任方，就移动到哪个库区（8000移至8002/8003）
                    MesMove move = createMove(model, sourceValue, areaCode, org, null == sn ? workCenterCode : sn.getWorkCenterCode(), MesExtEnumUtil.MOVE_TYPE.SCRAP_MOVE);
                    ConvertBean.serviceModelInitialize(move,model.getUserName());
                    moveRepository.save(move);
                }
            }

        } else if (type == MesExtEnumUtil.NC_TYPE.RELEASE.getValue()) {
            //批次不需要校验条码
            if (model.getPartInspection().getSourceType() == MesExtEnumUtil.PART_INSPECTION_SOURCE_TYPE.SINGLE.getValue()) {
                checkProduceSn(sn, model.getSn());
                //更新条码质量状态
                sn.setQcStatus(MesExtEnumUtil.PRODUCE_QC_STATUS.QUALIFIED.getValue());
                ConvertBean.serviceModelUpdate(sn, model.getUserName());
                produceSnExtService.update(sn);
                //更新工单对应qcStatus
                if(isWorkOrderQcStatus){
                    MesWorkOrder workOrder = getWorkOrder(org,sn.getWorkOrderNo());
                    if (!StringUtil.isEmpty(workOrder)){
                        workOrder.setQcStatus(MesExtEnumUtil.PRODUCE_QC_STATUS.QUALIFIED.getValue());
                        ConvertBean.serviceModelUpdate(workOrder, model.getUserName());
                        workOrderRepository.update(workOrder);
                    }
                }
            }

            //更新检验单
            if (model.getType() != 10 && model.getType() != 40) {
                model.getPartInspection().setDefectTypeId(person.getId());
            }
            model.getPartInspection().setInspectionStatus(MesExtEnumUtil.PART_INSPECTION_STATUS.QUALIFIED.getValue());
            model.getPartInspection().setNcStatus(MesExtEnumUtil.PART_INSPECTION_NC_STATUS.RELEASE.getValue());
            ConvertBean.serviceModelUpdate(model.getPartInspection(), model.getUserName());
            String sourceValue = configService.getCfgValue(org, "UMLGO");

            if (model.getOptType() == 2) {
                sourceValue = refundSource;

                model.getPartInspection().setRefundFlag(CommonEnumUtil.TRUE_OR_FALSE.TRUE.getValue());
            }
            partInspectionRepository.save(model.getPartInspection());

            String target = configService.getCfgValue(org, "LGORT");
            DdlPackBean ddlPackBean = DdlPackBean.getDdlPackBean();
            DdlPreparedPack.getStringEqualPack(model.getPart().getPartNo(), "partNo", ddlPackBean);

            MesProductVersion version = productVersionRepository.getByProperty(ddlPackBean);
            if (version != null) {
                target = version.getReceiveInventoryPoint();
            }

            if (!headModel && !CollectionUtils.isEmpty(mesPartModels) && mesPartModels.size() > 0) {
                List<MesMove> moveList = new ArrayList<>();

                for (MesPartModel mesPartModel : mesPartModels) {
                    //移库 转正常、放行：8000移至2000
                    MesMove move = createMove(model, sourceValue, mesPartModel.getLocateNo(), org, null == sn ? workCenterCode : sn.getWorkCenterCode(), MesExtEnumUtil.MOVE_TYPE.NORMAL_MOVE, mesPartModel.getPartNo());
                    ConvertBean.serviceModelInitialize(move, model.getUserName());
                    moveList.add(move);
                }
                moveRepository.saveAll(moveList);

            } else  {
                //移库 转正常、放行：8000移至2000
                MesMove move = createMove(model, sourceValue, target, org, null == sn ? workCenterCode : sn.getWorkCenterCode(), MesExtEnumUtil.MOVE_TYPE.NORMAL_MOVE);
                ConvertBean.serviceModelInitialize(move, model.getUserName());
                moveRepository.save(move);
            }
        }
    }

    /**
     * 保存数据
     *
     * @param part
     * @param model
     * @param org
     */
    private void saveLotDate(MesNcProcessingInputModel model, MesPartSap part,String org, boolean isOrder) {
        String workCenterCode = null == model.getPartInspection() ? null : model.getPartInspection().getWorkCenterCode();
        assert model.getPartInspection() != null;
        model.getPartInspection().setQmsSync(CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue());

        String refundSource = configService.getCfgValue(org, "REFUND");
        List<MesPartInspectionPerson> personList = new ArrayList<>();

        MesPartInspection mesPartInspection = model.getPartInspection();
        for (MesNcPersonModel mesNcPersonModel : model.getPersonModelList()) {
            Integer type = mesNcPersonModel.getNcStatus();

            if (type == MesExtEnumUtil.PART_INSPECTION_NC_STATUS.NORMAL.getValue()) {

                model.getPartInspection().setInspectionStatus(MesExtEnumUtil.PART_INSPECTION_STATUS.QUALIFIED.getValue());
                model.getPartInspection().setNcStatus(MesExtEnumUtil.PART_INSPECTION_NC_STATUS.NORMAL.getValue());
                ConvertBean.serviceModelUpdate(model.getPartInspection(), model.getUserName());
                String sourceValue = configService.getCfgValue(org, "UMLGO");

                if (model.getOptType() == 2) {
                    sourceValue = refundSource;
                    model.getPartInspection().setRefundFlag(CommonEnumUtil.TRUE_OR_FALSE.TRUE.getValue());
                }

                //partInspectionRepository.save(model.getPartInspection());

                MesPartInspectionPerson mesPartInspectionPerson = new MesPartInspectionPerson();
                mesPartInspectionPerson.setQty(Double.valueOf(mesNcPersonModel.getQty()));
                mesPartInspectionPerson.setNcStatus(mesNcPersonModel.getNcStatus());
                mesPartInspectionPerson.setSn(model.getPartInspection().getSn());
                mesPartInspectionPerson.setOrganizeCode(model.getOrganizeCode());
                mesPartInspectionPerson.setPid(model.getPartInspection().getId());
                ConvertBean.serviceModelInitialize(mesPartInspectionPerson, model.getUserName());
                personList.add(mesPartInspectionPerson);


                String target = configService.getCfgValue(org, "LGORT");
                DdlPackBean ddlPackBean = DdlPackBean.getDdlPackBean(org);
                DdlPreparedPack.getStringEqualPack(model.getPart().getPartNo(), "partNo", ddlPackBean);

                MesProductVersion version = productVersionRepository.getByProperty(ddlPackBean);
                if (version != null) {
                    target = version.getReceiveInventoryPoint();
                }

                //移库 转正常、放行：8000移至2000
                MesMove move = createLotMove(model,mesNcPersonModel.getQty(), sourceValue, target, org, workCenterCode, MesExtEnumUtil.MOVE_TYPE.NORMAL_MOVE);
                ConvertBean.serviceModelInitialize(move, model.getUserName());
                moveRepository.save(move);
            }
            else if (type == MesExtEnumUtil.PART_INSPECTION_NC_STATUS.REWORK.getValue()) {

                //生成返工单 根据责任方库区对应关系，选择哪个责任方，就移动到哪个库区（8000移至8002/8003）；
                GenSerialNoModel serialNoModel = new GenSerialNoModel("NC_REWORK");
                serialNoModel.setPartNo(part.getPartNo());
                ResultBean rb = syncFuncService.syncSerialNo(serialNoModel, model.getPartInspection().getModifyUser(), org, 1);
                String rework = "";
                if (null != rb && !CollectionUtils.isEmpty(rb.getResultList())) {
                    rework = (rb.getResultList().get(0)).toString();
                }
                MesPartInspectionPerson mesPartInspectionPerson = new MesPartInspectionPerson();
                mesPartInspectionPerson.setQty(Double.valueOf(mesNcPersonModel.getQty()));
                mesPartInspectionPerson.setNcStatus(mesNcPersonModel.getNcStatus());
                mesPartInspectionPerson.setSn(model.getPartInspection().getSn());
                mesPartInspectionPerson.setOrganizeCode(model.getOrganizeCode());
                mesPartInspectionPerson.setPid(model.getPartInspection().getId());

                DdlPackBean partyPackBean = DdlPackBean.getDdlPackBean(org);
                DdlPreparedPack.getStringEqualPack(mesNcPersonModel.getOnlyPerson(), "responsibleParty", partyPackBean);
                MesOrg mesOrg = mesOrgRDao.getByProperty(partyPackBean);

                mesPartInspectionPerson.setResponsibleParty(mesOrg.getResponsibleParty());
                ConvertBean.serviceModelInitialize(mesPartInspectionPerson, model.getUserName());
                personList.add(mesPartInspectionPerson);

                MesReworkTask reworkTask = new MesReworkTask();
                reworkTask.setQty(mesNcPersonModel.getQty());
                reworkTask.setSn(model.getPartInspection().getSn());
                reworkTask.setReworkOrder(rework);
                reworkTask.setStatus(MesExtEnumUtil.REWORK_TASK_STATUS.CREATE.getValue());
                reworkTask.setPartNo(model.getPartInspection().getPartNo());
                reworkTask.setPartName(model.getPartInspection().getPartName());
                reworkTask.setPartInspectionId(model.getPartInspection().getId());
                reworkTask.setOrganizeCode(org);
                reworkTask.setResponsibleParty(mesNcPersonModel.getOnlyPerson());
                reworkTask.setDisassembleType(MesPcnExtConstWords.ZERO);
                reworkTask.setLotNo(model.getPartInspection().getLotNo());
                reworkTask.setType(model.getPartInspection().getSourceType());
                ConvertBean.serviceModelInitialize(reworkTask, model.getUserName());
                reworkTaskRepository.insert(reworkTask);

                //生成返工单明细
                List<MesReworkTaskDetail> taskDetailList = new ArrayList<>();
                for (MesPartInspectionDetail detail : model.getPartInspectionDetailList()) {

                    MesReworkTaskDetail taskDetail = new MesReworkTaskDetail();
                    taskDetail.setPid(reworkTask.getId());
                    taskDetail.setStatus(MesExtEnumUtil.REWORK_TASK_DETAIL_STATUS.REWORK_TASK_DETAIL_STATUS_10.getValue());
                    taskDetail.setPartInspectionDetailId(detail.getId());
                    taskDetail.setOrganizeCode(org);
                    ConvertBean.serviceModelInitialize(taskDetail, model.getUserName());
                    taskDetailList.add(taskDetail);

                }

                reworkTaskDetailRepository.saveAll(taskDetailList);

                //model.getPartInspection().setDefectTypeId(person.getId());
                model.getPartInspection().setNcStatus(MesExtEnumUtil.PART_INSPECTION_NC_STATUS.REWORK.getValue());
                model.getPartInspection().setReworkTaskId(reworkTask.getId());
                ConvertBean.serviceModelUpdate(model.getPartInspection(),model.getUserName());
                String sourceValue = configService.getCfgValue(org, "UMLGO");

                if (model.getOptType() == 2) {
                    sourceValue = refundSource;
                    model.getPartInspection().setRefundFlag(CommonEnumUtil.TRUE_OR_FALSE.TRUE.getValue());
                }
                //partInspectionRepository.save(model.getPartInspection());

                MesMove move = createLotMove(model,mesNcPersonModel.getQty(), sourceValue, mesNcPersonModel.getInventoryLocationCode(), org,workCenterCode, MesExtEnumUtil.MOVE_TYPE.RETURN_MOVE);
                ConvertBean.serviceModelInitialize(move, model.getUserName());
                moveRepository.save(move);

            } else if (type == MesExtEnumUtil.PART_INSPECTION_NC_STATUS.SCRAP.getValue()) {
                //报废时设置责任人
                model.getPartInspection().setResponsibleParty(mesNcPersonModel.getOnlyPerson());
                //model.getPartInspection().setDefectTypeId(person.getId());
                model.getPartInspection().setNcStatus(MesExtEnumUtil.PART_INSPECTION_NC_STATUS.SCRAP.getValue());
                model.getPartInspection().setRejectQty(model.getPartInspection().getQty());
                ConvertBean.serviceModelUpdate(model.getPartInspection(), model.getUserName());

                if (model.getOptType() == 2) {
                    model.getPartInspection().setRefundFlag(CommonEnumUtil.TRUE_OR_FALSE.TRUE.getValue());
                }

                //partInspectionRepository.save(model.getPartInspection());

                MesPartInspectionPerson mesPartInspectionPerson = new MesPartInspectionPerson();
                mesPartInspectionPerson.setQty(Double.valueOf(mesNcPersonModel.getQty()));
                mesPartInspectionPerson.setNcStatus(mesNcPersonModel.getNcStatus());
                mesPartInspectionPerson.setSn(model.getPartInspection().getSn());
                mesPartInspectionPerson.setOrganizeCode(model.getOrganizeCode());
                mesPartInspectionPerson.setPid(model.getPartInspection().getId());

                DdlPackBean partyPackBean = DdlPackBean.getDdlPackBean(org);
                DdlPreparedPack.getStringEqualPack(mesNcPersonModel.getOnlyPerson(), "responsibleParty", partyPackBean);
                MesOrg mesOrg = mesOrgRDao.getByProperty(partyPackBean);
                if (mesOrg ==null) {
                    throw new ImppBusiException(String.format("责任人【%s】不存在", mesNcPersonModel.getOnlyPerson()));
                }
                mesPartInspectionPerson.setResponsibleParty(mesOrg.getResponsibleParty());
                ConvertBean.serviceModelInitialize(mesPartInspectionPerson, model.getUserName());
                personList.add(mesPartInspectionPerson);

                String sourceValue = configService.getCfgValue(org, "UMLGO");
                if (model.getOptType() == 2) {
                    sourceValue = refundSource;
                }
                //移库 转报废 根据责任方库区对应关系的主数据，选择哪个责任方，就移动到哪个库区（8000移至8002/8003）
                MesMove move = createLotMove(model,mesNcPersonModel.getQty(), sourceValue, mesNcPersonModel.getInventoryLocationCode(), org, workCenterCode, MesExtEnumUtil.MOVE_TYPE.SCRAP_MOVE);
                ConvertBean.serviceModelInitialize(move,model.getUserName());
                moveRepository.save(move);
            } else if (type == MesExtEnumUtil.PART_INSPECTION_NC_STATUS.RELEASE.getValue()) {
                //更新检验单
               /* if (model.getType() != 10 && model.getType() != 40) {
                    model.getPartInspection().setDefectTypeId(person.getId());
                }*/
                model.getPartInspection().setInspectionStatus(MesExtEnumUtil.PART_INSPECTION_STATUS.QUALIFIED.getValue());
                model.getPartInspection().setNcStatus(MesExtEnumUtil.PART_INSPECTION_NC_STATUS.RELEASE.getValue());
                ConvertBean.serviceModelUpdate(model.getPartInspection(), model.getUserName());
                String sourceValue = configService.getCfgValue(org, "UMLGO");

                if (model.getOptType() == 2) {
                    sourceValue = refundSource;
                    model.getPartInspection().setRefundFlag(CommonEnumUtil.TRUE_OR_FALSE.TRUE.getValue());
                }
                //partInspectionRepository.save(model.getPartInspection());


                MesPartInspectionPerson mesPartInspectionPerson = new MesPartInspectionPerson();
                mesPartInspectionPerson.setQty(Double.valueOf(mesNcPersonModel.getQty()));
                mesPartInspectionPerson.setNcStatus(mesNcPersonModel.getNcStatus());
                mesPartInspectionPerson.setSn(model.getPartInspection().getSn());
                mesPartInspectionPerson.setOrganizeCode(model.getOrganizeCode());
                mesPartInspectionPerson.setPid(model.getPartInspection().getId());

                ConvertBean.serviceModelInitialize(mesPartInspectionPerson, model.getUserName());
                personList.add(mesPartInspectionPerson);


                String target = configService.getCfgValue(org, "LGORT");
                DdlPackBean ddlPackBean = DdlPackBean.getDdlPackBean();
                DdlPreparedPack.getStringEqualPack(model.getPart().getPartNo(), "partNo", ddlPackBean);

                MesProductVersion version = productVersionRepository.getByProperty(ddlPackBean);
                if (version != null) {
                    target = version.getReceiveInventoryPoint();
                }
                //移库 转正常、放行：8000移至2000
                MesMove move = createLotMove(model,mesNcPersonModel.getQty(), sourceValue, target, org, workCenterCode, MesExtEnumUtil.MOVE_TYPE.NORMAL_MOVE);
                ConvertBean.serviceModelInitialize(move, model.getUserName());
                moveRepository.save(move);

            }
        }
        mesPartInspection.setNcStatus(MesExtEnumUtil.PART_INSPECTION_NC_STATUS.SUCCESS.getValue());
        ConvertBean.serviceModelUpdate(mesPartInspection, model.getUserName());
        partInspectionRepository.save(mesPartInspection);
        mesPartInspectionPersonRepository.saveAll(personList);
    }



    public MesWorkOrder getWorkOrder(String organizeCode, String workOrderNo) {
        if (StringUtils.isEmpty(organizeCode) || StringUtils.isEmpty(workOrderNo)) return null;
        return workOrderRepository.getByProperty(
                new String[]{MesPcnExtConstWords.ORGANIZE_CODE, MesPcnExtConstWords.IS_DELETED, MesPcnExtConstWords.IS_VALID, MesPcnExtConstWords.WORK_ORDER_NO},
                new Object[]{organizeCode, CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue(), CommonEnumUtil.IS_VAILD.VAILD.getValue(), workOrderNo});
    }
    private int disassembleType(MesNcProcessingInputModel model, String org, MesProduceSn sn) {
        if (MesExtEnumUtil.PART_INSPECTION_SOURCE_TYPE.SINGLE.getValue() == model.getPartInspection().getSourceType()) {
            if (Objects.isNull(sn)) {
                throw new ImppBusiException(String.format("【%s】此条码不存在，请检查数据", model.getSn()));
            }
            //产线信息
            MesWorkCenter centerDb = prodOrgExtService.getWorkCenterDb(org, sn.getWorkCenterCode());
            if (Objects.isNull(centerDb)) {
                throw new ImppBusiException(String.format("产线【%s】信息不存在，请检查数据", sn.getWorkCenterCode()));
            }
            //拆解类型
            if (MesExtEnumUtil.WORK_CENTER_TYPE.SORT.getValue() == centerDb.getCenterType()) {
                return MesExtEnumUtil.REWORK_TASK_DISASSEMBLE_TYPE.SORT_DISASSEMBLE.getValue();
            } else if (MesExtEnumUtil.WORK_CENTER_TYPE.NOSORT.getValue() == centerDb.getCenterType()) {
                return MesExtEnumUtil.REWORK_TASK_DISASSEMBLE_TYPE.NOSORT_DISASSEMBLE.getValue();
            }
        }
        return MesPcnExtConstWords.ZERO;
    }

    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));
        }

        return produceSn;
    }

    private MesProduceSn getProduceSn(String serialNumber, String org) {
        if (StringUtils.isEmpty(serialNumber)) return null;
        //根据扫描的条码查询条码是否存在
        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 (StringUtil.isEmpty(produceSn)){
            produceSn = (MesProduceSn) workOrderExtService.getWorkOrderSort(org, serialNumber, false);
        }
        return produceSn;
    }

    private MesProduceSn checkProduceSn(MesProduceSn produceSn, String serialNumber) {

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

        return produceSn;
    }

    private MesMove createMove(MesNcProcessingInputModel model, String source, String target, String org, String workCenterCode, MesExtEnumUtil.MOVE_TYPE moveType) {
        GenSerialNoModel serialNoModel = new GenSerialNoModel("INPUT_DEFECT_ZRSUM");
        serialNoModel.setPartNo(model.getPart().getPartNo());
        ResultBean rb = syncFuncService.syncSerialNo(serialNoModel, model.getPartInspection().getModifyUser(), org, 1);
        String zrsum = "";
        if (null != rb && !CollectionUtils.isEmpty(rb.getResultList())) {
            zrsum = (rb.getResultList().get(0)).toString();
        }

        MesMove move = new MesMove();
        move.setMatnr(model.getPart().getPartNo());
        move.setOrganizeCode(org);
        move.setFactoryCode(org);
        move.setLgort(source);
        move.setUmlgo(target);
        move.setMenge(model.getPartInspection().getQty());
        move.setMeins(model.getPart().getUnit());
        move.setZrsum(zrsum);
        move.setPostDate(TimeTool.getToday());
        move.setPostTime(TimeTool.getTimeShortWithColon());
        move.setMoveType(moveType.getValue());
        move.setPartInspectionId(model.getPartInspection().getId());
        move.setProductSn(model.getSn());
        move.setWorkCenter(prodOrgExtService.getErpWorkCenterCode(org, workCenterCode));
        return move;
    }

    private MesMove createLotMove(MesNcProcessingInputModel model,double qty, String source, String target, String org, String workCenterCode, MesExtEnumUtil.MOVE_TYPE moveType) {
        GenSerialNoModel serialNoModel = new GenSerialNoModel("INPUT_DEFECT_ZRSUM");
        serialNoModel.setPartNo(model.getPart().getPartNo());
        ResultBean rb = syncFuncService.syncSerialNo(serialNoModel, model.getPartInspection().getModifyUser(), org, 1);
        String zrsum = "";
        if (null != rb && !CollectionUtils.isEmpty(rb.getResultList())) {
            zrsum = (rb.getResultList().get(0)).toString();
        }

        MesMove move = new MesMove();
        move.setMatnr(model.getPart().getPartNo());
        move.setOrganizeCode(org);
        move.setFactoryCode(org);
        move.setLgort(source);
        move.setUmlgo(target);
        move.setMenge(qty);
        move.setMeins(model.getPart().getUnit());
        move.setZrsum(zrsum);
        move.setPostDate(TimeTool.getToday());
        move.setPostTime(TimeTool.getTimeShortWithColon());
        move.setMoveType(moveType.getValue());
        move.setPartInspectionId(model.getPartInspection().getId());
        move.setProductSn(model.getSn());
        move.setWorkCenter(prodOrgExtService.getErpWorkCenterCode(org, workCenterCode));
        return move;
    }

    private MesMove createMove(MesNcProcessingInputModel model, String source, String target, String org, String workCenterCode, MesExtEnumUtil.MOVE_TYPE moveType, String partNo) {
        GenSerialNoModel serialNoModel = new GenSerialNoModel("INPUT_DEFECT_ZRSUM");
        serialNoModel.setPartNo(partNo);
        ResultBean rb = syncFuncService.syncSerialNo(serialNoModel, model.getPartInspection().getModifyUser(), org, 1);
        String zrsum = "";
        if (null != rb && !CollectionUtils.isEmpty(rb.getResultList())) {
            zrsum = (rb.getResultList().get(0)).toString();
        }

        MesMove move = new MesMove();
        move.setMatnr(partNo);
        move.setOrganizeCode(org);
        move.setFactoryCode(org);
        move.setLgort(source);
        move.setUmlgo(target);
        move.setMenge(model.getPartInspection().getQty());
        move.setMeins(model.getPart().getUnit());
        move.setZrsum(zrsum);
        move.setPostDate(TimeTool.getToday());
        move.setPostTime(TimeTool.getTimeShortWithColon());
        move.setMoveType(moveType.getValue());
        move.setPartInspectionId(model.getPartInspection().getId());
        move.setProductSn(model.getSn());
        move.setWorkCenter(prodOrgExtService.getErpWorkCenterCode(org, workCenterCode));
        return move;
    }
}
