package com.lframework.xingyun.sc.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.time.LocalDate;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class ProportionUtils {

    public static Logger log = LoggerFactory.getLogger(ProportionUtils.class);

    public static String calculateProportion(BigDecimal purchase, BigDecimal sale) {
        if (sale == null || sale.compareTo(BigDecimal.ZERO) == 0) {
            return "0.00%";
        }
        BigDecimal ratio = purchase.divide(sale, 4, RoundingMode.HALF_UP); // 保留4位小数
        DecimalFormat df = new DecimalFormat("0.00%");
        return df.format(ratio);
    }

    public static List<BigDecimal> initZeroList(int size) {
        return IntStream.range(0, size)
                .mapToObj(i -> BigDecimal.ZERO)
                .collect(Collectors.toList());
    }

    public static void fillAmounts(List<Map<String, Object>> data, List<BigDecimal> amounts,
                                   Map<YearMonth, Integer> indexMap, String amountKey) {
        for (Map<String, Object> item : data) {
            try {
                String ymStr = (String) item.get("month");
                YearMonth ym = YearMonth.parse(ymStr, DateTimeFormatter.ofPattern("yyyy-MM"));
                BigDecimal amount = (BigDecimal) item.get(amountKey);

                Integer index = indexMap.get(ym);
                if (index != null && amount != null) {
                    amounts.set(index, amounts.get(index).add(amount));
                }
            } catch (Exception e) {
                log.error("数据格式异常: {}", item, e);
            }
        }
    }

    public static void dayFillAmounts(List<Map<String, Object>> data, List<BigDecimal> amounts, LocalDate now, String amountKey) {
        for (Map<String, Object> item : data) {
            try {
                String dateStr = (String) item.get("date");
                LocalDate date = LocalDate.parse(dateStr, DateTimeFormatter.ISO_DATE);

                // 计算日期索引（0=30天前，29=当天）
                long daysBetween = ChronoUnit.DAYS.between(now.minusDays(29), date);
                if (daysBetween < 0 || daysBetween >= 30) continue;

                BigDecimal amount = (BigDecimal) item.get(amountKey); // 动态获取金额字段
                if (amount != null) {
                    amounts.set((int) daysBetween, amount);
                }
            } catch (Exception e) {
                log.error("数据处理异常: {}", item, e);
            }
        }
    }

    public static String calculateGrowth(BigDecimal current, BigDecimal last) {
        // 处理去年为0但当前年有数据的情况
        if (last.compareTo(BigDecimal.ZERO) == 0) {
            if (current.compareTo(BigDecimal.ZERO) > 0) {
                return "100.00%"; // 从零到有，增长100%
            } else {
                return "0.00%"; // 两年均为零，无增长
            }
        }

        // 正常计算
        BigDecimal growth = current.subtract(last)
                .divide(last, 4, RoundingMode.HALF_UP)
                .multiply(BigDecimal.valueOf(100));
        return String.format("%.2f%%", growth);
    }

}
