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

import cn.estsh.i3plus.ext.mes.pcn.api.busi.IMesAssemblyExtService;
import cn.estsh.i3plus.ext.mes.pcn.api.busi.IMesNumberRuleMatchDispatchService;
import cn.estsh.i3plus.ext.mes.pcn.pojo.context.MesProductionAssemblyContext;
import cn.estsh.i3plus.ext.mes.pcn.pojo.util.MesPcnExtConstWords;
import cn.estsh.i3plus.pojo.mes.bean.MesProductionAssemblyUnique;
import cn.estsh.i3plus.pojo.mes.util.MesExtEnumUtil;
import cn.estsh.impp.framework.boot.util.SpringContextsUtil;
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.List;
import java.util.Map;
import java.util.Optional;

/**
 * 外协件规则匹配且唯一
 */
@Slf4j
@Service
public class MesNumberRuleMatchAndUniqueService implements IMesNumberRuleMatchDispatchService {

    @Autowired
    private IMesAssemblyExtService assemblyExtService;

    @Override
    public Map<String, Object> matchNumberRule(String organizeCode, String sn, Object... params) {
        // 校验正则表达式
        Map<String, Object> result = ((IMesNumberRuleMatchDispatchService) SpringContextsUtil.getBean(MesExtEnumUtil.ASSEMBLY_MATCH_TYPE.MATCH_TYPE_20.getStrategyClass())).matchNumberRule(organizeCode, sn, params);

        if (!(Boolean) result.get(MesPcnExtConstWords.RESULT)) return result;

        if (!MesProductionAssemblyContext.class.isAssignableFrom(params[0].getClass())) {
            result.put(MesPcnExtConstWords.RESULT, false);
            result.put(MesPcnExtConstWords.MESSAGE, "参数匹配规则信息不是装配件匹配规则!");
            return result;
        }

        List<MesProductionAssemblyUnique> productionAssemblyUniqueList = assemblyExtService.getProductionAssemblyUniqueList(organizeCode, sn);

        Optional<MesProductionAssemblyUnique> optional = CollectionUtils.isEmpty(productionAssemblyUniqueList) ? null :
                productionAssemblyUniqueList.stream().filter(o -> (null != o && o.getAssemblyStatus().compareTo(MesExtEnumUtil.ASSEMBLY_STATUS.ASSEMBLY_STATUS_10.getValue()) == 0)).findFirst();

        if (null != optional && optional.isPresent()) {
            result.put(MesPcnExtConstWords.RESULT, false);
            result.put(MesPcnExtConstWords.MESSAGE, String.format("条码[%s]状态[已装配]!", sn));
            return result;
        }

        return result;

    }

}
