package com.xisc.pm.app.service.strategy.pdrule;

import com.xisc.pm.api.dto.RuleParamDTO;
import com.xisc.pm.app.service.strategy.RuleExecStrategyFactory;
import com.xisc.pm.domain.entity.PmProContProdTtr;
import com.xisc.pm.infra.constant.RuleSetConstants;
import com.xisc.pm.infra.enums.PdRuleItemType;
import io.choerodon.core.exception.CommonException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 
 * @author jun.zeng
 *
 */
@Component
public class SampleModeCountRuleExecStrategy implements RuleExecStrategy {

    @Override
    public void afterPropertiesSet() throws Exception {
        RuleExecStrategyFactory.register(PdRuleItemType.SAMPLE_MODE_CODE_COUNT, this);
    }

    @Override
    public boolean execRule(RuleParamDTO ruleParam) {
        Map<String, Object> bizData = ruleParam.getBizData();
        String orderNo = (String) bizData.get(RuleSetConstants.ORDER_NO);
        String mscLineNo = (String) bizData.get(RuleSetConstants.MSC_LINE_NO);

        PmProContProdTtr axisPmProContProdTtr = (PmProContProdTtr) bizData.get(RuleSetConstants.AXIS_PM_PRO_CONT_PROD_ATTR);
        PmProContProdTtr pmProContProdTtr = (PmProContProdTtr) bizData.get(RuleSetConstants.PM_PRO_CONT_PROD_ATTR);
        if (null == axisPmProContProdTtr || StringUtils.isBlank(axisPmProContProdTtr.getSampleModeCode())) {
            // 读生产合同池没有找到记录，合同号【order_no】，产线号【msc_line_no】
            throw new CommonException("pm.pm_pd_rule_set_001", orderNo, mscLineNo);
        }
        
        if(null != pmProContProdTtr) {
            if("B".equals(axisPmProContProdTtr.getSampleModeCode())) {
                if(!pmProContProdTtr.getOrderNo().equals(axisPmProContProdTtr.getOrderNo())){
                    // 轴合同的取样方式为【SAMPLE_MODE_CODE】，和其他合同不能组在一起
                    throw new CommonException("pm.pm_pd_rule_set_044" , axisPmProContProdTtr.getSampleModeCode());
                }
            } else {
                if(StringUtils.isNotBlank(pmProContProdTtr.getSampleModeCode()) 
                        && "B".equals(pmProContProdTtr.getSampleModeCode())) {
                    // 自然张取样的合同【order_no】必须单独组板
                    throw new CommonException("pm.pm_pd_rule_set_045" , pmProContProdTtr.getOrderNo());
                }
            }
        }
        return true ;
    }

}
