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

import cn.estsh.i3plus.ext.mes.pcn.api.base.IMesPartService;
import cn.estsh.i3plus.ext.mes.pcn.api.busi.IMesNumberRuleMatchDispatchService;
import cn.estsh.i3plus.ext.mes.pcn.api.busi.IMesProduceSnExtService;
import cn.estsh.i3plus.ext.mes.pcn.api.busi.recyclablepackage.IMesRecyclablePackageBindingLogService;
import cn.estsh.i3plus.ext.mes.pcn.api.busi.recyclablepackage.IMesRecyclablePackageBindingService;
import cn.estsh.i3plus.ext.mes.pcn.api.busi.recyclablepackage.IMesRecyclablePackageService;
import cn.estsh.i3plus.ext.mes.pcn.apiservice.util.MesPcnException;
import cn.estsh.i3plus.ext.mes.pcn.pojo.model.MesRecyclablePackageBindingModel;
import cn.estsh.i3plus.ext.mes.pcn.pojo.util.MesPcnExtConstWords;
import cn.estsh.i3plus.platform.common.convert.ConvertBean;
import cn.estsh.i3plus.platform.common.tool.TimeTool;
import cn.estsh.i3plus.pojo.base.bean.DdlPackBean;
import cn.estsh.i3plus.pojo.base.enumutil.CommonEnumUtil;
import cn.estsh.i3plus.pojo.base.tool.DdlPreparedPack;
import cn.estsh.i3plus.pojo.base.util.StringUtil;
import cn.estsh.i3plus.pojo.mes.bean.MesPartSap;
import cn.estsh.i3plus.pojo.mes.bean.MesProduceSn;
import cn.estsh.i3plus.pojo.mes.bean.recyclablepackage.*;
import cn.estsh.i3plus.pojo.mes.repository.recyclablepackage.MesRecyclablePackageBindingDetailRepository;
import cn.estsh.i3plus.pojo.mes.repository.recyclablepackage.MesRecyclablePackageBindingRepository;
import cn.estsh.i3plus.pojo.mes.util.MesExtEnumUtil;
import cn.estsh.impp.framework.boot.util.ResultBean;
import cn.estsh.impp.framework.boot.util.SpringContextsUtil;
import cn.estsh.impp.framework.boot.util.ValidatorBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

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

/**
 * @Description : 料箱绑定
 * @Reference :
 * @Author : junsheng.li
 * @CreateDate 2024/9/7 10:20
 * @Modify:
 **/
@Service
@Slf4j
public class MesRecyclablePackageBindingServiceImpl implements IMesRecyclablePackageBindingService {

    @Autowired
    private IMesRecyclablePackageService mesRecyclablePackageService;

    @Autowired
    private MesRecyclablePackageBindingRepository mesRecyclablePackageBindingRepository;

    @Autowired
    private MesRecyclablePackageBindingDetailRepository mesRecyclablePackageBindingDetailRepository;

    @Autowired
    private IMesProduceSnExtService mesProduceSnExtService;

    @Autowired
    private IMesPartService mesPartService;

    @Autowired
    private IMesRecyclablePackageBindingLogService mesRecyclablePackageBindingLogService;

    @Override
    public List<MesRecyclablePackageBindingDetail> findMesRecyclablePackageBindingDetailByPid(String organizeCode, long pid) {
        if (StringUtil.isEmptyAndNull(organizeCode) || StringUtil.isEmptyAndNull(pid)) {
            return null;
        }
        return mesRecyclablePackageBindingDetailRepository.findByProperty(
                new String[]{MesPcnExtConstWords.ORGANIZE_CODE, MesPcnExtConstWords.IS_DELETED, MesPcnExtConstWords.IS_VALID, MesPcnExtConstWords.PID},
                new Object[]{organizeCode, CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue(), CommonEnumUtil.IS_VAILD.VAILD.getValue(), pid});

    }

    @Override
    public Map<Long, List<MesRecyclablePackageBindingDetail>> findMesRecyclablePackageBindingDetailByPidMap(String organizeCode, List<Long> pidList) {
        if (StringUtil.isEmptyAndNull(organizeCode) || CollectionUtils.isEmpty(pidList)) {
            return null;
        }
        DdlPackBean packBean = DdlPackBean.getDdlPackBean(organizeCode);
        DdlPreparedPack.getInPackList(pidList, MesPcnExtConstWords.PID, packBean);
        List<MesRecyclablePackageBindingDetail> packageBindingDetailList = mesRecyclablePackageBindingDetailRepository.findByHqlWhere(packBean);
        return CollectionUtils.isEmpty(packageBindingDetailList) ? null : packageBindingDetailList.stream().filter(Objects::nonNull).collect(Collectors.groupingBy(MesRecyclablePackageBindingDetail::getPid));

    }

    @Override
    public int findMesRecyclablePackageBindingDetailByPidCount(String organizeCode, long pid) {
        if (StringUtil.isEmptyAndNull(organizeCode) || StringUtil.isEmptyAndNull(pid)) {
            return MesPcnExtConstWords.ZERO;
        }
        return mesRecyclablePackageBindingDetailRepository.findByPropertyCount(
                new String[]{MesPcnExtConstWords.ORGANIZE_CODE, MesPcnExtConstWords.IS_DELETED, MesPcnExtConstWords.IS_VALID, MesPcnExtConstWords.PID},
                new Object[]{organizeCode, CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue(), CommonEnumUtil.IS_VAILD.VAILD.getValue(), pid});

    }

    @Override
    public List<MesRecyclablePackageBindingDetail> findMesRecyclablePackageBindingDetailByProductSn(String organizeCode, String productSn) {
        if (StringUtil.isEmptyAndNull(organizeCode) || StringUtil.isEmptyAndNull(productSn)) {
            return null;
        }
        return mesRecyclablePackageBindingDetailRepository.findByProperty(
                new String[]{MesPcnExtConstWords.ORGANIZE_CODE, MesPcnExtConstWords.IS_DELETED, MesPcnExtConstWords.IS_VALID, MesPcnExtConstWords.PRODUCT_SN},
                new Object[]{organizeCode, CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue(), CommonEnumUtil.IS_VAILD.VAILD.getValue(), productSn});
    }

    @Override
    public MesRecyclablePackageBinding getMesRecyclablePackageBindingByPackageSn(String organizeCode, String packageSn) {
        if (StringUtil.isEmptyAndNull(organizeCode) || StringUtil.isEmptyAndNull(packageSn)) {
            return null;
        }
        return mesRecyclablePackageBindingRepository.getByProperty(
                new String[]{MesPcnExtConstWords.ORGANIZE_CODE, MesPcnExtConstWords.IS_DELETED, MesPcnExtConstWords.IS_VALID, MesPcnExtConstWords.PACKAGE_SN},
                new Object[]{organizeCode, CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue(), CommonEnumUtil.IS_VAILD.VAILD.getValue(), packageSn});
    }

    @Override
    public Map<String, List<MesRecyclablePackageBinding>> findMesRecyclablePackageBindingByPackageSnMap(String organizeCode, List<String> packageSnList) {
        if (StringUtil.isEmptyAndNull(organizeCode) || CollectionUtils.isEmpty(packageSnList)) {
            return null;
        }
        DdlPackBean packBean = DdlPackBean.getDdlPackBean(organizeCode);
        DdlPreparedPack.getInPackList(packageSnList, MesPcnExtConstWords.PACKAGE_SN, packBean);
        List<MesRecyclablePackageBinding> packageBindingList = mesRecyclablePackageBindingRepository.findByHqlWhere(packBean);
        return CollectionUtils.isEmpty(packageBindingList) ? null : packageBindingList.stream().filter(Objects::nonNull).collect(Collectors.groupingBy(MesRecyclablePackageBinding::getPackageSn));
    }

    @Override
    public List<MesRecyclablePackageBindingDetail> findMesRecyclablePackageBindingDetail(MesRecyclablePackageBindingModel mesRecyclablePackageBindingModel) {
        //回收包装绑定
        MesRecyclablePackageBinding mesRecyclablePackageBinding = getMesRecyclablePackageBindingByPackageSn(mesRecyclablePackageBindingModel.getOrganizeCode(), mesRecyclablePackageBindingModel.getPackageSn());
        if (Objects.isNull(mesRecyclablePackageBinding)) {
            return null;
        }
        //回收包装绑定明细
        return findMesRecyclablePackageBindingDetailByPid(mesRecyclablePackageBinding.getOrganizeCode(), mesRecyclablePackageBinding.getId());
    }

    @Override
    public ResultBean doScan(MesRecyclablePackageBindingModel mesRecyclablePackageBindingModel) {
        MesRecyclablePackageBinding mesRecyclablePackageBinding = null;
        String msg = MesPcnExtConstWords.EMPTY;
        switch (mesRecyclablePackageBindingModel.getType()) {
            //扫描包条码
            case 10:
                mesRecyclablePackageBinding = doScanPackageSn(mesRecyclablePackageBindingModel);
                msg = String.format("料包条码[%s]扫描成功!", mesRecyclablePackageBindingModel.getPackageSn());
                break;
            //扫描零件条码
            case 20:
                mesRecyclablePackageBinding = doScanProductSn(mesRecyclablePackageBindingModel);
                msg = String.format("零件条码[%s]扫描成功!", mesRecyclablePackageBindingModel.getProductSn());
                break;
            //清空
            case 30:
                mesRecyclablePackageBinding = deletedMesRecyclablePackageBindingDetail(mesRecyclablePackageBindingModel, true);
                msg = String.format("料包条码[%s]清空成功!", mesRecyclablePackageBindingModel.getPackageSn());
                break;
            //删除
            case 40:
                mesRecyclablePackageBinding = deletedMesRecyclablePackageBindingDetail(mesRecyclablePackageBindingModel, false);
                msg = "删除成功!";
                break;
            //关箱
            case 50:
                mesRecyclablePackageBinding = updateClosePackageBinding(mesRecyclablePackageBindingModel);
                msg = String.format("料包条码[%s]关箱成功,请扫描下一箱!", mesRecyclablePackageBindingModel.getPackageSn());
                break;
            default:
                MesPcnException.throwMesBusiException("扫描类型【%s】不存在", mesRecyclablePackageBindingModel.getType());
                break;
        }
        return ResultBean.success(msg).setResultObject(mesRecyclablePackageBinding);
    }

    @Override
    public void doMesRecyclablePackageUnBinding(MesRecyclablePackageBinding mesRecyclablePackageBinding, List<MesRecyclablePackageBindingDetail> bindingDetailList,String userName) {
        DdlPackBean packBean = DdlPackBean.getDdlPackBean(mesRecyclablePackageBinding.getOrganizeCode());
        DdlPreparedPack.getNumEqualPack(mesRecyclablePackageBinding.getId(), MesPcnExtConstWords.PID, packBean);
        mesRecyclablePackageBindingDetailRepository.updateByProperties(
                new String[]{MesPcnExtConstWords.MODIFY_USER, MesPcnExtConstWords.MODIFY_DATE_TIME, MesPcnExtConstWords.IS_DELETED, MesPcnExtConstWords.REMARK, MesPcnExtConstWords.SYSTEM_SYNC_STATUS},
                new Object[]{userName, TimeTool.getNowTime(true), CommonEnumUtil.TRUE_OR_FALSE.TRUE.getValue(), MesPcnExtConstWords.STEP_UNBINDING, CommonEnumUtil.FALSE}, packBean);
        //更新数量
        mesRecyclablePackageBinding.setTotalQty(MesPcnExtConstWords.ZERO);
        mesRecyclablePackageBinding.setStatus(MesExtEnumUtil.RECYCLABLE_PACKAGE_PACKAGE_BINDING_STATUS.UNPACKED.getValue());
        ConvertBean.serviceModelUpdate(mesRecyclablePackageBinding, userName);
        mesRecyclablePackageBindingRepository.update(mesRecyclablePackageBinding);
        //记录日志
        mesRecyclablePackageBindingLogService.insertUnBinding(mesRecyclablePackageBinding, bindingDetailList);
    }

    private MesRecyclablePackageBinding doScanPackageSn(MesRecyclablePackageBindingModel mesRecyclablePackageBindingModel) {
        //校验包装
        mesRecyclablePackageService.checkMesRecyclablePackage(mesRecyclablePackageBindingModel.getOrganizeCode(), mesRecyclablePackageBindingModel.getPackageSn());
        //绑定主表信息
        MesRecyclablePackageBinding mesRecyclablePackageBinding = getMesRecyclablePackageBindingByPackageSn(mesRecyclablePackageBindingModel.getOrganizeCode(), mesRecyclablePackageBindingModel.getPackageSn());
        if (Objects.isNull(mesRecyclablePackageBinding)) {
            //保存包装
            mesRecyclablePackageBinding = insertMesRecyclablePackageBinding(mesRecyclablePackageBindingModel);
        }
        return mesRecyclablePackageBinding;
    }

    private MesRecyclablePackageBinding doScanProductSn(MesRecyclablePackageBindingModel mesRecyclablePackageBindingModel) {
        ValidatorBean.checkNotNull(mesRecyclablePackageBindingModel.getProductSn(), "零件条码不能为空");
        //校验箱
        MesRecyclablePackageBinding mesRecyclablePackageBinding = getPackageBinding(mesRecyclablePackageBindingModel.getOrganizeCode(), mesRecyclablePackageBindingModel.getPackageSn());
        if (MesExtEnumUtil.RECYCLABLE_PACKAGE_PACKAGE_BINDING_STATUS.CLOSED.getValue() == mesRecyclablePackageBinding.getStatus()) {
            MesPcnException.throwMesBusiException("料包条码【%s】已关箱", mesRecyclablePackageBinding.getPackageSn());
        }
        //校验零件条码是否扫描
        checkIsScan(mesRecyclablePackageBindingModel);
        //查询包条码信息
        MesRecyclablePackage mesRecyclablePackage = mesRecyclablePackageService.checkMesRecyclablePackage(mesRecyclablePackageBindingModel.getOrganizeCode(), mesRecyclablePackageBindingModel.getPackageSn());
        //查询包类型
        MesRecyclablePackageType packageType = mesRecyclablePackageService.checkMesRecyclablePackageType(mesRecyclablePackage.getOrganizeCode(), mesRecyclablePackage.getPackageTypeCode());
        //查询包装零件
        List<MesRecyclablePackagePart> packagePartList = mesRecyclablePackageService.checkMesRecyclablePackagePart(mesRecyclablePackageBindingModel.getOrganizeCode(), mesRecyclablePackage.getPackageTypeCode());
        //条码信息
        MesProduceSn mesProduceSn = getMesProduceSn(mesRecyclablePackageBindingModel, packagePartList);
        //记录绑定明细
        MesRecyclablePackageBindingDetail mesRecyclablePackageBindingDetail = insertMesRecyclablePackageBindingDetail(mesRecyclablePackageBindingModel.getUserName(), mesRecyclablePackageBinding, mesProduceSn);
        //更新数量
        mesRecyclablePackageBinding.setTotalQty(findMesRecyclablePackageBindingDetailByPidCount(mesRecyclablePackageBindingModel.getOrganizeCode(), mesRecyclablePackageBinding.getId()));
        //自动关箱
        if (!Objects.isNull(packageType.getCheckPartNoFlag()) && CommonEnumUtil.TRUE_OR_FALSE.TRUE.getValue() == packageType.getCheckPartNoFlag() && getMesRecyclablePackagePart(packagePartList, mesRecyclablePackage.getPackageTypeCode(), mesProduceSn.getPartNo()).getQty().intValue() <= mesRecyclablePackageBinding.getTotalQty()) {
            mesRecyclablePackageBinding.setStatus(MesExtEnumUtil.RECYCLABLE_PACKAGE_PACKAGE_BINDING_STATUS.CLOSED.getValue());
        }
        ConvertBean.serviceModelUpdate(mesRecyclablePackageBinding, mesRecyclablePackageBindingModel.getUserName());
        mesRecyclablePackageBindingRepository.update(mesRecyclablePackageBinding);
        //记录日志
        mesRecyclablePackageBindingLogService.insertBinding(mesRecyclablePackageBinding, mesRecyclablePackageBindingDetail);
        return mesRecyclablePackageBinding;
    }

    private MesRecyclablePackagePart getMesRecyclablePackagePart(List<MesRecyclablePackagePart> packagePartList, String packageTypeCode, String partNo) {
        Optional<MesRecyclablePackagePart> packagePart = packagePartList.stream().filter(t -> t.getPartNo().toUpperCase().equals(partNo.toUpperCase())).findFirst();
        if (!packagePart.isPresent()) {
            MesPcnException.throwMesBusiException("回用包装类型【%s】零件【%s】数据不存在", packageTypeCode, partNo);
        }
        return packagePart.get();
    }

    private void checkIsScan(MesRecyclablePackageBindingModel mesRecyclablePackageBindingModel) {
        List<MesRecyclablePackageBindingDetail> detailByProductSn = findMesRecyclablePackageBindingDetailByProductSn(mesRecyclablePackageBindingModel.getOrganizeCode(), mesRecyclablePackageBindingModel.getProductSn());
        if (!CollectionUtils.isEmpty(detailByProductSn)) {
            MesPcnException.throwMesBusiException("零件条码【%s】已绑定，请勿重复绑定", mesRecyclablePackageBindingModel.getProductSn());
        }
    }

    private MesProduceSn getMesProduceSn(MesRecyclablePackageBindingModel mesRecyclablePackageBindingModel, List<MesRecyclablePackagePart> mesRecyclablePackagePartList) {
        List<MesProduceSn> produceSnList = mesProduceSnExtService.getProduceSnList(mesRecyclablePackageBindingModel.getOrganizeCode(), mesRecyclablePackageBindingModel.getProductSn());
        if (CollectionUtils.isEmpty(produceSnList)) {
            //外协件校验
            MesRecyclablePackagePart mesRecyclablePackagePart = getMesRecyclablePackagePart(mesRecyclablePackageBindingModel, mesRecyclablePackagePartList.stream().filter(t -> !Objects.isNull(t.getProductSnCheckType()) && MesExtEnumUtil.PRODUCT_SN_CHECK_TYPE.PRODUCT_SN_CHECK_TYPE_20.getValue() == t.getProductSnCheckType()).collect(Collectors.toList()));
            if (Objects.isNull(mesRecyclablePackagePart)) {
                MesPcnException.throwMesBusiException("条码【%s】不存在", mesRecyclablePackageBindingModel.getProductSn());
            }
            //封装数据
            MesPartSap mesPartSapByPartNo = mesPartService.getMesPartSapByPartNo(mesRecyclablePackagePart.getPartNo(), mesRecyclablePackageBindingModel.getOrganizeCode());
            MesProduceSn mesProduceSn = new MesProduceSn();
            mesProduceSn.setPartNo(mesRecyclablePackagePart.getPartNo());
            mesProduceSn.setPartName(mesPartSapByPartNo.getPartName());
            mesProduceSn.setProductSn(mesRecyclablePackageBindingModel.getProductSn());
            return mesProduceSn;
        }
        return produceSnList.stream().sorted(Comparator.comparing(MesProduceSn::getCreateDatetime).reversed()).collect(Collectors.toList()).iterator().next();
    }

    private MesRecyclablePackagePart getMesRecyclablePackagePart(MesRecyclablePackageBindingModel mesRecyclablePackageBindingModel, List<MesRecyclablePackagePart> mesRecyclablePackagePartList) {
        //外协件
        MesRecyclablePackagePart checkPassRecyclablePackagePart = null;
        if (!CollectionUtils.isEmpty(mesRecyclablePackagePartList)) {
            for (MesRecyclablePackagePart mesRecyclablePackagePart : mesRecyclablePackagePartList) {
                // 校验正则表达式
                if (checkRule(mesRecyclablePackageBindingModel, mesRecyclablePackagePart.getProductSnRule())) {
                    checkPassRecyclablePackagePart = mesRecyclablePackagePart;
                    break;
                }
            }
        }
        return checkPassRecyclablePackagePart;
    }

    private boolean checkRule(MesRecyclablePackageBindingModel mesRecyclablePackageBindingModel, String rule) {
        return (Boolean) ((IMesNumberRuleMatchDispatchService) SpringContextsUtil.getBean(MesExtEnumUtil.ASSEMBLY_MATCH_TYPE.MATCH_TYPE_20.getStrategyClass())).matchNumberRule(mesRecyclablePackageBindingModel.getOrganizeCode(), mesRecyclablePackageBindingModel.getProductSn(), rule, rule).get(MesPcnExtConstWords.RESULT);
    }

    private MesRecyclablePackageBindingDetail insertMesRecyclablePackageBindingDetail(String userName, MesRecyclablePackageBinding mesRecyclablePackageBinding, MesProduceSn mesProduceSn) {
        MesRecyclablePackageBindingDetail mesRecyclablePackageBindingDetail = new MesRecyclablePackageBindingDetail();
        mesRecyclablePackageBindingDetail.setOrganizeCode(mesRecyclablePackageBinding.getOrganizeCode());
        mesRecyclablePackageBindingDetail.setPid(mesRecyclablePackageBinding.getId());
        mesRecyclablePackageBindingDetail.setProductSn(mesProduceSn.getProductSn());
        mesRecyclablePackageBindingDetail.setPartNo(mesProduceSn.getPartNo());
        mesRecyclablePackageBindingDetail.setPartName(mesProduceSn.getPartName());
        mesRecyclablePackageBindingDetail.setQty(MesPcnExtConstWords.ONE);
        mesRecyclablePackageBindingDetail.setStatus(MesPcnExtConstWords.ZERO);
        mesRecyclablePackageBindingDetail.setLotNumber(mesProduceSn.getLotNo());
        mesRecyclablePackageBindingDetail.setSubType(Objects.isNull(mesProduceSn.getId()) ? MesExtEnumUtil.RECYCLABLE_PACKAGE_BINDING_DETAIL_SUB_TYPE.RECYCLABLE_PACKAGE_BINDING_DETAIL_SUB_TYPE_20.getValue() : MesExtEnumUtil.RECYCLABLE_PACKAGE_BINDING_DETAIL_SUB_TYPE.RECYCLABLE_PACKAGE_BINDING_DETAIL_SUB_TYPE_10.getValue());
        ConvertBean.serviceModelInitialize(mesRecyclablePackageBindingDetail, userName);
        return mesRecyclablePackageBindingDetailRepository.insert(mesRecyclablePackageBindingDetail);
    }

    private MesRecyclablePackageBinding insertMesRecyclablePackageBinding(MesRecyclablePackageBindingModel mesRecyclablePackageBindingModel) {
        MesRecyclablePackageBinding mesRecyclablePackageBinding = new MesRecyclablePackageBinding();
        mesRecyclablePackageBinding.setOrganizeCode(mesRecyclablePackageBindingModel.getOrganizeCode());
        mesRecyclablePackageBinding.setPackageSn(mesRecyclablePackageBindingModel.getPackageSn());
        mesRecyclablePackageBinding.setHangerPackageSn(mesRecyclablePackageBindingModel.getPackageSn());
        mesRecyclablePackageBinding.setTypeCode("10");
        mesRecyclablePackageBinding.setStatus(MesExtEnumUtil.RECYCLABLE_PACKAGE_PACKAGE_BINDING_STATUS.UNCLOSED.getValue());
        mesRecyclablePackageBinding.setTotalQty(MesPcnExtConstWords.ZERO);
        mesRecyclablePackageBinding.setFid(UUID.randomUUID().toString());
        ConvertBean.serviceModelInitialize(mesRecyclablePackageBinding, mesRecyclablePackageBindingModel.getUserName());
        mesRecyclablePackageBindingLogService.insertCreate(mesRecyclablePackageBinding);
        return mesRecyclablePackageBindingRepository.insert(mesRecyclablePackageBinding);
    }

    private MesRecyclablePackageBinding deletedMesRecyclablePackageBindingDetail(MesRecyclablePackageBindingModel mesRecyclablePackageBindingModel, boolean deleteAll) {
        if (!deleteAll && (Objects.isNull(mesRecyclablePackageBindingModel.getDetailsIds()) || mesRecyclablePackageBindingModel.getDetailsIds().length <= 0)) {
            MesPcnException.throwMesBusiException("请选择要删除的数据");
        }
        //删除数据
        MesRecyclablePackageBinding mesRecyclablePackageBinding = getPackageBinding(mesRecyclablePackageBindingModel.getOrganizeCode(), mesRecyclablePackageBindingModel.getPackageSn());
        List<MesRecyclablePackageBindingDetail> bindingDetailList = findRecyclablePackageBindingDetailList(mesRecyclablePackageBindingModel, mesRecyclablePackageBinding);
        for (MesRecyclablePackageBindingDetail detail : bindingDetailList) {
            detail.setIsDeleted(CommonEnumUtil.TRUE_OR_FALSE.TRUE.getValue());
            detail.setSystemSyncStatus(CommonEnumUtil.FALSE);
            detail.setSystemSyncDatetime(MesPcnExtConstWords.EMPTY);
            ConvertBean.serviceModelUpdate(detail, mesRecyclablePackageBindingModel.getUserName());
        }
        mesRecyclablePackageBindingDetailRepository.saveAll(bindingDetailList);
        //更新数量
        mesRecyclablePackageBinding.setTotalQty(findMesRecyclablePackageBindingDetailByPidCount(mesRecyclablePackageBindingModel.getOrganizeCode(), mesRecyclablePackageBinding.getId()));
        if (mesRecyclablePackageBinding.getTotalQty() <= MesPcnExtConstWords.ZERO) {
            mesRecyclablePackageBinding.setStatus(MesExtEnumUtil.RECYCLABLE_PACKAGE_PACKAGE_BINDING_STATUS.UNPACKED.getValue());
        }
        ConvertBean.serviceModelUpdate(mesRecyclablePackageBinding, mesRecyclablePackageBindingModel.getUserName());
        mesRecyclablePackageBindingRepository.update(mesRecyclablePackageBinding);
        //记录日志
        mesRecyclablePackageBindingLogService.insertUnBinding(mesRecyclablePackageBinding, bindingDetailList);
        return mesRecyclablePackageBinding;
    }

    private List<MesRecyclablePackageBindingDetail> findRecyclablePackageBindingDetailList(MesRecyclablePackageBindingModel mesRecyclablePackageBindingModel, MesRecyclablePackageBinding mesRecyclablePackageBinding) {
        DdlPackBean packBean = DdlPackBean.getDdlPackBean(mesRecyclablePackageBindingModel.getOrganizeCode());
        DdlPreparedPack.getNumEqualPack(mesRecyclablePackageBinding.getId(), "pid", packBean);
        DdlPreparedPack.getInPackArray(mesRecyclablePackageBindingModel.getDetailsIds(), "id", packBean);
        List<MesRecyclablePackageBindingDetail> bindingDetailList = mesRecyclablePackageBindingDetailRepository.findByHqlWhere(packBean);
        if (CollectionUtils.isEmpty(bindingDetailList)) {
            MesPcnException.throwMesBusiException("请选择数据信息不存在");
        }
        return bindingDetailList;
    }

    private MesRecyclablePackageBinding updateClosePackageBinding(MesRecyclablePackageBindingModel mesRecyclablePackageBindingModel) {
        MesRecyclablePackageBinding mesRecyclablePackageBinding = getPackageBinding(mesRecyclablePackageBindingModel.getOrganizeCode(), mesRecyclablePackageBindingModel.getPackageSn());
        if (MesExtEnumUtil.RECYCLABLE_PACKAGE_PACKAGE_BINDING_STATUS.CLOSED.getValue() == mesRecyclablePackageBinding.getStatus()) {
            MesPcnException.throwMesBusiException("料包条码【%s】已关，不能重复关箱，请重新扫描", mesRecyclablePackageBinding.getPackageSn());
        }
        if (findMesRecyclablePackageBindingDetailByPidCount(mesRecyclablePackageBinding.getOrganizeCode(), mesRecyclablePackageBinding.getId()) <= MesPcnExtConstWords.ZERO) {
            MesPcnException.throwMesBusiException("料包条码【%s】明细不能为空，请扫描零件明细", mesRecyclablePackageBinding.getPackageSn());
        }
        //更新未关箱状态
        mesRecyclablePackageBinding.setStatus(MesExtEnumUtil.RECYCLABLE_PACKAGE_PACKAGE_BINDING_STATUS.CLOSED.getValue());
        ConvertBean.serviceModelUpdate(mesRecyclablePackageBinding, mesRecyclablePackageBindingModel.getUserName());
        mesRecyclablePackageBindingRepository.update(mesRecyclablePackageBinding);
        //记录日志
        mesRecyclablePackageBindingLogService.insertClose(mesRecyclablePackageBinding);
        return mesRecyclablePackageBinding;
    }

    private MesRecyclablePackageBinding getPackageBinding(String organizeCode, String packageSn) {
        MesRecyclablePackageBinding mesRecyclablePackageBinding = getMesRecyclablePackageBindingByPackageSn(organizeCode, packageSn);
        if (Objects.isNull(mesRecyclablePackageBinding)) {
            MesPcnException.throwMesBusiException("回收包装【%s】绑定信息不存在", packageSn);
        }
        return mesRecyclablePackageBinding;
    }
}
