package com.storlead.sales.util;

import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.math.RoundingMode;

/**
 * 计算环比增长率工具类
 *
 * @author LPK
 */
@Component
public class CalculateGrowthUtils {

    public static BigDecimal calculateMonthlyGrowth(BigDecimal currentMonthData, BigDecimal previousMonthData) {
        // 处理特殊情况
        if (previousMonthData.compareTo(BigDecimal.ZERO) == 0 && currentMonthData.compareTo(BigDecimal.ZERO) != 0) {
            return currentMonthData.compareTo(BigDecimal.ZERO) == 0
                ? BigDecimal.ZERO
                : BigDecimal.valueOf(100);
        } else if (currentMonthData.compareTo(BigDecimal.ZERO) == 0 && previousMonthData.compareTo(BigDecimal.ZERO)!= 0 ) {
            return BigDecimal.valueOf(-100);
        } else if (currentMonthData.compareTo(BigDecimal.ZERO) == 0 && previousMonthData.compareTo(BigDecimal.ZERO) == 0) {
            return BigDecimal.ZERO;
        }

        // 计算环比增长率
        BigDecimal growthRate = currentMonthData
                .subtract(previousMonthData) // 当前数据减去上月数据
                .divide(previousMonthData, RoundingMode.HALF_UP) // 除以上月数据
                .multiply(BigDecimal.valueOf(100)); // 乘以100，转为百分比

        return growthRate.toString().endsWith(".00")? growthRate.setScale(0, RoundingMode.HALF_UP) : growthRate;
    }

    public static int calculateMonthlyGrowths(int currentMonthData, int previousMonthData) {
        // 处理特殊情况
        if (previousMonthData == 0 && currentMonthData != 0) {
            return currentMonthData == 0 ? 0 : 100;
        } else if (currentMonthData == 0 && previousMonthData != 0) {
            return -100;
        } else if (currentMonthData == 0 && previousMonthData == 0) {
            return 0;
        }

        // 计算环比增长率
        double growthRate = ((double) (currentMonthData - previousMonthData) / previousMonthData) * 100;

        return (int) Math.round(growthRate);
    }

}
