package com.sckw.transport.repository;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sckw.transport.dao.KwtVehicleExceptionMapper;
import com.sckw.transport.model.KwtVehicleException;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Repository;

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

/**
 * @author cxf
 * @desc 车辆异常图片Repository
 * @date 2025-12-01
 */
@Repository
public class KwtVehicleExceptionRepository extends ServiceImpl<KwtVehicleExceptionMapper, KwtVehicleException> {
    
    /**
     * 分页查询车辆异常图片
     *
     * @param entId          企业ID
     * @param exceptionType  异常类型
     * @param truckNo        车牌号
     * @param pageNum        页码
     * @param pageSize       每页数量
     * @return 分页结果
     */
    public IPage<KwtVehicleException> queryExceptionImagePage(Long entId, Integer exceptionType,
                                                              String truckNo,String startDate,String endDate, int pageNum, int pageSize) {
        return page(new Page<>(pageNum, pageSize),
                Wrappers.<KwtVehicleException>lambdaQuery()
                        .eq(KwtVehicleException::getDelFlag, 0)
                        .eq(Objects.nonNull(entId), KwtVehicleException::getEntId, entId)
                        .eq(Objects.nonNull(exceptionType), KwtVehicleException::getExceptionType, exceptionType)
                        .like(StringUtils.isNotBlank(truckNo), KwtVehicleException::getTruckNo, truckNo)
                        .ge(StringUtils.isNotBlank(startDate),KwtVehicleException::getCreateTime,startDate)
                        .le(StringUtils.isNotBlank(endDate),KwtVehicleException::getCreateTime,endDate)
                        .orderByDesc(KwtVehicleException::getExceptionTime));
    }

    /**
     * 分页查询每个车牌号异常时间最新的一条记录
     * 使用子查询确保每个车牌号只返回异常时间最新的一条记录
     *
     * @param exceptionType  异常类型
     * @param truckNo        车牌号
     * @param pageNum        页码
     * @param pageSize       每页数量
     * @return 分页结果
     */
    public IPage<KwtVehicleException> queryExceptionImagePage1(Set<Long> wOrderIds, Integer exceptionType,
                                                               String truckNo, String startDate, String endDate, int pageNum, int pageSize) {
        // 构建子查询条件：当前记录的异常时间等于该车牌号的最大异常时间
        // 使用 (truck_no, exception_time) IN 子查询来确保只查询每个车牌号最新的一条
        StringBuilder subQuery = new StringBuilder();
        subQuery.append("(truck_no, exception_time) IN (");
        subQuery.append("SELECT truck_no, MAX(exception_time) ");
        subQuery.append("FROM kwt_vehicle_exception ");
        subQuery.append("WHERE del_flag = 0");
        if (CollectionUtils.isNotEmpty(wOrderIds)) {
            subQuery.append(" AND w_order_id IN (")
                    .append(wOrderIds.stream().map(String::valueOf)
                            .collect(Collectors.joining(","))).append(")");
        }
        if (Objects.nonNull(exceptionType)) {
            subQuery.append(" AND exception_type = ").append(exceptionType);
        }
        if (StringUtils.isNotBlank(startDate)) {
            subQuery.append(" AND exception_time >= '").append(startDate).append("'");
        }
        if (StringUtils.isNotBlank(endDate)) {
            subQuery.append(" AND exception_time <= '").append(endDate).append("'");
        }
        if (StringUtils.isNotBlank(truckNo)) {
            // 转义单引号防止 SQL 注入
            String escapedTruckNo = truckNo.replace("'", "''");
            subQuery.append(" AND truck_no LIKE '%").append(escapedTruckNo).append("%'");
        }
        
        subQuery.append(" GROUP BY truck_no)");
        
        return page(new Page<>(pageNum, pageSize),
                Wrappers.<KwtVehicleException>lambdaQuery()
                        .eq(KwtVehicleException::getDelFlag, 0)
                        .in(CollectionUtils.isNotEmpty(wOrderIds), KwtVehicleException::getWOrderId, wOrderIds)
                        .eq(Objects.nonNull(exceptionType), KwtVehicleException::getExceptionType, exceptionType)
                        .like(StringUtils.isNotBlank(truckNo), KwtVehicleException::getTruckNo, truckNo)
                        .apply(subQuery.toString())
                        .orderByDesc(KwtVehicleException::getExceptionTime));
    }
    
    /**
     * 批量查询运单的异常数量
     *
     * @param wOrderNos 运单号列表
     * @return 运单号对应的异常数量 Map
     */
    public Map<String, Integer> countExceptionsByWOrderNos(List<String> wOrderNos) {
        if (wOrderNos == null || wOrderNos.isEmpty()) {
            return Map.of();
        }
        
        List<KwtVehicleException> exceptions = list(
                Wrappers.<KwtVehicleException>lambdaQuery()
                        .eq(KwtVehicleException::getDelFlag, 0)
                        .in(KwtVehicleException::getWOrderNo, wOrderNos)
        );
        
        // 按运单号分组统计数量
        return exceptions.stream()
                .filter(e -> e.getWOrderNo() != null)
                .collect(Collectors.groupingBy(
                        KwtVehicleException::getWOrderNo,
                        Collectors.collectingAndThen(Collectors.counting(), Long::intValue)
                ));
    }

    public List<KwtVehicleException> queryByEnt(Set<Long> waybillOrderIds, Date startDate,Date endDate) {
        return list(Wrappers.<KwtVehicleException>lambdaQuery()
                .eq(KwtVehicleException::getDelFlag, 0)
                .in(KwtVehicleException::getWOrderId, waybillOrderIds)
                .ge(KwtVehicleException::getCreateTime,startDate)
                .le(KwtVehicleException::getCreateTime,endDate));
    }
}
