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

import cn.estsh.i3plus.ext.mes.pcn.api.base.ISxWorkOrderExtService;
import cn.estsh.i3plus.ext.mes.pcn.api.base.IWorkCenterExtService;
import cn.estsh.i3plus.ext.mes.pcn.api.busi.IPackageExtService;
import cn.estsh.i3plus.ext.mes.pcn.api.busi.IProduceSnExtService;
import cn.estsh.i3plus.ext.mes.pcn.api.busi.ISxWeighManageService;
import cn.estsh.i3plus.ext.mes.pcn.pojo.bean.*;
import cn.estsh.i3plus.ext.mes.pcn.pojo.model.WeighManageInfoDetailModel;
import cn.estsh.i3plus.ext.mes.pcn.pojo.model.WeighManageInfoModel;
import cn.estsh.i3plus.ext.mes.pcn.pojo.model.WeighManageWorkOrderModel;
import cn.estsh.i3plus.ext.mes.pcn.pojo.repository.MesWeighManagerDetailRepository;
import cn.estsh.i3plus.ext.mes.pcn.pojo.repository.MesWeighManagerRepository;
import cn.estsh.i3plus.ext.mes.pcn.pojo.repository.MesWeighRepository;
import cn.estsh.i3plus.ext.mes.pcn.pojo.util.MesPcnExtConstWords;
import cn.estsh.i3plus.ext.mes.pcn.pojo.util.MesPcnExtEnumUtil;
import cn.estsh.i3plus.mes.pcn.api.iservice.busi.ISyncFuncService;
import cn.estsh.i3plus.platform.common.convert.ConvertBean;
import cn.estsh.i3plus.platform.common.exception.ImppExceptionEnum;
import cn.estsh.i3plus.platform.common.tool.MathOperation;
import cn.estsh.i3plus.pojo.base.bean.BaseResultBean;
import cn.estsh.i3plus.pojo.base.enumutil.CommonEnumUtil;
import cn.estsh.i3plus.pojo.mes.bean.MesPackageDetail;
import cn.estsh.i3plus.pojo.mes.model.GenSerialNoModel;
import cn.estsh.impp.framework.boot.exception.ImppExceptionBuilder;
import lombok.extern.slf4j.Slf4j;
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.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author wangjie
 * @version 1.0
 * @date 2021/1/13 9:28
 **/
@Slf4j
@Service
public class SxWeighManageService implements ISxWeighManageService {

    @Autowired
    private IWorkCenterExtService workCenterExtService;

    @Autowired
    private ISxWorkOrderExtService workOrderExtService;

    @Autowired
    private MesWeighRepository weighRepository;

    @Autowired
    private MesWeighManagerRepository weighManagerRepository;

    @Autowired
    private MesWeighManagerDetailRepository weighManagerDetailRepository;

    @Autowired
    private ISyncFuncService syncFuncService;

    @Autowired
    private IProduceSnExtService produceSnExtService;

    @Autowired
    private IPackageExtService packageExtService;

    @Override
    public List<MesWorkCenterExt> queryCenterList(String organizeCode) {
        return workCenterExtService.getWorkCenterExtList(organizeCode);
    }

    @Override
    public List<WeighManageWorkOrderModel> queryWorkOrderList(WeighManageWorkOrderModel model) {
        if (StringUtils.isEmpty(model.getWorkCenterCode()) && StringUtils.isEmpty(model.getWorkOrderNo())) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES_PCN.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                    .setErrorDetail("请选择生产线或输入工单号查询")
                    .build();
        }
        List<WeighManageWorkOrderModel> resultList = null;
        List<MesWorkOrderExt> workOrderExtList = null;
        if (StringUtils.isEmpty(model.getWorkOrderNo())) {
            workOrderExtList = workOrderExtService.
                    getWorkOrderListByCenterAndStatusOrderByStartTime(model.getOrganizeCode(), model.getWorkCenterCode(), MesPcnExtEnumUtil.WORK_ORDER_STATUS.OPEN.getValue());
        } else {
            MesWorkOrderExt workOrderExt = workOrderExtService.getWorkOrderExtByOrderNo(model.getOrganizeCode(), model.getWorkOrderNo());
            if (null != workOrderExt) {
                workOrderExtList = new ArrayList<>();
                workOrderExtList.add(workOrderExt);
            }
        }

        if (!CollectionUtils.isEmpty(workOrderExtList)) {
            for (MesWorkOrderExt workOrderExt : workOrderExtList) {
                if (null == workOrderExt) {
                    continue;
                }
                if (CollectionUtils.isEmpty(resultList)) {
                    resultList = new ArrayList<>();
                }
                WeighManageWorkOrderModel result = new WeighManageWorkOrderModel();
                result.setWorkOrderNo(workOrderExt.getOrderNo());
                result.setPartNo(workOrderExt.getPartNo());
                result.setPartNameRdd(workOrderExt.getPartNameRdd());
                result.setStartTime(workOrderExt.getStartTime());
                result.setWorkCenterCode(workOrderExt.getWorkCenterCode());
                resultList.add(result);
            }
        }

        return resultList;
    }

    @Override
    public List<WeighManageWorkOrderModel> queryWeighManageOrderList(String organizeCode, String workOrderNo) {
        List<WeighManageWorkOrderModel> resultList = null;
        List<MesWeighManager> weighManagerList = weighManagerRepository.findByProperty(
                new String[]{MesPcnExtConstWords.ORGANIZE_CODE, MesPcnExtConstWords.IS_DELETED, MesPcnExtConstWords.IS_VALID, MesPcnExtConstWords.ORDER_NO},
                new Object[]{organizeCode, CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue(), CommonEnumUtil.IS_VAILD.VAILD.getValue(), workOrderNo},
                " order by createDatetime desc ");
        weighManagerList = CollectionUtils.isEmpty(weighManagerList) ? null :
                weighManagerList.stream().filter(o -> (null != o && MesPcnExtEnumUtil.CONFIRM_TYPE.NO.getValue() == o.getCartonConfirmCheck())).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(weighManagerList)) {
            for (MesWeighManager weighManager : weighManagerList) {
                if (null == weighManager) {
                    continue;
                }
                if (CollectionUtils.isEmpty(resultList)) {
                    resultList = new ArrayList<>();
                }
                WeighManageWorkOrderModel result = new WeighManageWorkOrderModel();
                result.setId(weighManager.getId());
                result.setOrderJobNo(weighManager.getOrderJobNo());
                result.setWorkOrderNo(weighManager.getOrderNo());
                result.setPartNo(weighManager.getPartNo());
                result.setPartNameRdd(weighManager.getPartName());
                result.setCreateDatetime(weighManager.getCreateDatetime());
                resultList.add(result);
            }
        }
        return resultList;
    }

    @Override
    public WeighManageInfoModel queryWeighManageOrderInfo(Long id) {
        MesWeighManager weighManager = weighManagerRepository.getById(id);
        if (null == weighManager) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES_PCN.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                    .setErrorDetail("ID[%s]的称重单据不存在", id)
                    .build();
        }
        WeighManageInfoModel result = new WeighManageInfoModel();
        BeanUtils.copyProperties(weighManager, result);
        result.setWorkOrderNo(weighManager.getOrderNo());
        result.setPartNameRdd(weighManager.getPartName());
        if (MathOperation.compareTo(result.getFinishWeighNum(), result.getWeighNum()) >= 0) {
            result.setScanReadOnlyFlag(true);
            if (MesPcnExtEnumUtil.CONFIRM_TYPE.NO.getValue() == weighManager.getCartonConfirmCheck()) {
                result.setConfirmReadOnlyFlag(false);
            } else {
                result.setConfirmReadOnlyFlag(true);
            }
        } else {
            result.setScanReadOnlyFlag(false);
            result.setConfirmReadOnlyFlag(true);
        }

        if (!StringUtils.isEmpty(result.getAvgWeight()) && MathOperation.compareTo(result.getAvgWeight(), new Double(0)) == 0) {
            result.setAvgWeight(null);
        }
        if (!StringUtils.isEmpty(result.getRealUpLimit()) && MathOperation.compareTo(result.getRealUpLimit(), new Double(0)) == 0) {
            result.setRealUpLimit(null);
        }
        if (!StringUtils.isEmpty(result.getRealDownLimit()) && MathOperation.compareTo(result.getRealDownLimit(), new Double(0)) == 0) {
            result.setRealDownLimit(null);
        }

        return result;
    }

    @Override
    public List<WeighManageInfoDetailModel> queryWeighManageOrderInfoDetail(String organizeCode, String orderJobNo, WeighManageInfoModel weighManageInfo) {
        List<WeighManageInfoDetailModel> resultList = null;
        List<MesWeighManagerDetail> weighManagerDetailList = weighManagerDetailRepository.findByProperty(
                new String[]{MesPcnExtConstWords.ORGANIZE_CODE, MesPcnExtConstWords.IS_DELETED, MesPcnExtConstWords.IS_VALID, MesPcnExtConstWords.ORDER_JOB_NO},
                new Object[]{organizeCode, CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue(), CommonEnumUtil.IS_VAILD.VAILD.getValue(), orderJobNo},
                " order by createDatetime desc ");
        if (!CollectionUtils.isEmpty(weighManagerDetailList)) {
            for (MesWeighManagerDetail weighManagerDetail : weighManagerDetailList) {
                if (null == weighManagerDetail) {
                    continue;
                }
                WeighManageInfoDetailModel result = new WeighManageInfoDetailModel();
                BeanUtils.copyProperties(weighManagerDetail, result);
                result.setWorkOrderNo(weighManagerDetail.getOrderNo());
                result.setPartNameRdd(weighManagerDetail.getPartName());
                if (MathOperation.compareTo(weighManageInfo.getFinishWeighNum(), weighManageInfo.getWeighNum()) == 0) {
                    if (MathOperation.compareTo(weighManagerDetail.getRealWeigh(), weighManageInfo.getRealUpLimit()) > 0 ||
                            MathOperation.compareTo(weighManagerDetail.getRealWeigh(), weighManageInfo.getRealDownLimit()) < 0) {
                        result.setColor(MesPcnExtConstWords.COLOR_RED);
                    } else {
                        result.setColor(MesPcnExtConstWords.COLOR_WHITE);
                    }
                } else {
                    result.setColor(MesPcnExtConstWords.COLOR_RED);
                }
                if (CollectionUtils.isEmpty(resultList)) {
                    resultList = new ArrayList<>();
                }
                resultList.add(result);
            }
        }
        return resultList;
    }

    @Override
    public void insertWeighManageOrder(WeighManageWorkOrderModel model) {
        MesWeigh weigh = weighRepository.getByProperty(
                new String[]{MesPcnExtConstWords.ORGANIZE_CODE, MesPcnExtConstWords.IS_DELETED, MesPcnExtConstWords.IS_VALID, MesPcnExtConstWords.PART_NO},
                new Object[]{model.getOrganizeCode(), CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue(), CommonEnumUtil.IS_VAILD.VAILD.getValue(), model.getPartNo()});
        if (null == weigh) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES_PCN.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                    .setErrorDetail("物料编码[%s]未维护称重基础数据", model.getPartNo())
                    .build();
        }
        if (StringUtils.isEmpty(weigh.getDownLimit()) || StringUtils.isEmpty(weigh.getUpLimit()) || StringUtils.isEmpty(weigh.getWeighNum())) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES_PCN.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                    .setErrorDetail("物料编码[%s]维护的称重基础异常,请检查上下限值跟称重数量是否为空", model.getPartNo())
                    .build();
        }
        if (MathOperation.compareTo(weigh.getWeighNum(), new Double(0)) <= 0) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES_PCN.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                    .setErrorDetail("物料编码[%s]维护的称重基础异常,请检查称重数量是否大于0", model.getPartNo())
                    .build();
        }

        MesWeighManager weighManager = new MesWeighManager();
        weighManager.setOrderJobNo(getManagerOrderJobNo(model.getUserInfo(), model.getOrganizeCode()));
        weighManager.setOrderNo(model.getWorkOrderNo());
        weighManager.setPartNo(model.getPartNo());
        weighManager.setPartName(model.getPartNameRdd());
        weighManager.setFinishWeighNum(new Double(0));
        weighManager.setAvgWeight(new Double(0));
        weighManager.setCartonConfirmCheck(MesPcnExtEnumUtil.CONFIRM_TYPE.NO.getValue());
        weighManager.setIsQualityConfirm(MesPcnExtEnumUtil.QUALITY_CHECK.NO.getValue());
        weighManager.setIsTeamConfirm(MesPcnExtEnumUtil.SHIFT_GROUP_CHECK.NO.getValue());
        weighManager.setWorkCenterCode(model.getWorkCenterCode());
        weighManager.setRealDownLimit(new Double(0));
        weighManager.setRealUpLimit(new Double(0));
        weighManager.setStandardWeight(weigh.getStandardWeight());
        weighManager.setWeighNum(weigh.getWeighNum());
        weighManager.setUpLimit(weigh.getUpLimit());
        weighManager.setDownLimit(weigh.getDownLimit());
        weighManager.setOrganizeCode(model.getOrganizeCode());
        ConvertBean.serviceModelInitialize(weighManager, model.getUserInfo());
        weighManagerRepository.insert(weighManager);
    }

    private String getManagerOrderJobNo(String userName, String organizeCode) {
        BaseResultBean oneCodeResult = syncFuncService.syncSerialNo(new GenSerialNoModel(MesPcnExtEnumUtil.COMMON_SN.CZ_NO.getCode()), userName, organizeCode, 1);
        if (oneCodeResult != null && oneCodeResult.isSuccess()) {
            return oneCodeResult.getResultList().get(0).toString();
        } else {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES_PCN.getCode())
                    .setErrorCode(ImppExceptionEnum.CLOUD_CALL_EXCEPTION.getCode())
                    .setErrorDetail("生成唯一工单号失败")
                    .build();
        }
    }

    @Override
    public void insertWeighManageOrderDetail(WeighManageInfoDetailModel model) {
        if (MathOperation.compareTo(model.getRealWeigh(), new Double(0)) <= 0) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES_PCN.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                    .setErrorDetail("输入的重量[%s]无效", model.getRealWeigh())
                    .build();
        }
        MesWeighManager weighManager = weighManagerRepository.getById(model.getId());
        if (null == weighManager) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES_PCN.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                    .setErrorDetail("ID[%s]的称重单据不存在", model.getId())
                    .build();
        }
        if (MathOperation.compareTo(weighManager.getWeighNum(), weighManager.getFinishWeighNum()) == 0) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES_PCN.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                    .setErrorDetail("称重单据[%s]关联的包装条码数量已经满足称重数量[%s],操作失败", weighManager.getOrderJobNo(), weighManager.getWeighNum())
                    .build();
        }
        MesWeighManagerDetail weighManagerDetailDb = weighManagerDetailRepository.getByProperty(
                new String[]{MesPcnExtConstWords.ORGANIZE_CODE, MesPcnExtConstWords.IS_DELETED, MesPcnExtConstWords.IS_VALID, MesPcnExtConstWords.PACKAGENO},
                new Object[]{model.getOrganizeCode(), CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue(), CommonEnumUtil.IS_VAILD.VAILD.getValue(), model.getPackageNo()});
        if (null != weighManagerDetailDb) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES_PCN.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                    .setErrorDetail("包装条码[%s]已经被称重过,操作失败", model.getPackageNo())
                    .build();
        }
        MesPackageExt packageExt = packageExtService.getPackageByPackNo(model.getOrganizeCode(), model.getPackageNo());
        if (null == packageExt) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES_PCN.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                    .setErrorDetail("包装条码[%s]不存在", model.getPackageNo())
                    .build();
        }
        if (StringUtils.isEmpty(packageExt.getLastWorkOrderNo()) && !packageExt.getWorkOrderNo().equals(weighManager.getOrderNo())) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES_PCN.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                    .setErrorDetail("包装条码[%s]关联的工单号[%s]与当前称重单据[%s]关联的工单号[%s]不一致",
                            model.getPackageNo(), packageExt.getWorkOrderNo(), weighManager.getOrderJobNo(), weighManager.getOrderNo())
                    .build();
        }
        if (!StringUtils.isEmpty(packageExt.getLastWorkOrderNo()) && !packageExt.getLastWorkOrderNo().equals(weighManager.getOrderNo())) {
            if (packageExt.getLastWorkOrderNo().equals(packageExt.getWorkOrderNo())) {
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.MES_PCN.getCode())
                        .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                        .setErrorDetail("包装条码[%s]关联的工单号[%s]与当前称重单据[%s]关联的工单号[%s]不一致",
                                model.getPackageNo(), packageExt.getWorkOrderNo(), weighManager.getOrderJobNo(), weighManager.getOrderNo())
                        .build();
            } else {
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.MES_PCN.getCode())
                        .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                        .setErrorDetail("包装条码[%s]关联的返工工单号[%s]与当前称重单据[%s]关联的工单号[%s]不一致",
                                model.getPackageNo(), packageExt.getLastWorkOrderNo(), weighManager.getOrderJobNo(), weighManager.getOrderNo())
                        .build();
            }
        }
        MesPackageDetail packageDetail = packageExtService.getPackageDetailByPackNo(model.getOrganizeCode(), model.getPackageNo());
        if (null == packageDetail) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES_PCN.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                    .setErrorDetail("包装条码[%s]未关联产品条码", model.getPackageNo())
                    .build();
        }
        MesProduceSnExt produceSnExt = produceSnExtService.getProduceSnExtBySn(model.getOrganizeCode(), packageDetail.getSerialNumber());
        if (null == produceSnExt) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES_PCN.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                    .setErrorDetail("包装条码[%s]关联的产品条码[%s]不存在", model.getPackageNo(), packageDetail.getSerialNumber())
                    .build();
        }
        if (StringUtils.isEmpty(produceSnExt.getLastWorkOrderNo()) && !produceSnExt.getWorkOrderNo().equals(weighManager.getOrderNo())) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES_PCN.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                    .setErrorDetail("包装条码[%s]关联的产品条码[%s]关联的工单号[%s]与当前称重单据[%s]关联的工单号[%s]不一致",
                            model.getPackageNo(), produceSnExt.getSerialNumber(), produceSnExt.getWorkOrderNo(), weighManager.getOrderJobNo(), weighManager.getOrderNo())
                    .build();
        }
        if (!StringUtils.isEmpty(packageExt.getLastWorkOrderNo()) && !packageExt.getLastWorkOrderNo().equals(weighManager.getOrderNo())) {
            if (packageExt.getLastWorkOrderNo().equals(packageExt.getWorkOrderNo())) {
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.MES_PCN.getCode())
                        .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                        .setErrorDetail("包装条码[%s]关联的产品条码[%s]关联的工单号[%s]与当前称重单据[%s]关联的工单号[%s]不一致",
                                model.getPackageNo(), produceSnExt.getSerialNumber(), produceSnExt.getWorkOrderNo(), weighManager.getOrderJobNo(), weighManager.getOrderNo())
                        .build();
            } else {
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.MES_PCN.getCode())
                        .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                        .setErrorDetail("包装条码[%s]关联的产品条码[%s]关联的返工工单号[%s]与当前称重单据[%s]关联的工单号[%s]不一致",
                                model.getPackageNo(), produceSnExt.getSerialNumber(), produceSnExt.getLastWorkOrderNo(), weighManager.getOrderJobNo(), weighManager.getOrderNo())
                        .build();
            }
        }
        if (MesPcnExtEnumUtil.PRODUCE_SN_STATUS.OFFLINE.getValue() != produceSnExt.getSnStatus()) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES_PCN.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                    .setErrorDetail("包装条码[%s]关联的产品条码[%s]的条码状态为[%s],不能执行称重操作",
                            model.getPackageNo(), packageDetail.getSerialNumber(), MesPcnExtEnumUtil.PRODUCE_SN_STATUS.valueOfDescription(produceSnExt.getSnStatus()))
                    .build();
        }
        if (MesPcnExtEnumUtil.PRODUCE_SN_QC_STATUS.QUALIFIED.getValue() != produceSnExt.getQcStatus()) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES_PCN.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                    .setErrorDetail("包装条码[%s]关联的产品条码[%s]的质量状态为[%s],不能执行称重操作",
                            model.getPackageNo(), packageDetail.getSerialNumber(), MesPcnExtEnumUtil.PRODUCE_SN_QC_STATUS.valueOfDescription(produceSnExt.getQcStatus()))
                    .build();
        }

        List<MesWeighManagerDetail> weighManagerDetailList = weighManagerDetailRepository.findByProperty(
                new String[]{MesPcnExtConstWords.ORGANIZE_CODE, MesPcnExtConstWords.IS_DELETED, MesPcnExtConstWords.IS_VALID, MesPcnExtConstWords.ORDER_JOB_NO},
                new Object[]{model.getOrganizeCode(), CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue(), CommonEnumUtil.IS_VAILD.VAILD.getValue(), weighManager.getOrderJobNo()});

        MesWeighManagerDetail weighManagerDetail = new MesWeighManagerDetail();
        weighManagerDetail.setOrderJobNo(weighManager.getOrderJobNo());
        weighManagerDetail.setOrderNo(weighManager.getOrderNo());
        weighManagerDetail.setPartNo(weighManager.getPartNo());
        weighManagerDetail.setPartName(weighManager.getPartName());
        weighManagerDetail.setPackageNo(model.getPackageNo());
        weighManagerDetail.setSerialNumber(produceSnExt.getSerialNumber());
        weighManagerDetail.setRealWeigh(model.getRealWeigh());
        weighManagerDetail.setOrganizeCode(model.getOrganizeCode());
        ConvertBean.serviceModelInitialize(weighManagerDetail, model.getUserInfo());
        weighManagerDetailRepository.insert(weighManagerDetail);

        weighManager.setFinishWeighNum(MathOperation.add(weighManager.getFinishWeighNum(), new Double(1)));
        if (MathOperation.compareTo(weighManager.getFinishWeighNum(), weighManager.getWeighNum()) >= 0) {
            weighManagerDetailList.add(weighManagerDetail);
            Double realWeighAmount = weighManagerDetailList.stream().filter(o -> (null != o && !StringUtils.isEmpty(o.getRealWeigh()))).mapToDouble(MesWeighManagerDetail::getRealWeigh).sum();
            weighManager.setAvgWeight(MathOperation.div(realWeighAmount, weighManager.getFinishWeighNum(), 2));
            weighManager.setRealUpLimit(MathOperation.add(weighManager.getAvgWeight(), weighManager.getUpLimit()));
            weighManager.setRealDownLimit(MathOperation.sub(weighManager.getAvgWeight(), weighManager.getDownLimit()));
        }
        ConvertBean.serviceModelUpdate(weighManager, model.getUserInfo());
        weighManagerRepository.save(weighManager);
    }

    @Override
    public void updateWeighManageOrderCarton(WeighManageInfoModel model) {
        MesWeighManager weighManager = weighManagerRepository.getById(model.getId());
        if (null == weighManager) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES_PCN.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                    .setErrorDetail("ID[%s]的称重单据不存在", model.getId())
                    .build();
        }
        if (MathOperation.compareTo(weighManager.getFinishWeighNum(), weighManager.getWeighNum()) < 0) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES_PCN.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                    .setErrorDetail("称重单据[%s]关联的包装条码数量[%s]未满足称重数量[%s],不能执行确认纸箱操作",
                            weighManager.getOrderJobNo(), weighManager.getFinishWeighNum(), weighManager.getWeighNum())
                    .build();
        }
        if (MesPcnExtEnumUtil.CONFIRM_TYPE.YES.getValue() == weighManager.getCartonConfirmCheck()) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES_PCN.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                    .setErrorDetail("称重单据[%s]已经被[%s]在[%s]确认过纸箱,不可重复确认",
                            weighManager.getOrderJobNo(), weighManager.getCartonConfirmPerson(), weighManager.getCartonConfirmTime())
                    .build();
        }

        weighManager.setCartonConfirmCheck(MesPcnExtEnumUtil.CONFIRM_TYPE.YES.getValue());
        weighManager.setCartonConfirmPerson(model.getUserInfo());
        ConvertBean.serviceModelUpdate(weighManager, model.getUserInfo());
        weighManager.setCartonConfirmTime(weighManager.getModifyDatetime());
        weighManagerRepository.save(weighManager);
    }

}
