package cn.estsh.i3plus.ext.mes.pcn.apiservice.serviceimpl.rulematch.containerbind.checkqty;

import cn.estsh.i3plus.ext.mes.pcn.pojo.model.MesContainerPartsModel;
import cn.estsh.i3plus.ext.mes.pcn.pojo.util.MesPcnExtConstWords;
import cn.estsh.i3plus.pojo.mes.bean.MesContainerPackage;
import cn.estsh.i3plus.pojo.mes.bean.MesContainerPackageDetail;
import cn.estsh.i3plus.pojo.mes.util.MesExtEnumUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.*;

@Slf4j
@Component
public class MesContainerBindMixService extends MesAbstractContainerBindCheckQtyService {

    public MesContainerBindMixService() {
        super(MesExtEnumUtil.CONTAINER_TYPE_MIX_TYPE.MIX_TYPE_20);
    }

    @Override
    public Map<String, Object> doCheck(String organizeCode, MesContainerPackage containerPackage, List<MesContainerPackageDetail> packageDetails, List<MesContainerPartsModel> containerParts) {
        Map<String, Object> result = new HashMap<>();
        result.put(MesPcnExtConstWords.RESULT, false);
        final double packageQty = getContainerPackageQty(organizeCode, packageDetails);

        Set<String> partNoSet = new HashSet<>();
        for (MesContainerPackageDetail packageDetail : packageDetails) {
            if (StringUtils.isEmpty(packageDetail.getPartNo())) {
                continue;
            }
            partNoSet.add(packageDetail.getPartNo());
        }
        for (MesContainerPartsModel containerPart : containerParts) {
            if (containerPart.getQty() == null || !partNoSet.contains(containerPart.getPartNo())) {
                continue;
            }
            if (packageQty > containerPart.getQty()) {
                result.put(MesPcnExtConstWords.MESSAGE, String.format("容器条码[%s]超出了包装规格[%s]", containerPackage.getContainerSn(), containerPart.getQty()));
                return result;
            }
            if (packageQty == containerPart.getQty().intValue()) {
                containerPackage.setPackageStatus(MesExtEnumUtil.CONTAINER_PACKAGE_STATUS.STATUS_20.getValue());
            }
        }

        result.put(MesPcnExtConstWords.RESULT, true);
        return result;
    }
}
