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

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Component;

import com.xisc.pm.api.dto.RuleParamDTO;
import com.xisc.pm.app.service.strategy.RuleExecStrategyFactory;
import com.xisc.pm.domain.entity.PmMinThickTolBt;
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 lombok.extern.slf4j.Slf4j;

/**
 * 合同厚度正负一校验（C04）
 * 
 * @author jun.zeng
 * 
 *
 * 
 */
@Slf4j
@Component
public class MinThickTolRuleExecStrategy implements RuleExecStrategy {

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

    @SuppressWarnings("unchecked")
    @Override
    public boolean execRule(RuleParamDTO ruleParam) {
        Map<String, Object> bizData = ruleParam.getBizData();

        String orderNo = (String) bizData.get(RuleSetConstants.ORDER_NO);
        PmMinThickTolBt pmMinThickTolBt = (PmMinThickTolBt) bizData.get(RuleSetConstants.PM_MIN_THICK_TOL_BT);
        PmProContProdTtr axisPmProContProdTtr = (PmProContProdTtr) bizData.get(RuleSetConstants.AXIS_PM_PRO_CONT_PROD_ATTR);
        List<PmProContProdTtr> pmProContProdTtrs = (List<PmProContProdTtr>) bizData.get(RuleSetConstants.PM_PRO_CONT_PROD_ATTR_LIST);
        if(pmProContProdTtrs == null || pmProContProdTtrs.isEmpty()) {
            // 当传入的非轴合同数量小于1，则校验通过
            return true ;
        }
        BigDecimal max = axisPmProContProdTtr.getOrderThick().add(axisPmProContProdTtr.getThickTolMax());
        BigDecimal min = axisPmProContProdTtr.getOrderThick().add(axisPmProContProdTtr.getThickTolMin());
        for (PmProContProdTtr pmProContProdTtr : pmProContProdTtrs) {
            BigDecimal thickMax = pmProContProdTtr.getOrderThick().add(pmProContProdTtr.getThickTolMax());
            BigDecimal thickMin = pmProContProdTtr.getOrderThick().add(pmProContProdTtr.getThickTolMin());
            if(thickMax.compareTo(max) <= 0) {
                max = thickMax;
            }
            if(thickMin.compareTo(min) >= 0) {
                min = thickMin;
            }
        }
        BigDecimal thickTol = max.subtract(min);
        log.debug(String.format("规则集40：max:%s , min%s , thickTol:%s, minThickTol：%s", max.toPlainString() , min.toPlainString() , thickTol.toPlainString() , pmMinThickTolBt.getMinThickTol()));
        if(BigDecimal.ZERO.compareTo(thickTol) > 0 || thickTol.compareTo(pmMinThickTolBt.getMinThickTol()) <= 0) {
            throw new CommonException("pm.pm_pd_rule_set_013" ,orderNo == null ? axisPmProContProdTtr.getOrderNo() : orderNo) ;
        }
        return true ;
    }

}
