package com.hw.common.core.utils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;

/**
 * @Author YInQ
 * @create 2023-04-15 18:35
 */
public class sortReportUitls {
    public static void sortArrayList(ArrayList<String> names, ArrayList<Float> values) {
        int size = values.size();

        // 将UnitName和UnitValue打包成一个字符串
        String[] pairs = new String[size];
        for (int i = 0; i < size; i++) {
            pairs[i] = names.get(i) + ":" + values.get(i);
        }

        // 使用Comparator实现对打包后的字符串的排序
        Arrays.sort(pairs, new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                float value1 = Float.parseFloat(o1.split(":")[1]);
                float value2 = Float.parseFloat(o2.split(":")[1]);
                return Float.compare(value2, value1);
            }
        });

        // 将排序后的字符串解包成UnitName和UnitValue
        for (int i = 0; i < size; i++) {
            String[] parts = pairs[i].split(":");
            names.set(i, parts[0]);
            values.set(i, Float.parseFloat(parts[1]));
        }
    }


    /**
     * 计算同环比增长率
     * @param currentValue 当前值
     * @param lastValue 同期值
     * @param scale 小数点保留位数
     * @return 同比增长率
     */
    public static BigDecimal calculateMoMYoY(BigDecimal currentValue, BigDecimal lastValue, int scale) {
        if (currentValue == null || lastValue == null || lastValue.compareTo(BigDecimal.ZERO) == 0) {
            return BigDecimal.ZERO;
        }
        BigDecimal diff = currentValue.subtract(lastValue);
        BigDecimal rate = diff.divide(lastValue, scale + 2, RoundingMode.HALF_UP);
        return rate.multiply(BigDecimal.valueOf(100)).setScale(scale, RoundingMode.HALF_UP);
    }

}
