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

import cn.estsh.i3plus.ext.mes.pcn.api.busi.IMesCustomerSnTransformService;
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.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.StringUtils;

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

/**
 * 自制件规则匹配【排序: 通用自制件补条码字符】
 */
@Slf4j
@Service
public class MesNumberRuleMatchSortSnGmService implements IMesNumberRuleMatchDispatchService {

    @Autowired
    private IMesCustomerSnTransformService customerSnTransformService;

    @Override
    public Map<String, Object> matchNumberRule(String organizeCode, String sn, Object... params) {

        Map<String, Object> result = new HashMap<>();
        result.put(MesPcnExtConstWords.RESULT, false);

        if (StringUtils.isEmpty(sn)) {
            result.put(MesPcnExtConstWords.MESSAGE, "参数缺失零件条码!");
            return result;
        }

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

        String productSn = customerSnTransformService.transformBarCodeGm(sn);
        if (productSn.length() == sn.length()) {
            result.put(MesPcnExtConstWords.MESSAGE, String.format("通用自制件条码固定长度为58位,零件条码[%s]长度[%s]位!", sn, sn.length()));
            return result;
        }

        // 自制件条码
        result = ((IMesNumberRuleMatchDispatchService) SpringContextsUtil.getBean(MesExtEnumUtil.ASSEMBLY_MATCH_TYPE.MATCH_TYPE_10.getStrategyClass())).matchNumberRule(organizeCode, sn, params);

        if (!(Boolean) result.get(MesPcnExtConstWords.RESULT)) result.put(MesPcnExtConstWords.MESSAGE, String.format("通用%s", result.get(MesPcnExtConstWords.MESSAGE)));
        else result.put(MesPcnExtConstWords.ASSEMBLY_SN, productSn);//落表需要使用转换后的条码

        return result;
    }
}
