package com.xdap.self_development.service.impl;

import com.alibaba.fastjson2.JSON;
import com.xdap.self_development.common.BusinessDatabase;
import com.xdap.self_development.controller.form.*;
import com.xdap.self_development.domain.dto.ChartCommonParameterDTO;
import com.xdap.self_development.domain.pojo.*;
import com.xdap.self_development.domain.view.ParameterItem;
import com.xdap.self_development.domain.view.ParametersView;
import com.xdap.self_development.exception.CommonException;
import com.xdap.self_development.service.CommonParameterService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 通用参数服务实现类
 *
 * @version 1.0
 * @since 2025
 */
@Service
public class CommonParameterServiceImpl implements CommonParameterService {
    @Resource
    private BusinessDatabase bd;

    /**
     * 获取系统和参数
     * 查询所有子系统和参数信息
     *
     * @return 子系统和参数项列表
     */
    @Override
    public List<ModelCommonItem> getSystemAndPara() {
        List<ParameterPojo> parameters = bd.getBusinessDatabase()
                .viewQueryMode(true)
                .view("getAllSubsystemAndPara")
                .doQuery(ParameterPojo.class);

        List<GlobalParameterPojo> globalParameters = bd.getBusinessDatabase().doQuery(GlobalParameterPojo.class);
        globalParameters.forEach(globalParameter -> {
            ParameterPojo parameter = new ParameterPojo();
            BeanUtils.copyProperties(globalParameter, parameter);
            parameters.add(parameter);
        });

        return convertToModelCommonItemList(parameters);
    }

    /**
     * 获取模型常用参数
     * 根据用户ID查询模型常用参数
     *
     * @param userId 用户ID
     * @return 模型常用参数列表
     */
    @Override
    public List<ModelCommon> getModelCommonParameter(String userId) {
        List<CommonParameterPojo> commonParameters = bd.getBusinessDatabase()
                .eq("create_by", userId)
                .eq("common_type", 1)
                .doQuery(CommonParameterPojo.class);

        List<String> ids = commonParameters.stream().map(CommonParameterPojo::getId)
                .collect(Collectors.toList());
        if (ids.isEmpty()) {
            return Collections.emptyList();
        }

        // 数据处理
        List<ModelCommonParametersPojo> modelCommonParameters = bd.getBusinessDatabase()
                .viewQueryMode(true).view("getCommonAndParameters")
                .setVar("ids", ids).doQuery(ModelCommonParametersPojo.class);
        modelCommonParameters.addAll(
                bd.getBusinessDatabase().viewQueryMode(true).view("getCommonAndGlobalParameters")
                        .setVar("ids", ids).doQuery(ModelCommonParametersPojo.class)
        );
        return convertToModelCommonList(modelCommonParameters, commonParameters);
    }

    /**
     * 插入模型常用参数
     * 保存新的模型常用参数配置
     *
     * @param form 模型常用参数插入表单
     * @return void
     */
    @Override
    @Transactional
    public void insertModelCommonParameter(ModelCommonParameterInsertForm form) {
        // 检查名字是否重复
        List<CommonParameterPojo> modelCommonParameters1 = bd.getBusinessDatabase()
                .eq("common_name", form.getCommonName())
                .eq("create_by", form.getUserId())
                .doQuery(CommonParameterPojo.class);
        if (!modelCommonParameters1.isEmpty()) {
            throw new CommonException("常用名重复，请重新命名");
        }
        // 新增常用
        CommonParameterPojo commonParameter = new CommonParameterPojo();
        commonParameter.setCommonName(form.getCommonName());
        commonParameter.setCommonType(1);
        commonParameter.setCreateBy(form.getUserId());
        bd.getBusinessDatabase().doInsert(commonParameter);

        // 关联常用参数
        List<ModelCommonParametersPojo> modelCommonParameters =
                convertToModelCommonParameters(form.getParameters(), commonParameter.getId());
        bd.getBusinessDatabase().doBatchInsert(modelCommonParameters);
    }

    /**
     * 更新模型常用参数
     * 修改已有的模型常用参数配置
     *
     * @param form 模型常用参数更新表单
     * @return void
     */
    @Override
    @Transactional
    public void updateModelCommonParameter(ModelCommonParameterUpdateForm form) {
        CommonParameterPojo commonParameter = bd.getBusinessDatabase()
                .eq("id", form.getCommonId()).doQueryFirst(CommonParameterPojo.class);
        if (commonParameter == null) {
            throw new CommonException("无该常用");
        }
        bd.getBusinessDatabase().eq("common_id", form.getCommonId())
                .doDelete(ModelCommonParametersPojo.class);
        List<ModelCommonParametersPojo> modelCommonParameters =
                convertToModelCommonParameters(form.getParameters(), form.getCommonId());
        bd.getBusinessDatabase().doBatchInsert(modelCommonParameters);
    }

    /**
     * 获取分析常用参数
     * 根据用户ID查询分析常用参数
     *
     * @param userId 用户ID
     * @return 分析常用参数POJO列表
     */
    @Override
    public List<AnalysisCommonParameterInsertForm> getAnalysisCommonParameter(String userId) {
        List<AnalysisCommonParametersPojo> list = bd.getBusinessDatabase()
                .viewQueryMode(true)
                .view("queryCommon")
                .setVar("user_id", userId)
                .doQuery(AnalysisCommonParametersPojo.class);

        List<AnalysisCommonParameterInsertForm> res = new ArrayList<>();
        for (AnalysisCommonParametersPojo commonParameter : list) {
            AnalysisCommonParameterInsertForm analysisCommonParameter = new AnalysisCommonParameterInsertForm();
            analysisCommonParameter.setModelName(JSON.parseArray(commonParameter.getModelName()).toJavaList(String.class));
            analysisCommonParameter.setPlate(JSON.parseArray(commonParameter.getPlate()).toJavaList(String.class));
            analysisCommonParameter.setPlatform(JSON.parseArray(commonParameter.getPlatform()).toJavaList(String.class));
            analysisCommonParameter.setSeries(JSON.parseArray(commonParameter.getSeries()).toJavaList(String.class));
            analysisCommonParameter.setProjectName(JSON.parseArray(commonParameter.getProjectName()).toJavaList(String.class));
            analysisCommonParameter.setProjectNumber(JSON.parseArray(commonParameter.getProjectNumber()).toJavaList(String.class));
            analysisCommonParameter.setEmission(JSON.parseArray(commonParameter.getEmission()).toJavaList(String.class));
            analysisCommonParameter.setDisplacementMax(commonParameter.getDisplacementMax());
            analysisCommonParameter.setDisplacementMin(commonParameter.getDisplacementMin());
            analysisCommonParameter.setCombustionType(JSON.parseArray(commonParameter.getCombustionType()).toJavaList(String.class));
            analysisCommonParameter.setCommonName(commonParameter.getCommonName());
            analysisCommonParameter.setCommonId(commonParameter.getCommonId());
            res.add(analysisCommonParameter);
        }
        return res;
    }

    /**
     * 插入分析常用参数
     * 保存新的分析常用参数配置
     *
     * @param form 分析常用参数插入表单
     * @return void
     */
    @Override
    @Transactional
    public void insertAnalysisCommonParameter(AnalysisCommonParameterInsertForm form) {
        // 检查名字是否重复
        List<CommonParameterPojo> modelCommonParameters1 = bd.getBusinessDatabase()
                .eq("common_name", form.getCommonName()).doQuery(CommonParameterPojo.class);
        if (!modelCommonParameters1.isEmpty()) {
            throw new CommonException("常用名重复，请重新命名");
        }
        // 新增常用
        CommonParameterPojo commonParameter = new CommonParameterPojo();
        commonParameter.setCommonName(form.getCommonName());
        commonParameter.setCommonType(2);
        commonParameter.setCreateBy(form.getUserId());
        bd.getBusinessDatabase().doInsert(commonParameter);

        // 关联常用参数
        AnalysisCommonParametersPojo analysisCommonParameter = new AnalysisCommonParametersPojo();
        analysisCommonParameter.setModelName(JSON.toJSONString(form.getModelName()));
        analysisCommonParameter.setPlate(JSON.toJSONString(form.getPlate()));
        analysisCommonParameter.setPlatform(JSON.toJSONString(form.getPlatform()));
        analysisCommonParameter.setSeries(JSON.toJSONString(form.getSeries()));
        analysisCommonParameter.setProjectName(JSON.toJSONString(form.getProjectName()));
        analysisCommonParameter.setProjectNumber(JSON.toJSONString(form.getProjectNumber()));
        analysisCommonParameter.setEmission(JSON.toJSONString(form.getEmission()));
        analysisCommonParameter.setDisplacementMax(form.getDisplacementMax());
        analysisCommonParameter.setDisplacementMin(form.getDisplacementMin());
        analysisCommonParameter.setCombustionType(JSON.toJSONString(form.getCombustionType()));

        analysisCommonParameter.setCommonId(commonParameter.getId());
        bd.getBusinessDatabase().doInsert(analysisCommonParameter);
    }

    /**
     * 更新分析常用参数
     * 修改已有的分析常用参数配置
     *
     * @param form 分析常用参数更新表单
     * @return void
     */
    @Override
    @Transactional
    public void updateAnalysisCommonParameter(AnalysisCommonParameterUpdateForm form) {
        CommonParameterPojo commonParameter = bd.getBusinessDatabase()
                .eq("id", form.getCommonId())
                .doQueryFirst(CommonParameterPojo.class);
        if (commonParameter == null) {
            throw new CommonException("无该常用");
        }
        AnalysisCommonParametersPojo commonParameters = bd.getBusinessDatabase()
                .eq("common_id", form.getCommonId())
                .doQueryFirst(AnalysisCommonParametersPojo.class);
        commonParameters.setModelName(JSON.toJSONString(form.getModelName()));
        commonParameters.setPlate(JSON.toJSONString(form.getPlate()));
        commonParameters.setPlatform(JSON.toJSONString(form.getPlatform()));
        commonParameters.setSeries(JSON.toJSONString(form.getSeries()));
        commonParameters.setProjectName(JSON.toJSONString(form.getProjectName()));
        commonParameters.setProjectNumber(JSON.toJSONString(form.getProjectNumber()));
        commonParameters.setEmission(JSON.toJSONString(form.getEmission()));
        commonParameters.setDisplacementMax(form.getDisplacementMax());
        commonParameters.setDisplacementMin(form.getDisplacementMin());
        commonParameters.setCombustionType(JSON.toJSONString(form.getCombustionType()));
        bd.getBusinessDatabase().rowid("id", commonParameter.getRowId()).doUpdate(commonParameter);
    }

    @Override
    public List<ChartCommonParameterDTO> getChartCommonParameter(String userId) {
        List<ChartCommonParameterDTO> list = new ArrayList<>();
        List<CommonParameterPojo> commonParameterPojos = bd.getBusinessDatabase()
                .eq("create_by", userId)
                .eq("common_type", 3)
                .doQuery(CommonParameterPojo.class);

        for (CommonParameterPojo commonParameterPojo : commonParameterPojos) {
            ChartCommonParameterDTO chartCommonParameterDTO = new ChartCommonParameterDTO();
            List<ChartCommonParameterPojo> chartCommonParameterPojos = bd.getBusinessDatabase()
                    .eq("common_id", commonParameterPojo.getId())
                    .doQuery(ChartCommonParameterPojo.class);
            for (ChartCommonParameterPojo chartCommonParameterPojo : chartCommonParameterPojos) {
                chartCommonParameterPojo.setYAxisParameters(JSON.parseArray(chartCommonParameterPojo.getYAxis(), String.class));
            }
            chartCommonParameterDTO.setCommonId(commonParameterPojo.getId());
            chartCommonParameterDTO.setCommonName(commonParameterPojo.getCommonName());
            chartCommonParameterDTO.setCharts(chartCommonParameterPojos);
            list.add(chartCommonParameterDTO);
        }
        return list;
    }

    @Override
    @Transactional
    public void insertChartCommonParameter(ChartCommonParameterInsertForm form) {
        // 检查名字是否重复
        List<CommonParameterPojo> modelCommonParameters1 = bd.getBusinessDatabase()
                .eq("common_name", form.getCommonName())
                .eq("create_by", form.getUserId())
                .doQuery(CommonParameterPojo.class);
        if (!modelCommonParameters1.isEmpty()) {
            throw new CommonException("常用名重复，请重新命名");
        }
        // 新增常用
        CommonParameterPojo commonParameter = new CommonParameterPojo();
        commonParameter.setCommonName(form.getCommonName());
        commonParameter.setCommonType(3);
        commonParameter.setCreateBy(form.getUserId());
        bd.getBusinessDatabase().doInsert(commonParameter);

        // 关联常用参数
        List<ChartCommonParameterPojo> chartCommonParameters = new ArrayList<>();
        for (ChartCommonItem chart : form.getCharts()) {
            ChartCommonParameterPojo chartCommonParameter = new ChartCommonParameterPojo();
            chartCommonParameter.setTitle(chart.getTitle());
            chartCommonParameter.setChartType(chart.getChartType());
            chartCommonParameter.setXAxis(chart.getXAxis());
            chartCommonParameter.setYAxis(JSON.toJSONString(chart.getYAxis()));
            chartCommonParameter.setCommonId(commonParameter.getId());
            chartCommonParameters.add(chartCommonParameter);
        }
        bd.getBusinessDatabase().doBatchInsert(chartCommonParameters);
    }

    @Override
    public void updateChartCommonParameter(ChartCommonParameterUpdateForm form) {
        CommonParameterPojo commonParameter = bd.getBusinessDatabase()
                .eq("id", form.getCommonId())
                .doQueryFirst(CommonParameterPojo.class);
        if (commonParameter == null) {
            throw new CommonException("无该常用");
        }

        // 更新常用名
        bd.getBusinessDatabase()
                .eq("id", commonParameter.getId())
                .update("common_name", form.getCommonName())
                .doUpdate(CommonParameterPojo.class);

        // 更新常用
        bd.getBusinessDatabase().eq("common_id", form.getCommonId())
                .doDelete(ChartCommonParameterPojo.class);
        List<ChartCommonParameterPojo> chartCommonParameters = new ArrayList<>();
        for (ChartCommonItem chart : form.getCharts()) {
            ChartCommonParameterPojo chartCommonParameter = new ChartCommonParameterPojo();
            chartCommonParameter.setTitle(chart.getTitle());
            chartCommonParameter.setChartType(chart.getChartType());
            chartCommonParameter.setXAxis(chart.getXAxis());
            chartCommonParameter.setYAxis(JSON.toJSONString(chart.getYAxis()));
            chartCommonParameter.setCommonId(commonParameter.getId());
            chartCommonParameters.add(chartCommonParameter);
        }
        bd.getBusinessDatabase().doBatchInsert(chartCommonParameters);
    }

    /**
     * ParameterPojo 列表转换为 ModelCommonItem 列表
     * 将参数POJO列表转换为模型常用项列表
     *
     * @param parameterList 参数POJO列表
     * @return 模型常用项列表
     */
    public static List<ModelCommonItem> convertToModelCommonItemList(List<ParameterPojo> parameterList) {
        if (parameterList == null || parameterList.isEmpty()) {
            return new ArrayList<>();
        }
        LinkedHashMap<String, List<ParameterPojo>> groupedBySubsystem = parameterList.stream()
                .filter(param -> param.getSubsystemName() != null)  // 过滤掉 subsystemName 为 null 的参数
                .sorted(Comparator.comparingInt(param -> {
                    Integer orderNum = param.getOrderNum();
                    return orderNum != null ? orderNum : Integer.MAX_VALUE;  // null 值的放到最后
                }))
                .collect(Collectors.groupingBy(
                        ParameterPojo::getSubsystemName,
                        LinkedHashMap::new,  // 保持插入顺序
                        Collectors.toList()
                ));
        return groupedBySubsystem.entrySet().stream()
                .map(entry -> {
                    ModelCommonItem item = new ModelCommonItem();
                    item.setSubsystem(entry.getKey());
                    List<ParametersView> parameters = entry.getValue().stream()
                            .filter(Objects::nonNull)  // 过滤掉 null 的参数对象
                            .map(param -> {
                                String paramId = param.getId() != null ? param.getId() : "";
                                String paramName = param.getParameterName() != null ? param.getParameterName() : "";
                                String paramType = param.getParameterType() != null ? param.getParameterType() : "";
                                String subsystem = param.getSubsystemName() != null ? param.getSubsystemName() : "";
                                String partsName = param.getPartsName() != null ? param.getPartsName() : "";
                                return new ParametersView(
                                        paramId,
                                        paramName,
                                        paramType,
                                        subsystem,
                                        partsName
                                );
                            })
                            .collect(Collectors.toList());
                    item.setParameters(parameters);
                    return item;
                })
                .collect(Collectors.toList());
    }

    /**
     * 将 ModelCommonParametersPojo 列表转换为 ModelCommon 列表
     * 将模型常用参数POJO列表转换为模型常用列表
     *
     * @param paramsList        模型常用参数POJO列表
     * @param commonParameters  通用参数POJO列表
     * @return 模型常用列表
     */
    private List<ModelCommon> convertToModelCommonList(
            List<ModelCommonParametersPojo> paramsList, List<CommonParameterPojo> commonParameters
    ) {
        Map<String, List<ModelCommonParametersPojo>> groupedByCommonId = new HashMap<>();
        if (paramsList != null && !paramsList.isEmpty()) {
            groupedByCommonId = paramsList.stream()
                    .filter(param -> param.getCommonId() != null)  // 过滤掉 commonId 为 null 的参数
                    .collect(Collectors.groupingBy(ModelCommonParametersPojo::getCommonId));
        }
        
        List<ModelCommon> result = new ArrayList<>();
        for (CommonParameterPojo commonParameter : commonParameters) {
            String commonId = commonParameter.getId();
            if (commonId == null) {
                continue;
            }
            List<ModelCommonParametersPojo> commonParams = groupedByCommonId.get(commonId);
            
            ModelCommon modelCommon = new ModelCommon();
            modelCommon.setCommonName(commonParameter.getCommonName());
            modelCommon.setCommonId(commonId);
            
            if (commonParams == null || commonParams.isEmpty()) {
                // 即使没有参数，也返回一个空的子系统列表
                modelCommon.setSubsystems(new ArrayList<>());
            } else {
                Map<String, List<ModelCommonParametersPojo>> groupedBySubsystem = commonParams.stream()
                        .filter(param -> param.getSubsystemName() != null)  // 过滤掉 subsystemName 为 null 的参数
                        .collect(Collectors.groupingBy(ModelCommonParametersPojo::getSubsystemName));
                
                List<ModelCommonItem> items = new ArrayList<>();
                for (Map.Entry<String, List<ModelCommonParametersPojo>> subsystemEntry : groupedBySubsystem.entrySet()) {
                    ModelCommonItem item = new ModelCommonItem();
                    item.setSubsystem(subsystemEntry.getKey());
                    List<ParametersView> parameters = subsystemEntry.getValue().stream()
                            .map(param -> new ParametersView(
                                    param.getParameterId(),
                                    param.getParameterName(),
                                    param.getParameterType(),
                                    param.getSubsystemName(),
                                    param.getPartsName()
                            ))
                            .collect(Collectors.toList());
                    item.setParameters(parameters);
                    items.add(item);
                }
                modelCommon.setSubsystems(items);
            }
            result.add(modelCommon);
        }
        return result;
    }

    /**
     * 将List 转换为 ModelCommonParametersPojo 列表
     * 将参数项列表转换为模型常用参数POJO列表
     *
     * @param parameters 参数项列表
     * @param commonId   通用ID
     * @return 模型常用参数POJO列表
     */
    private List<ModelCommonParametersPojo> convertToModelCommonParameters(
            List<ParameterItem> parameters, String commonId) {
        List<ModelCommonParametersPojo> result = new ArrayList<>();

        if (parameters != null) {
        // 筛选整车参数
        List<String> globalParameters = parameters.stream().filter(item -> item.getIsGlobal() == 1)
                .map(ParameterItem::getParameterId).collect(Collectors.toList());
        List<String> localParameters = parameters.stream().filter(item -> item.getIsGlobal() != 1)
                .map(ParameterItem::getParameterId).collect(Collectors.toList());

            for (String parameterId : globalParameters) {
                ModelCommonParametersPojo param = new ModelCommonParametersPojo();
                param.setParameterId(parameterId);
                param.setCommonId(commonId);
                param.setIsGlobal(1);
                result.add(param);
            }

            for (String parameterId : localParameters) {
                ModelCommonParametersPojo param = new ModelCommonParametersPojo();
                param.setParameterId(parameterId);
                param.setCommonId(commonId);
                param.setIsGlobal(0);
                result.add(param);
            }
        }
        return result;
    }
}
