package com.xdap.self_development.service.impl;


import com.xdap.self_development.common.BusinessDatabase;
import com.xdap.self_development.controller.request.ReportRequest;
import com.xdap.self_development.domain.pojo.DataEntryEngineModelPojo;
import com.xdap.self_development.domain.pojo.EngineParamDetailPojo;
import com.xdap.self_development.domain.pojo.ParameterPojo;
import com.xdap.self_development.domain.view.AnalysisModelParamterView;
import com.xdap.self_development.domain.view.AnalysisModelParamterViewAndParam;
import com.xdap.self_development.exception.CommonException;
import com.xdap.self_development.service.AnalysisCommonParametersService;
import com.xdap.self_development.service.EngineParamDetailService;
import com.xdap.self_development.service.TcDataQueryService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;


/**
 * 分析常用参数服务实现类
 *
 * @version 1.0
 * @since 2025
 */
@Slf4j
@Service
public class AnalysisCommonParametersServiceImpl implements AnalysisCommonParametersService {

    @Resource
    BusinessDatabase businessDatabase;

    @Resource
    TcDataQueryService tcDataQueryService;

    @Resource
    private EngineParamDetailService engineParamDetailService;

    private static final Pattern ALL_NUMBER_PATTERN = Pattern.compile("^[-+]?\\d+(\\.\\d+)?([Ee][-+]?\\d+)?$");


    /**
     * 显示报表
     * 根据模型列表生成分析报表
     *
     * @param models 模型ID列表
     * @return 分析模型参数视图和参数对象
     */
    @Override
    public AnalysisModelParamterViewAndParam showReport(List<String> models) {

        return showReport2(models);

    }

    /**
     * 模糊查询模型
     * 根据报表请求条件模糊匹配符合条件的模型
     *
     * @param request 报表请求对象
     * @return 引擎模型POJO列表
     */
    @Override
    public List<DataEntryEngineModelPojo> selectModelByLike(ReportRequest request) {
        if (request.getEngineCapacityMax() != null &&
                request.getEngineCapacityMin() != null &&
                request.getEngineCapacityMax() < request.getEngineCapacityMin()
        ) {
            throw new CommonException("排量范围设置错误");
        }
        return new ArrayList<>(businessDatabase.getBusinessDatabase()
                .like("model_name", request.getModelName())
                .like("plate", request.getPlate())
                .like("platform", request.getPlatform())
                .like("series", request.getSeries())
                .like("project_name", request.getProjectName())
                .like("product_number", request.getProductNumber())
                .like("emission", request.getEmission())
                .like("burn_type", request.getBurnType())
                .conjuctionOr()
                .lteq("engine_capacity", request.getEngineCapacityMax())
                .gteq("engine_capacity", request.getEngineCapacityMin())
                .eq("is_delete", 0)
                .doQuery(DataEntryEngineModelPojo.class));
    }

    /**
     * 获取可用参数
     * 返回系统中所有可用的参数名称列表
     *
     * @return 可用参数名称列表
     */
    @Override
    public List<String> getAvailableParameters(
            String userId
    ) {
        List<ParameterPojo> modelParams = businessDatabase.getBusinessDatabase()
                .viewQueryMode(true)
                .view("selectAllParameters")
                .doQuery(ParameterPojo.class);
        // 按权限过滤
        List<ParameterPojo> parameters = engineParamDetailService.selectParamByIsUserId(modelParams, userId);
        return parameters.stream()
                .filter(x -> Objects.equals(x.getIsNumber(), "数值"))
                .map(ParameterPojo::getParameterName).distinct().collect(Collectors.toList());
    }

    /**
     * 显示报表2
     * 根据模型列表生成分析报表（第二个实现）
     *
     * @param models 模型ID列表
     * @return 分析模型参数视图和参数对象
     */
    public AnalysisModelParamterViewAndParam showReport2(List<String> models) {
        // 查询所有符合条件的机型
        List<DataEntryEngineModelPojo> engineModelPojos = businessDatabase.getBusinessDatabase()
                .in("id", models)
                .doQuery(DataEntryEngineModelPojo.class);

        if (engineModelPojos.isEmpty()) {
            throw new CommonException("没有找到符合条件的机型");
        }

        // 获取机型id列表
        Set<String> modelIds = engineModelPojos.stream()
                .map(DataEntryEngineModelPojo::getId)
                .collect(Collectors.toSet());

        // 获取数据平台机型的参数
        List<EngineParamDetailPojo> allEngineParamDetails = businessDatabase.getBusinessDatabase()
                .in("engine_model_id", modelIds)
                .doQuery(EngineParamDetailPojo.class);

        // 按 modelId 分组
        Map<String, List<EngineParamDetailPojo>> engineParamDetailMap = allEngineParamDetails.stream()
                .collect(Collectors.groupingBy(pojo -> pojo.getEngineModelId() + "_" + pojo.getMajorVersion()));

        // 批量查询 TC 数据
        List<EngineParamDetailPojo> allTcData = tcDataQueryService.tcDataSelectAllByproductNumberBatch(engineModelPojos);

        // 按 modelId 分组
        Map<String, List<EngineParamDetailPojo>> tcDataMap = allTcData.stream()
                .collect(Collectors.groupingBy(EngineParamDetailPojo::getEngineModelId));

        // 构建结果
        AnalysisModelParamterViewAndParam andParam = new AnalysisModelParamterViewAndParam();
        List<AnalysisModelParamterView> analysisModelParamterViews = new ArrayList<>();

        for (DataEntryEngineModelPojo engineModelPojo : engineModelPojos) {
            AnalysisModelParamterView analysisModelParamterView = new AnalysisModelParamterView();
            analysisModelParamterView.setModelID(engineModelPojo.getId());
            analysisModelParamterView.setModelName(engineModelPojo.getModelName());
            BeanUtils.copyProperties(engineModelPojo, analysisModelParamterView);

            // 获取 EngineParamDetailPojo 列表
            String groupKey = engineModelPojo.getId() + "_" + engineModelPojo.getVersionNumber();
            List<EngineParamDetailPojo> pojoList = engineParamDetailMap.getOrDefault(groupKey, Collections.emptyList());

            // 添加 TC 数据
            List<EngineParamDetailPojo> tcData = tcDataMap.getOrDefault(engineModelPojo.getId(), Collections.emptyList());

            // 合并原列表和TC数据，一次过滤+收集，避免创建中间列表
            pojoList = Stream.concat(pojoList.stream(), tcData.stream())
                    .filter(x ->
                            ObjectUtils.isNotEmpty(x.getParameterValue()) && isNumber(x.getParameterValue()))
                    .collect(Collectors.toList());

            analysisModelParamterView.setPojos(pojoList);
            analysisModelParamterViews.add(analysisModelParamterView);
        }

        andParam.setParamList(new ArrayList<>());
        andParam.setPojos(analysisModelParamterViews);
        return andParam;
    }

    /**
     * 验证所有数值类型
     *
     * @param str 待验证的字符串
     * @return 是否为数字
     */
    public static boolean isNumber(String str) {
        if (str == null || str.trim().isEmpty()) {
            return false;
        }
        return ALL_NUMBER_PATTERN.matcher(str.trim()).matches();
    }

}
