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

import cn.estsh.i3plus.ext.mes.pcn.apiservice.serviceimpl.rulematch.MesNumberRuleMatchRegularExpressionService;
import cn.estsh.i3plus.ext.mes.pcn.apiservice.util.MesPcnException;
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.base.enumutil.CommonEnumUtil;
import cn.estsh.i3plus.pojo.mes.bean.MesPart;
import cn.estsh.i3plus.pojo.mes.repository.MesPartRepository;
import cn.estsh.i3plus.pojo.mes.util.MesExtEnumUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * 外协件条码加料
 */
@Slf4j
@Component
public class MesContainerBindCooperationPartService extends MesAbstractContainerBindDispatchService {
    @Autowired
    private MesPartRepository mesPartRDao;
    @Autowired
    private MesNumberRuleMatchRegularExpressionService matchRegularService;

    public MesContainerBindCooperationPartService() {
        super(null, MesExtEnumUtil.CONTAINER_PART_MATCH_TYPE.MATCH_TYPE_20);
    }

    @Override
    public Map<String, Object> matchNumberRule(String organizeCode, String barcode, MesContainerPartsModel model) {
        Map<String, Object> result = new HashMap<>();
        result.put(MesPcnExtConstWords.RESULT, false);
        result.put(MesPcnExtConstWords.DATA_TYPE, MesExtEnumUtil.CONTAINER_BARCODE_DATA_TYPE.STATUS_10.getValue());

        Map<String, Object> matchNumberResult = matchRegularService.matchNumberRule(organizeCode, barcode, "", model.getMatchRule());
        if (!Objects.equals(matchNumberResult.get(MesPcnExtConstWords.RESULT), true)) {
            return matchNumberResult;
        }

        MesPart mesPart = mesPartRDao.getByProperty(
                new String[]{MesPcnExtConstWords.ORGANIZE_CODE, MesPcnExtConstWords.IS_DELETED, MesPcnExtConstWords.IS_VALID, "partNo"},
                new Object[]{organizeCode, CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue(), CommonEnumUtil.IS_VAILD.VAILD.getValue(), model.getPartNo()});
        if (mesPart == null) {
            MesPcnException.throwMesBusiException("零件号【%s】在物料表不存在, 请检查数据！", model.getPartNo());
        }

        if (Objects.equals(model.getContainerType(), MesExtEnumUtil.CONTAINER_TYPE.CONTAINER_TYPE_50.getValue())) {
            Double netWeight = getRawSnWeightQty(organizeCode, barcode);
            result.put(MesPcnExtConstWords.QTY, netWeight);
        }
        result.put(MesPcnExtConstWords.RESULT, true);
        return result;
    }
}
