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

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

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
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.PmIngotTypeBt;
import com.xisc.pm.domain.repository.PmIngotTypeBtRepository;
import com.xisc.pm.infra.constant.RuleSetConstants;
import com.xisc.pm.infra.enums.PdRuleItemType;

import io.choerodon.core.exception.CommonException;

/**
 * 小板单重<=锭坯型对应的钢锭重量
 * @author jun.zeng
 *
 */
@Component
public class IngotTypeRuleExecStrategy implements RuleExecStrategy {
    
    @Autowired
    private PmIngotTypeBtRepository pmIngotTypeBtRepository;

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

    @Override
    public boolean execRule(RuleParamDTO ruleParam) {
        Map<String, Object> bizData = ruleParam.getBizData();
        BigDecimal sumPlateWt = (BigDecimal) bizData.get(RuleSetConstants.SUM_PLATE_WT);
        String ingotType = (String) bizData.get(RuleSetConstants.INGOT_TYPE);
        
        if(StringUtils.isBlank(ingotType)) {
            // 钢锭重不能未空！
            throw new CommonException("pm.pm_pd_rule_set_047");
        }
        PmIngotTypeBt pmIngotTypeBt = pmIngotTypeBtRepository.selectByIngotType(ingotType , ruleParam.getTenantId());
        if(sumPlateWt == null) {
            sumPlateWt = BigDecimal.ZERO;
        }
        if(BigDecimal.ZERO.compareTo(sumPlateWt) == 0) {
            // 小板单重总和为0，出错！
            throw new CommonException("pm.pm_pd_rule_set_048");
        }
        if(sumPlateWt.compareTo(pmIngotTypeBt.getIngotWt()) > 0) {
            // 小板单重总和【{0}】大于钢锭本身总重量【{1}】.
            throw new CommonException("pm.pm_pd_rule_set_049" , sumPlateWt.toPlainString() , pmIngotTypeBt.getIngotWt().toPlainString());
        }

        return true;
    }

}
