package com.usky.vpp.util;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.Map;
import java.util.TreeMap;

/**
 * 累计电能表时序差值计算（与 EMS 分段用量逻辑一致）
 */
public final class VppEnergyUsageHelper {

    private static final int SCALE = 4;

    private VppEnergyUsageHelper() {
    }

    /**
     * 计算区间内累计电能增量：末值 - 首值；若回零则取末值。
     *
     * @return 无有效读数时返回 null
     */
    public static BigDecimal calcUsage(TreeMap<LocalDateTime, BigDecimal> timeValueMap,
                                       LocalDateTime startInclusive,
                                       LocalDateTime endExclusive) {
        if (timeValueMap == null || timeValueMap.isEmpty() || startInclusive == null || endExclusive == null) {
            return null;
        }
        TreeMap<LocalDateTime, BigDecimal> segment = new TreeMap<>();
        for (Map.Entry<LocalDateTime, BigDecimal> entry : timeValueMap.entrySet()) {
            LocalDateTime ts = entry.getKey();
            if (!ts.isBefore(startInclusive) && ts.isBefore(endExclusive)) {
                segment.put(ts, entry.getValue());
            }
        }
        if (segment.size() < 2) {
            return null;
        }
        BigDecimal first = segment.firstEntry().getValue();
        BigDecimal last = segment.lastEntry().getValue();
        if (first == null || last == null) {
            return null;
        }
        BigDecimal usage = last.subtract(first);
        if (usage.compareTo(BigDecimal.ZERO) < 0) {
            usage = last;
        }
        return usage.setScale(SCALE, RoundingMode.HALF_UP);
    }

    public static BigDecimal zeroIfNull(BigDecimal value) {
        return value == null ? BigDecimal.ZERO.setScale(SCALE, RoundingMode.HALF_UP) : value;
    }

    public static BigDecimal addNullable(BigDecimal left, BigDecimal right) {
        return zeroIfNull(left).add(zeroIfNull(right));
    }
}
