package cn.iocoder.yudao.module.inspection.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.module.inspection.entity.DlInspectionProject;
import cn.iocoder.yudao.module.inspection.entity.InspectionInfo;
import cn.iocoder.yudao.module.inspection.service.IInspectionInfoService;
import cn.iocoder.yudao.module.inspection.service.IInspectionWorkNodeService;
import cn.iocoder.yudao.module.inspection.service.StatisticsService;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

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

/**
 * @BelongsProject: lanan-system
 * @BelongsPackage: cn.iocoder.yudao.module.inspection.service.impl
 * @Author: 许
 * @CreateTime: 2025-08-05  11:24
 * @Description: 数据统计实现类
 * @Version: 1.0
 */
@Service
@RequiredArgsConstructor
public class StatisticsServiceImpl implements StatisticsService {

    private final IInspectionWorkNodeService inspectionWorkNodeService;

    private final IInspectionInfoService inspectionInfoService;

    private final AdminUserApi adminUserApi;
    /**
     * @description: 获取员工统计信息
     * @author: 许
     * @date: 2025/8/5 11:25
     * @param: [dlInspectionProject]
     * @return: java.util.Map<java.lang.String, java.lang.Object>
     */
    @Override
    public Map<String, Object> queryStaffStatisticsInfo(DlInspectionProject dlInspectionProject) {
        Map<String, Object> result = new HashMap<>();
        /*车型数量统计*/
        //1.根据userId查询完成的车型数量
        List<Map<String, Object>> goodsStatistics = inspectionWorkNodeService.queryStaffCountGroupByGoods(dlInspectionProject);
        result.put("goodsStatistics", goodsStatistics);

        /*初检数量统计 复检数量统计*/
        //1.根据userId查询
        Map<String, Object> inspectionStatistics =inspectionWorkNodeService.queryStaffInspectionCount(dlInspectionProject);
        result.put("inspectionStatistics", inspectionStatistics);

        /*获取员工信息*/
        AdminUserRespDTO user = adminUserApi.getUser(dlInspectionProject.getUserId());
        result.put("staffInfo", user);
        return result;
    }

    /**
     * @description: 获取员工统计信息
     * @author: 许
     * @date: 2025/8/5 14:30
     * @param: [dlInspectionProject]
     * @return: java.util.Map<java.lang.String, java.lang.Object>
     */
    @Override
    public Map<String, Object> queryStaffCountGroupByGoods(DlInspectionProject dlInspectionProject) {
        Map<String, Object> staffCount = inspectionWorkNodeService.getStaffCountByUserId(dlInspectionProject);
        if (staffCount == null || staffCount.isEmpty()) {
            return Collections.emptyMap();
        }

        Long userId = (Long) staffCount.get("userId");

        Set<Long> inspectionInfoIds = new HashSet<>();

        List<Map<String, Object>> children = (List<Map<String, Object>>) staffCount.get("children");
        if (children == null) {
            children = new ArrayList<>();
            staffCount.put("children", children);
        }

        // 收集已有项目中的 inspectionInfoId
        inspectionInfoIds.addAll(
                children.stream()
                        .map(map -> (String) map.get("inspectionInfoId"))
                        .flatMap(idsStr -> Arrays.stream(idsStr.split(",")))
                        .map(String::trim)
                        .filter(idStr -> !idStr.isEmpty())
                        .map(Long::valueOf)
                        .collect(Collectors.toSet())
        );

        // 查询接车信息
        List<InspectionInfo> meetCarList = inspectionInfoService.selectMeetCarList(dlInspectionProject.getDatetimeRange(), dlInspectionProject.getGoodsTitle());
        List<InspectionInfo> userMeetCarList = meetCarList.stream()
                .filter(i -> userId.equals(i.getMeetManId()))
                .collect(Collectors.toList());

        long meetCount = userMeetCarList.stream().filter(i -> Integer.valueOf(0).equals(i.getMeetType())).count();
        long meetGoCount = userMeetCarList.stream().filter(i -> Integer.valueOf(1).equals(i.getMeetType())).count();
        inspectionInfoIds.addAll(userMeetCarList.stream().map(InspectionInfo::getId).collect(Collectors.toList()));

        Map<String, Object> meetPhotoMap = new HashMap<>();
        meetPhotoMap.put("projectName", "接车拍照");
        meetPhotoMap.put("count", meetCount);
        children.add(meetPhotoMap);

        Map<String, Object> meetGoMap = new HashMap<>();
        meetGoMap.put("projectName", "上门接车");
        meetGoMap.put("count", meetGoCount);
        children.add(meetGoMap);


        // 查询还车信息
        LambdaQueryWrapper<InspectionInfo> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(InspectionInfo::getIsReturnCar, 1);

        List<String> datetimeRange = dlInspectionProject.getDatetimeRange();
        if (CollUtil.isNotEmpty(datetimeRange) && datetimeRange.size() == 2) {
            wrapper.between(InspectionInfo::getEndTime, datetimeRange.get(0), datetimeRange.get(1));
        }

        List<InspectionInfo> returnCarList = inspectionInfoService.list(wrapper);


        List<InspectionInfo> userReturnCarList = returnCarList.stream()
                .filter(i -> userId.equals(i.getReturnCarUserId()))
                .collect(Collectors.toList());

        long returnCount = userReturnCarList.stream().filter(i -> Integer.valueOf(0).equals(i.getReturnType())).count();
        long returnGoCount = userReturnCarList.stream().filter(i -> Integer.valueOf(1).equals(i.getReturnType())).count();
        inspectionInfoIds.addAll(userReturnCarList.stream().map(InspectionInfo::getId).collect(Collectors.toList()));

        Map<String, Object> returnPhotoMap = new HashMap<>();
        returnPhotoMap.put("projectName", "还车拍照");
        returnPhotoMap.put("count", returnCount);
        children.add(returnPhotoMap);

        Map<String, Object> returnGoMap = new HashMap<>();
        returnGoMap.put("projectName", "上门还车");
        returnGoMap.put("count", returnGoCount);
        children.add(returnGoMap);


        // 重新设置总数
        staffCount.put("totalCount", (long) inspectionInfoIds.size());

        // 移除 count == 0 的 children
        children.removeIf(c -> ((Long) c.getOrDefault("count", 0L)) == 0L);
        // 按 count 降序排序
        children.sort(Comparator.comparingLong(c -> (Long) c.getOrDefault("count", 0L)));
        Collections.reverse(children);

        return staffCount;
    }
}
