package com.sckw.transport.service;

import cn.hutool.core.date.DateUtil;
import com.sckw.core.common.enums.enums.DictEnum;
import com.sckw.core.model.enums.CarWaybillV1Enum;
import com.sckw.transport.api.model.vo.TransportTopStatisticsVo;
import com.sckw.transport.model.KwtLogisticsOrder;
import com.sckw.transport.model.KwtLogisticsOrderUnit;
import com.sckw.transport.model.KwtWaybillOrder;
import com.sckw.transport.model.KwtWaybillOrderSubtask;
import com.sckw.transport.repository.KwtLogisticsOrderRepository;
import com.sckw.transport.repository.KwtLogisticsOrderUnitRepository;
import com.sckw.transport.repository.KwtWaybillOrderRepository;
import com.sckw.transport.repository.KwtWaybillOrderSubtaskRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 运输统计服务。
 * <p>
 * 当前主要负责首页顶部数据展示区四项指标统计：
 * 累计运量、累计车次、今日车次、今日运量。
 * </p>
 *
 * @author ai
 * @date 2026/04/22
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class TransportStatisticsService {

    /**
     * 公开报表固定统计企业范围。
     * <p>
     * 当前接口免登录访问，企业范围按需求固定为图片中的父企业及两个子企业。
     * </p>
     */
    private static final List<Long> REPORT_ENT_IDS = List.of(
            538038314096136193L,
            538039617157337089L,
            538040297439891457L
    );

    private final KwtLogisticsOrderRepository logisticsOrderRepository;
    private final KwtLogisticsOrderUnitRepository logisticsOrderUnitRepository;
    private final KwtWaybillOrderRepository waybillOrderRepository;
    private final KwtWaybillOrderSubtaskRepository waybillOrderSubtaskRepository;

    /**
     * 查询首页顶部运输统计数据。
     * <p>
     * 统计规则：
     * 1. 仅统计状态为“已完成”的运单；
     * 2. 运量根据所属物流订单计费方式动态统计：
     *    按装货量计费取 loadAmount，按卸货量计费取 unloadAmount；
     * 3. 今日维度按运单完成时间（主运单更新时间）落在当天范围内统计。
     * </p>
     *
     * @return 顶部四项统计指标
     */
    public TransportTopStatisticsVo queryTopStatistics() {
        Date todayStart = DateUtil.beginOfDay(new Date());
        Date tomorrowStart = DateUtil.beginOfDay(DateUtil.offsetDay(new Date(), 1));

        log.info("查询顶部运输统计数据，todayStart={}, tomorrowStart={}", todayStart, tomorrowStart);

        List<Long> logisticsOrderIds = queryReportLogisticsOrderIds();
        if (logisticsOrderIds.isEmpty()) {
            log.info("公开报表企业范围未查询到物流订单，entIds={}", REPORT_ENT_IDS);
            return buildEmptyStatistics();
        }
        log.debug("公开报表企业范围匹配到 {} 个物流订单", logisticsOrderIds.size());

        List<KwtWaybillOrder> completedWaybillOrders = defaultList(
                waybillOrderRepository.queryCompletedWaybillOrdersByLogisticsOrderIds(
                        CarWaybillV1Enum.COMPLETED.getCode(), logisticsOrderIds));
        if (completedWaybillOrders.isEmpty()) {
            log.info("公开报表企业范围未查询到已完成运单，entIds={}", REPORT_ENT_IDS);
            return buildEmptyStatistics();
        }

        // 提取已完成运单的ID列表，用于查询关联的子任务数据
        List<Long> waybillOrderIds = completedWaybillOrders.stream()
                .filter(Objects::nonNull)
                .map(KwtWaybillOrder::getId)
                .filter(Objects::nonNull)
                .toList();
        log.debug("公开报表企业范围匹配到 {} 个已完成运单", waybillOrderIds.size());

        // 批量查询物流订单信息
        List<KwtLogisticsOrder> logisticsOrders = logisticsOrderIds.isEmpty()
                ? Collections.emptyList()
                : defaultList(logisticsOrderRepository.queryByLogisticsOrderIds(logisticsOrderIds));
        log.debug("查询到 {} 条物流订单记录", logisticsOrders.size());

        // 构建物流订单ID到计费方式的映射关系
        Map<Long, String> billingModeMap = logisticsOrders.stream()
                .filter(Objects::nonNull)
                .filter(logisticsOrder -> Objects.nonNull(logisticsOrder.getId()))
                .collect(Collectors.toMap(KwtLogisticsOrder::getId, KwtLogisticsOrder::getBillingMode, (left, right) -> left));
        log.debug("构建计费方式映射完成，共 {} 条记录", billingModeMap.size());

        // 根据运单ID列表批量查询子任务信息，用于后续统计净重
        List<KwtWaybillOrderSubtask> subtasks = waybillOrderIds.isEmpty()
                ? Collections.emptyList()
                : defaultList(waybillOrderSubtaskRepository.queryByWOrderIds(waybillOrderIds));

        // 先按运单维度汇总净重，后续累计和今日统计都直接复用，避免重复遍历明细数据。
        // 其中净重按物流订单计费方式动态取值：
        // billingMode=1 取装货量，billingMode=2 取卸货量，其它情况默认按卸货量处理。
        Map<Long, BigDecimal> transportAmountMap = subtasks.stream()
                .filter(Objects::nonNull)
                .filter(subtask -> Objects.nonNull(subtask.getWOrderId()))
                .collect(Collectors.groupingBy(
                        KwtWaybillOrderSubtask::getWOrderId,
                        Collectors.mapping(
                                subtask -> resolveTransportAmount(subtask, billingModeMap.get(subtask.getLOrderId())),
                                Collectors.reducing(BigDecimal.ZERO, Function.identity(), BigDecimal::add)
                        )
                ));

        // 计算累计运量：遍历所有已完成运单，从预计算的运量映射中获取各运单净重并累加
        BigDecimal totalTransportAmount = completedWaybillOrders.stream()
                .filter(Objects::nonNull)
                .map(KwtWaybillOrder::getId)
                .map(id -> transportAmountMap.getOrDefault(id, BigDecimal.ZERO))
                .reduce(BigDecimal.ZERO, BigDecimal::add);

        // 筛选今日完成的运单：根据运单更新时间判断是否落在当天时间范围内
        List<KwtWaybillOrder> todayCompletedWaybillOrders = completedWaybillOrders.stream()
                .filter(Objects::nonNull)
                .filter(waybillOrder -> isBetween(waybillOrder.getUpdateTime(), todayStart, tomorrowStart))
                .toList();

        // 计算今日运量：遍历今日完成的运单，从预计算的运量映射中获取各运单净重并累加
        BigDecimal todayTransportAmount = todayCompletedWaybillOrders.stream()
                .map(KwtWaybillOrder::getId)
                .map(id -> transportAmountMap.getOrDefault(id, BigDecimal.ZERO))
                .reduce(BigDecimal.ZERO, BigDecimal::add);

        // 构建统计结果对象，填充累计车次、累计运量、今日车次、今日运量四项指标
        TransportTopStatisticsVo statisticsVo = TransportTopStatisticsVo.builder()
                .totalTripCount((long) completedWaybillOrders.size())
                .totalTransportAmount(totalTransportAmount)
                .todayTripCount((long) todayCompletedWaybillOrders.size())
                .todayTransportAmount(todayTransportAmount)
                .build();

        log.info("顶部运输统计数据查询完成，result={}", statisticsVo);
        return statisticsVo;
    }

    private TransportTopStatisticsVo buildEmptyStatistics() {
        return TransportTopStatisticsVo.builder()
                .totalTransportAmount(BigDecimal.ZERO)
                .totalTripCount(0L)
                .todayTripCount(0L)
                .todayTransportAmount(BigDecimal.ZERO)
                .build();
    }

    private <T> List<T> defaultList(List<T> list) {
        return list == null ? Collections.emptyList() : list;
    }

    private BigDecimal defaultAmount(BigDecimal amount) {
        return amount == null ? BigDecimal.ZERO : amount;
    }

    /**
     * 查询公开报表固定企业范围对应的物流订单ID。
     * <p>
     * 先从 kwt_logistics_order_unit 表按固定企业范围获取物流订单，
     * 再进入后续运单统计逻辑。
     * </p>
     *
     * @return 公开报表企业范围内的物流订单ID
     */
    private List<Long> queryReportLogisticsOrderIds() {
        return defaultList(logisticsOrderUnitRepository.queryByReportEntIds(REPORT_ENT_IDS))
                .stream()
                .filter(Objects::nonNull)
                .map(KwtLogisticsOrderUnit::getLOrderId)
                .filter(Objects::nonNull)
                .distinct()
                .toList();
    }

    /**
     * 根据物流订单计费方式解析运单净重。
     *
     * @param subtask     运单子单
     * @param billingMode 物流订单计费方式
     * @return 当前子单应参与统计的净重
     */
    private BigDecimal resolveTransportAmount(KwtWaybillOrderSubtask subtask, String billingMode) {
        if (billingMode == null) {
            return BigDecimal.ZERO;
        }
        if (DictEnum.CHARGING_TYPE_1.getValue().equals(billingMode)) {
            return defaultAmount(subtask.getLoadAmount());
        }
        if (DictEnum.CHARGING_TYPE_2.getValue().equals(billingMode)) {
            return defaultAmount(subtask.getUnloadAmount());
        }
        return defaultAmount(subtask.getUnloadAmount());
    }

    private boolean isBetween(Date targetTime, Date startTime, Date endTime) {
        return Objects.nonNull(targetTime)
                && !targetTime.before(startTime)
                && targetTime.before(endTime);
    }
}
