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;

/**
 * 轴合同与非轴合同会检方式匹配校验 （S02）
 * 
 * @author jun.zeng
 * 
 */
@Component
public class CheckMethodMatchRuleExecStrategy implements RuleExecStrategy {

    @Override
    public void afterPropertiesSet() throws Exception {
        RuleExecStrategyFactory.register(PdRuleItemType.CHECK_METHOD_MATCH, 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 (axisPmProContProdTtr == null || pmProContProdTtr == null) {
            // 读生产合同池没有找到记录，合同号【order_no】，产线号【msc_line_no】
            throw new CommonException("pm.pm_pd_rule_set_001", orderNo, mscLineNo);
        }
        
        if(StringUtils.isBlank(axisPmProContProdTtr.getCheckMethodCode())) {
            if(equals(axisPmProContProdTtr.getCheckMethodCode(), pmProContProdTtr.getCheckMethodCode())) {
                return true;
            } 
            // 如果轴合同不是会检材
            throw new CommonException("pm.pm_pd_rule_set_054"); 
        } else {
            // 如果轴合同是会检材
            if (!equals(axisPmProContProdTtr.getCheckMethodCode(),pmProContProdTtr.getCheckMethodCode())
                    || !equals(axisPmProContProdTtr.getAccpAuthCode(),pmProContProdTtr.getAccpAuthCode())
                    || !equals(axisPmProContProdTtr.getFinCustCode(),pmProContProdTtr.getFinCustCode())) {
                throw new CommonException("pm.pm_pd_rule_set_054");
             }
        }
        return true;
    }
    
    private boolean equals(String axisValue , String value) {
        if(StringUtils.isNotBlank(axisValue)) {
            return axisValue.equals(value);
        } else {
            return StringUtils.isBlank(value);
        }
    }
}
