package com.rj.common;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.rj.entity.CustomerManagement;
import com.rj.entity.Dealership;
import com.rj.entity.ProjectManagement;
import com.rj.entity.SalesManagement;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

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

/**
 * 数据丰富工具类
 * 用于批量获取关联数据并填充到主数据中，减少代码冗余
 *
 * @author 系统生成
 * @since 2025-08-07
 */
@Component
public class DataEnrichmentUtil {

    @Autowired
    private ServiceManager serviceManager;

    /**
     * 批量获取关联数据并创建映射
     *
     * @param ids 主键ID列表
     * @param service 对应的Service
     * @param idGetter ID获取函数
     * @param nameGetter 名称获取函数
     * @param <T> 实体类型
     * @param <ID> ID类型
     * @return ID到名称的映射
     */
    public static <T, ID> Map<ID, String> batchGetNameMap(
            Collection<ID> ids,
            IService<T> service,
            Function<T, ID> idGetter,
            Function<T, String> nameGetter) {
        
        if (ids == null || ids.isEmpty()) {
            return new HashMap<>();
        }

        LambdaQueryWrapper<T> queryWrapper = new LambdaQueryWrapper<>();
        // 使用lambda表达式来避免类型问题
        queryWrapper.in(entity -> idGetter.apply(entity), ids);
        List<T> entities = service.list(queryWrapper);
        
        return entities.stream()
                .collect(Collectors.toMap(
                        idGetter,
                        nameGetter,
                        (existing, replacement) -> existing // 如果有重复key，保留第一个
                ));
    }

    /**
     * 批量获取关联数据并创建映射（支持自定义查询条件）
     *
     * @param ids 主键ID列表
     * @param service 对应的Service
     * @param idGetter ID获取函数
     * @param nameGetter 名称获取函数
     * @param additionalCondition 额外的查询条件
     * @param <T> 实体类型
     * @param <ID> ID类型
     * @return ID到名称的映射
     */
    public static <T, ID> Map<ID, String> batchGetNameMap(
            Collection<ID> ids,
            IService<T> service,
            Function<T, ID> idGetter,
            Function<T, String> nameGetter,
            Function<LambdaQueryWrapper<T>, LambdaQueryWrapper<T>> additionalCondition) {
        
        if (ids == null || ids.isEmpty()) {
            return new HashMap<>();
        }

        LambdaQueryWrapper<T> queryWrapper = new LambdaQueryWrapper<>();
        // 使用lambda表达式来避免类型问题
        queryWrapper.in(ids.size() > 0, entity -> idGetter.apply(entity), ids);
        
        if (additionalCondition != null) {
            queryWrapper = additionalCondition.apply(queryWrapper);
        }
        
        List<T> entities = service.list(queryWrapper);
        
        return entities.stream()
                .collect(Collectors.toMap(
                        idGetter,
                        nameGetter,
                        (existing, replacement) -> existing
                ));
    }

    /**
     * 批量获取关联数据并创建映射（支持多个字段）
     *
     * @param ids 主键ID列表
     * @param service 对应的Service
     * @param idGetter ID获取函数
     * @param fieldGetters 字段获取函数映射
     * @param <T> 实体类型
     * @param <ID> ID类型
     * @return ID到字段值的映射
     */
    public static <T, ID> Map<ID, Map<String, Object>> batchGetFieldMap(
            Collection<ID> ids,
            IService<T> service,
            Function<T, ID> idGetter,
            Map<String, Function<T, Object>> fieldGetters) {
        
        if (ids == null || ids.isEmpty()) {
            return new HashMap<>();
        }

        LambdaQueryWrapper<T> queryWrapper = new LambdaQueryWrapper<>();
        // 使用lambda表达式来避免类型问题
        queryWrapper.in(ids.size() > 0, entity -> idGetter.apply(entity), ids);
        List<T> entities = service.list(queryWrapper);
        
        return entities.stream()
                .collect(Collectors.toMap(
                        idGetter,
                        entity -> {
                            Map<String, Object> fieldMap = new HashMap<>();
                            fieldGetters.forEach((fieldName, getter) -> 
                                fieldMap.put(fieldName, getter.apply(entity)));
                            return fieldMap;
                        },
                        (existing, replacement) -> existing
                ));
    }

    /**
     * 批量获取关联数据并创建映射（支持自定义查询条件和多个字段）
     *
     * @param ids 主键ID列表
     * @param service 对应的Service
     * @param idGetter ID获取函数
     * @param fieldGetters 字段获取函数映射
     * @param additionalCondition 额外的查询条件
     * @param <T> 实体类型
     * @param <ID> ID类型
     * @return ID到字段值的映射
     */
    public static <T, ID> Map<ID, Map<String, Object>> batchGetFieldMap(
            Collection<ID> ids,
            IService<T> service,
            Function<T, ID> idGetter,
            Map<String, Function<T, Object>> fieldGetters,
            Function<LambdaQueryWrapper<T>, LambdaQueryWrapper<T>> additionalCondition) {
        
        if (ids == null || ids.isEmpty()) {
            return new HashMap<>();
        }

        LambdaQueryWrapper<T> queryWrapper = new LambdaQueryWrapper<>();
        // 使用lambda表达式来避免类型问题
        queryWrapper.in(ids.size() > 0, entity -> idGetter.apply(entity), ids);
        
        if (additionalCondition != null) {
            queryWrapper = additionalCondition.apply(queryWrapper);
        }
        
        List<T> entities = service.list(queryWrapper);
        
        return entities.stream()
                .collect(Collectors.toMap(
                        idGetter,
                        entity -> {
                            Map<String, Object> fieldMap = new HashMap<>();
                            fieldGetters.forEach((fieldName, getter) -> 
                                fieldMap.put(fieldName, getter.apply(entity)));
                            return fieldMap;
                        },
                        (existing, replacement) -> existing
                ));
    }

    /**
     * 从实体列表中提取指定字段的ID列表
     *
     * @param entities 实体列表
     * @param idGetter ID获取函数
     * @param <T> 实体类型
     * @param <ID> ID类型
     * @return ID列表
     */
    public static <T, ID> List<ID> extractIds(
            Collection<T> entities,
            Function<T, ID> idGetter) {
        
        if (entities == null || entities.isEmpty()) {
            return new ArrayList<>();
        }

        return entities.stream()
                .map(idGetter)
                .filter(Objects::nonNull)
                .distinct()
                .collect(Collectors.toList());
    }

    /**
     * 从实体列表中提取指定字段的ID列表（支持过滤条件）
     *
     * @param entities 实体列表
     * @param idGetter ID获取函数
     * @param filter 过滤条件
     * @param <T> 实体类型
     * @param <ID> ID类型
     * @return ID列表
     */
    public static <T, ID> List<ID> extractIds(
            Collection<T> entities,
            Function<T, ID> idGetter,
            Function<T, Boolean> filter) {
        
        if (entities == null || entities.isEmpty()) {
            return new ArrayList<>();
        }

        return entities.stream()
                .filter(filter::apply)
                .map(idGetter)
                .filter(Objects::nonNull)
                .distinct()
                .collect(Collectors.toList());
    }

    // ==================== 便捷方法，使用ServiceManager ====================

    /**
     * 批量获取门店名称映射（使用ServiceManager）
     */
    public Map<String, String> getDealershipIdNameMap(Collection<String> dealershipIds) {

        // 批量获取门店信息
        Map<String, String> dealershipNameMap;
        if (!dealershipIds.isEmpty()) {
            LambdaQueryWrapper<Dealership> dealershipQueryWrapper = new LambdaQueryWrapper<>();
            dealershipQueryWrapper.in(Dealership::getId, dealershipIds);
            List<Dealership> dealerships = serviceManager.getDealershipService().list(dealershipQueryWrapper);
            dealershipNameMap = dealerships.stream()
                    .collect(Collectors.toMap(Dealership::getId, Dealership::getDealershipName));
        } else {
            dealershipNameMap = new HashMap<>();
        }
        return dealershipNameMap;
    }

    /**
     * 批量获取项目名称映射（使用ServiceManager）
     */
    public Map<String, String> getProjectIdNameMap(Collection<String> projectIds) {

        Map<String, String> projectNameMap;
        if (!projectIds.isEmpty()) {
            LambdaQueryWrapper<ProjectManagement> projectManagementQueryWrapper = new LambdaQueryWrapper<>();
            projectManagementQueryWrapper.in(ProjectManagement::getId, projectIds);
            List<ProjectManagement> projectManagementList = serviceManager.getProjectManagementService().list(projectManagementQueryWrapper);
            projectNameMap = projectManagementList.stream()
                    .collect(Collectors.toMap(ProjectManagement::getId, ProjectManagement::getProjectName));
        } else {
            projectNameMap = new HashMap<>();
        }


        return  projectNameMap;
    }

    /**
     * 批量获取销售名称映射（使用ServiceManager）
     */
    public Map<String, String> getSalesIdNameMap(Collection<String> salesIds) {

        // 批量获取 销售信息
        Map<String, String> saleNameMap;
        if (!salesIds.isEmpty()) {
            LambdaQueryWrapper<SalesManagement> salesQueryWrapper = new LambdaQueryWrapper<>();
            salesQueryWrapper.in(SalesManagement::getId, salesIds);
            List<SalesManagement> sales = serviceManager.getSalesManagementService().list(salesQueryWrapper);
            saleNameMap = sales.stream()
                    .collect(Collectors.toMap(SalesManagement::getId, SalesManagement::getSalesName));
        } else {
            saleNameMap = new HashMap<>();
        }


        return  saleNameMap;
    }

    /**
     * 批量获取销售名称映射（使用ServiceManager）
     */
    public Map<String, String> getSalesIdPhoneMap(Collection<String> salesIds) {

        // 批量获取 销售信息
        Map<String, String> salePhoneMap;
        if (!salesIds.isEmpty()) {
            LambdaQueryWrapper<SalesManagement> salesQueryWrapper = new LambdaQueryWrapper<>();
            salesQueryWrapper.in(SalesManagement::getId, salesIds);
            List<SalesManagement> sales = serviceManager.getSalesManagementService().list(salesQueryWrapper);
            salePhoneMap = sales.stream()
                    .collect(Collectors.toMap(SalesManagement::getId, SalesManagement::getLoginAccount));
        } else {
            salePhoneMap = new HashMap<>();
        }


        return  salePhoneMap;
    }
    /**
     * 批量获取客户名称映射（使用ServiceManager）
     */
    public Map<String, String> getCustomerNameMap(Collection<String> customerIds) {

        // 批量获取 销售信息
        Map<String, String> saleNameMap;
        if (!customerIds.isEmpty()) {
            LambdaQueryWrapper<CustomerManagement> customerQueryWrapper = new LambdaQueryWrapper<>();
            customerQueryWrapper.in(CustomerManagement::getId, customerIds);
            List<CustomerManagement> sales = serviceManager.getCustomerManagementService().list(customerQueryWrapper);
            saleNameMap = sales.stream()
                    .collect(Collectors.toMap(CustomerManagement::getId, CustomerManagement::getCustomerName));
        } else {
            saleNameMap = new HashMap<>();
        }
        return saleNameMap;
    }

    /**
     * 批量获取设备名称映射（使用ServiceManager）
     */
    public Map<String, String> getDeviceNameMap(Collection<String> deviceIds) {
        return batchGetNameMap(
                deviceIds,
                serviceManager.getDeviceManagementService(),
                com.rj.entity.DeviceManagement::getId,
                com.rj.entity.DeviceManagement::getDeviceCode
        );
    }

    /**
     * 批量获取音频名称映射（使用ServiceManager）
     */
    public Map<String, String> getAudioNameMap(Collection<String> audioIds) {
        return batchGetNameMap(
                audioIds,
                serviceManager.getAudioManagementService(),
                com.rj.entity.AudioManagement::getId,
                com.rj.entity.AudioManagement::getRecordingName
        );
    }

    /**
     * 批量获取视频名称映射（使用ServiceManager）
     */
    public Map<String, String> getVideoNameMap(Collection<String> videoIds) {
        return batchGetNameMap(
                videoIds,
                serviceManager.getVideoManagementService(),
                com.rj.entity.VideoManagement::getId,
                com.rj.entity.VideoManagement::getVideoName
        );
    }

    /**
     * 批量获取预约信息映射（使用ServiceManager）
     */
    public Map<Long, String> getReservationNameMap(Collection<Long> reservationIds) {
        return batchGetNameMap(
                reservationIds,
                serviceManager.getReservationService(),
                com.rj.pojo.Reservation::getId,
                com.rj.pojo.Reservation::getName
        );
    }
}
