package com.ruoyi.common.core.utils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.concurrent.TimeUnit;

public class UnitChangeUtil {

    private static final double GB = 1024.0 * 1024.0 * 1024.0;

    /**
     * long类型字节转化为Gb
     * @param bytes
     * @return
     */
    public static double bytesToGb(long bytes) {
        double gb = bytes / GB;
        BigDecimal bd = new BigDecimal(gb);
        bd = bd.setScale(2, RoundingMode.HALF_UP);
        return bd.doubleValue();
    }

    /**
     * String类型字节转化为Gb
     * @param bytes
     * @return
     */
    public static BigDecimal bytesToGb(String bytes) {
        // 参数校验
        if (bytes == null || bytes.trim().isEmpty()) {
            return BigDecimal.ZERO;
        }
        BigDecimal bytesValue = new BigDecimal(bytes);
        BigDecimal bd = bytesValue.divide(BigDecimal.valueOf(GB), 2, RoundingMode.HALF_UP);
        return bd;
    }

    /**
     * Kb转化为Gb
     * @param kbValue
     * @return
     */
    public static double convertKbToGb(String kbValue) {
        if (kbValue == null || kbValue.trim().isEmpty()) {
            throw new IllegalArgumentException("KB值不能为空");
        }

        double kb = Double.parseDouble(kbValue.trim());
        double gb = kb / (1024.0 * 1024.0);

        BigDecimal bd = new BigDecimal(gb);
        bd = bd.setScale(2, RoundingMode.HALF_UP);
        return bd.doubleValue();
    }


    /**
     * 工具方法：将毫秒值转换为运行时长
     * @param uptimeMillis
     * @return
     */
    public static String formatUptime(long uptimeMillis) {
        if (uptimeMillis <= 0) {
            return "0秒";
        }

        long days = TimeUnit.MILLISECONDS.toDays(uptimeMillis);
        long hours = TimeUnit.MILLISECONDS.toHours(uptimeMillis) % 24;
        long minutes = TimeUnit.MILLISECONDS.toMinutes(uptimeMillis) % 60;
        long seconds = TimeUnit.MILLISECONDS.toSeconds(uptimeMillis) % 60;

        long months = days / 30;
        days = days % 30;

        return String.format("%d个月%d天%d小时%d分%d秒", months, days, hours, minutes, seconds);
    }

    /**
     * 工具方法- 将秒值转换为运行时长
     * @param uptimeSeconds
     * @return
     */
    public static String formatUptimeSeconds(long uptimeSeconds) {
        if (uptimeSeconds <= 0) {
            return "0秒";
        }

        long days = TimeUnit.SECONDS.toDays(uptimeSeconds);
        long hours = TimeUnit.SECONDS.toHours(uptimeSeconds) % 24;
        long minutes = TimeUnit.SECONDS.toMinutes(uptimeSeconds) % 60;
        long seconds = uptimeSeconds % 60;

        long months = days / 30;
        days = days % 30;

        return String.format("%d个月%d天%d小时%d分%d秒", months, days, hours, minutes, seconds);
    }
    /**
     * 将字符串小数值格式化为保留两位小数（高精度）
     * @param numberStr 数字字符串
     * @return 保留两位小数的字符串，如果转换失败返回原字符串
     */
    public static String formatDecimal(String numberStr) {
        if (numberStr == null || numberStr.trim().isEmpty()) {
            return numberStr;
        }

        try {
            if("NaN".equals(numberStr)){
                numberStr = "0";
            }
            BigDecimal number = new BigDecimal(numberStr);
            return number.setScale(1, RoundingMode.HALF_UP).toString();
        } catch (NumberFormatException e) {
            return numberStr; // 转换失败返回原字符串
        }
    }

    /**
     * 次数单位换算
     * @param count
     * @return
     */
    public static String formatWithUnit(long count) {
        String[] units = {"", "万", "百万", "亿"};
        double[] divisors = {1, 10_000.0, 1_000_000.0, 100_000_000.0};

        int unitIndex = 0;
        double value = count;

        for (int i = divisors.length - 1; i >= 0; i--) {
            if (count >= divisors[i]) {
                unitIndex = i;
                value = count / divisors[i];
                break;
            }
        }

        // 根据数值大小决定小数位数
        String formatPattern = (value >= 100 || unitIndex == 0) ? "%.0f %s次" : "%.1f %s次";
        return String.format(formatPattern, value, units[unitIndex]).trim();
    }

    /**
     * 简洁版本：所有值都显示为KB及以上单位
     */
    public static String formatWithKbMin(long bytes) {
        if (bytes == 0) {
            return "0.00 KB";
        }

        final String[] units = {"KB", "MB", "GB", "TB"};
        double value = bytes / 1024.0;
        int unitIndex = 0;

        while (value >= 1024 && unitIndex < units.length - 1) {
            value /= 1024;
            unitIndex++;
        }

        // 四舍五入到两位小数
        double roundedValue = Math.round(value * 100.0) / 100.0;

        // 处理四舍五入后可能出现的情况
        if (roundedValue == 0.0 && value > 0) {
            roundedValue = 0.01; // 最小值显示为0.01而不是0.00
        }

        return String.format("%.2f %s", roundedValue, units[unitIndex]);
    }
}
