package com.sinosig.util.valuerule.condition;

import lombok.Data;
import com.sinosig.util.valuerule.VRSingleCondition;
import org.springframework.util.StringUtils;

/**
 * 数值范围 (VALUERANGE2)条件
 *
 * @param <T> 当前成员变量类型
 */
@Data
public class VRValueRange2Condition<T> extends VRSingleCondition<T> {
    //最小值
    private String minValue;
    //最大值
    private String maxValue;
    //是否包含最小值
    private Boolean isIncludeMinValue;
    //是否包含最大值
    private Boolean isIncludeMaxValue;

    public VRValueRange2Condition(String name, Boolean isNotMode, String ruleInfo, T value) {
        super(name, isNotMode, ruleInfo, value);

    }

    public VRValueRange2Condition<T> init(String minValue, String maxValue, Boolean isIncludeMinValue, Boolean isIncludeMaxValue) {
        this.minValue = minValue;
        this.maxValue = maxValue;
        this.isIncludeMinValue = isIncludeMinValue;
        this.isIncludeMaxValue = isIncludeMaxValue;
        return this;
    }

    @Override
    public boolean validate() {
        if (!(value instanceof Number)) {
            throw new RuntimeException("仅支持数值类型字段，值规则比较。");
        }

        Double valueD = Double.valueOf(String.valueOf(value == null ? "" : value));
        boolean isInrange = true;

        //最小值比较
        if (!(StringUtils.isEmpty(minValue))) {
            Double minValueD = Double.valueOf(String.valueOf(minValue));
            isInrange = valueD > minValueD;
            if (isIncludeMinValue) {
                isInrange = isInrange || valueD == minValueD;
            }
        }

        //最大值比较。
        if (!(StringUtils.isEmpty(maxValue))) {
            Double maxValueD = Double.valueOf(String.valueOf(maxValue));
            isInrange = valueD < maxValueD;
            if (isIncludeMaxValue) {
                isInrange = isInrange || valueD == maxValueD;
            }
        }
        return isInrange;
    }
}
