package cn.van.business.util;

import cn.van.business.model.jd.OrderRow;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class OrderStatsUtil {

    public static Map<Long, OrderStats> groupByUnionIdAndCalculateStats(List<OrderRow> orderRows) {
        // 按 unionId 分组并统计
        return orderRows.stream()
                .collect(Collectors.groupingBy(OrderRow::getUnionId,
                        Collectors.collectingAndThen(Collectors.toList(), OrderStatsUtil::calculateStats)));
    }

    // 统计逻辑
    private static OrderStats calculateStats(List<OrderRow> orders) {
        long totalOrders = orders.size();
        long validOrders = (int) orders.stream().filter(o -> o.getValidCode() != -1).count();

        long paidOrders = orders.stream().filter(o -> o.getValidCode() == 16).count();
        double paidCommission = orders.stream()
                .filter(o -> o.getValidCode() == 16)
                .mapToDouble(OrderRow::getEstimateFee)
                .sum();

        long pendingOrders = orders.stream().filter(o -> o.getValidCode() == 15).count();
        double pendingCommission = orders.stream()
                .filter(o -> o.getValidCode() == 15)
                .mapToDouble(OrderRow::getEstimateFee)
                .sum();

        long canceledOrders = orders.stream()
                .filter(o -> o.getValidCode() != 16 && o.getValidCode() != 17)
                .count();

        long completedOrders = orders.stream().filter(o -> o.getValidCode() == 17).count();
        double completedCommission = orders.stream()
                .filter(o -> o.getValidCode() == 17)
                .mapToDouble(OrderRow::getEstimateFee)
                .sum();

        long violations = getStreamForWeiGui(orders).count();
        double violationCommission = getStreamForWeiGui(orders)
                .mapToDouble(o -> o.getEstimateCosPrice() * o.getCommissionRate() * 0.01)
                .sum();

        return new OrderStats(
                totalOrders,
                validOrders,
                paidOrders,
                paidCommission,
                pendingOrders,
                pendingCommission,
                canceledOrders,
                completedOrders,
                completedCommission,
                violations,
                violationCommission
        );
    }

    // 获取违规订单流
    private static Stream<OrderRow> getStreamForWeiGui(List<OrderRow> orderRows) {
        return orderRows.stream().filter(orderRow ->
                orderRow.getValidCode() == 13 ||
                orderRow.getValidCode() == 25 ||
                orderRow.getValidCode() == 26 ||
                orderRow.getValidCode() == 27 ||
                orderRow.getValidCode() == 28 ||
                orderRow.getValidCode() == 29);
    }
}
