package com.dxhy.portrait.business.util;

import java.math.BigDecimal;

import org.apache.commons.lang.StringUtils;

/**
 * @author dxhy
 */
public class MathUtil {
    private static final int DEFAULT_SCALE = 2;
    private static final int ROUND_MAX = 8;
    private static final int ROUND_MIN = 0;
    private static final int DEFAULT_ROUND_MODE = 4;

    public static String add(String v1, String v2) {
        BigDecimal b1 = new BigDecimal(v1);
        BigDecimal b2 = new BigDecimal(v2);
        return b1.add(b2).toPlainString();
    }

    public static String sub(String v1, String v2) {
        BigDecimal b1 = new BigDecimal(v1);
        BigDecimal b2 = new BigDecimal(v2);
        return b1.subtract(b2).toPlainString();
    }

    public static String multi(String v1, String v2) {
        BigDecimal b1 = new BigDecimal(v1);
        BigDecimal b2 = new BigDecimal(v2);
        return b1.multiply(b2).toPlainString();
    }

    public static String divide(String v1, String v2) {
        BigDecimal b1 = new BigDecimal(v1);
        BigDecimal b2 = new BigDecimal(v2);
        return b1.divide(b2, 2, 4).toPlainString();
    }

    public static String divide(String v1, String v2, int scale) {
        if (scale < 0) {
            scale = 2;
        }
        BigDecimal b1 = new BigDecimal(v1);
        BigDecimal b2 = new BigDecimal(v2);
        return b1.divide(b2, scale, 4).toPlainString();
    }

    public static String divide(String v1, String v2, int scale, int roundMode) {
        if (scale < 0) {
            scale = 2;
        }
        boolean roundModeOk = (roundMode < 0) || (roundMode > 8);
        if (roundModeOk) {
            roundMode = 4;
        }
        BigDecimal b1 = new BigDecimal(v1);
        BigDecimal b2 = new BigDecimal(v2);
        return b1.divide(b2, scale, roundMode).toPlainString();
    }

    public static String round(String v) {
        if (StringUtils.isNotBlank(v)) {
            return round(v, 2, 4);
        }
        return "0";
    }

    public static String round(String v, int scale) {
        if (scale < 0) {
            scale = 2;
        }
        return round(v, scale, 4);
    }

    public static String round(String v, int scale, int roundMode) {
        if (scale < 0) {
            scale = 2;
        }
        boolean roundModeOk = (roundMode < 0) || (roundMode > 8);
        if (roundModeOk) {
            roundMode = 4;
        }
        BigDecimal b = new BigDecimal(v);
        return b.setScale(scale, roundMode).toPlainString();
    }
}
