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.domain.vo.MmPlateVO;
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.math.BigDecimal;
import java.util.Map;

/**
 * 余材钢板厚度与合同厚度匹配（P01）
 */
@Component
public class PlateThickMatchRuleExecStrategy implements RuleExecStrategy {

    @Override
    public void afterPropertiesSet() throws Exception {
        RuleExecStrategyFactory.register(PdRuleItemType.PLATE_THICK_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);

        MmPlateVO mmPlateVO = (MmPlateVO) bizData.get(RuleSetConstants.MM_PLATE);
        PmProContProdTtr pmProContProdTtr = (PmProContProdTtr) bizData.get(RuleSetConstants.PM_PRO_CONT_PROD_ATTR);

        if (pmProContProdTtr == null || StringUtils.isBlank(pmProContProdTtr.getGiveSampleCode())) {
            // 读生产合同池没有找到记录，合同号【order_no】，产线号【msc_line_no】
            throw new CommonException("pm.pm_pd_rule_set_001", orderNo, mscLineNo);
        }
        if (mmPlateVO == null) {
            throw new CommonException("pm.pm_pd_plate_001");
        }
        BigDecimal orderThick = pmProContProdTtr.getOrderThick() == null ? BigDecimal.ZERO
                : pmProContProdTtr.getOrderThick();
        BigDecimal thickTolMax = pmProContProdTtr.getThickTolMax() == null ? BigDecimal.ZERO
                : pmProContProdTtr.getThickTolMax();
        BigDecimal thickTolMin = pmProContProdTtr.getThickTolMin() == null ? BigDecimal.ZERO
                : pmProContProdTtr.getThickTolMin();
        BigDecimal matActThick = mmPlateVO.getMatActThk() == null ? BigDecimal.ZERO : mmPlateVO.getMatActThk();

        if (orderThick.add(thickTolMax).compareTo(matActThick) < 0) {
            // 钢板实际厚度【MAT_ACT_THK】大于合同【order_no】的最大订货厚度。
            throw new CommonException("pm.pm_pd_rule_set_028", matActThick.toPlainString(), orderNo, orderThick.add(thickTolMax).toPlainString());
        }

        if (orderThick.add(thickTolMin).compareTo(matActThick) > 0) {
            // 钢板实际厚度【MAT_ACT_THK】小于合同【order_no】的最小订货厚度
            throw new CommonException("pm.pm_pd_rule_set_029", matActThick.toPlainString(), orderNo, orderThick.add(thickTolMin).toPlainString());
        }
        return true;
    }

}
