package com.sckw.order.util;

import com.sckw.core.model.enums.ChargingTypeEnum;
import com.sckw.order.model.KwoTradeOrder;
import org.springframework.lang.Nullable;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Objects;
import java.util.Optional;

/**
 * 贸易订单看板统计用计算工具（完成率等）
 */
public final class TradeOrderDashboardUtils {

    private static final BigDecimal HUNDRED = new BigDecimal("100");

    private TradeOrderDashboardUtils() {
    }

    /**
     * 完成率 = 已完成量 / 订单货物总量(吨等) * 100，四舍五入保留两位小数。
     * 装货量结算取累计装货量；卸货量结算取累计卸货量；按车次计费取实际交付量；总量为空或小于等于0时返回0.
     */
    public static BigDecimal completionRateOf(@Nullable KwoTradeOrder order) {
        if (order == null) {
            return BigDecimal.ZERO.setScale(2, RoundingMode.DOWN);
        }
        BigDecimal total = order.getAmount();
        if (total == null || total.compareTo(BigDecimal.ZERO) <= 0) {
            return BigDecimal.ZERO.setScale(2, RoundingMode.DOWN);
        }
        Integer chargeType = order.getChargeType();
        BigDecimal done;
        if (Objects.equals(chargeType, ChargingTypeEnum.ON.getCode())) {
            done = Optional.ofNullable(order.getLoadAmount()).orElse(BigDecimal.ZERO);
        } else if (Objects.equals(chargeType, ChargingTypeEnum.OFF.getCode())) {
            done = Optional.ofNullable(order.getUnloadAmount()).orElse(BigDecimal.ZERO);
        } else if (Objects.equals(chargeType, ChargingTypeEnum.CAR.getCode())) {
            done = Optional.ofNullable(order.getActualAmount()).orElse(BigDecimal.ZERO);
        } else {
            done = Optional.ofNullable(order.getActualAmount())
                    .filter(a -> a.compareTo(BigDecimal.ZERO) > 0)
                    .or(() -> Optional.ofNullable(order.getLoadAmount()))
                    .or(() -> Optional.ofNullable(order.getUnloadAmount()))
                    .orElse(BigDecimal.ZERO);
        }
        return done.multiply(HUNDRED).divide(total, 2, RoundingMode.DOWN);
    }
}
