package com.ruoyi.ems.service.impl;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.ems.domain.ReportDatasource;
import com.ruoyi.ems.domain.ReportField;
import com.ruoyi.ems.domain.ReportFieldCondition;
import com.ruoyi.ems.domain.ReportQueryConfig;
import com.ruoyi.ems.domain.ReportRelation;
import com.ruoyi.ems.domain.ReportTemplate;
import com.ruoyi.ems.mapper.CustomReportMapper;
import com.ruoyi.ems.model.ReportQueryResult;
import com.ruoyi.ems.service.ICustomReportService;
import com.ruoyi.ems.util.DynamicSqlBuilder;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 自定义报表Service实现
 *
 * @author ruoyi
 * @date 2026-01-30
 */
@Service
public class CustomReportServiceImpl implements ICustomReportService {

    private static final Logger logger = LoggerFactory.getLogger(CustomReportServiceImpl.class);

    @Autowired
    private CustomReportMapper reportMapper;

    // ==================== 数据源管理 ====================

    @Override
    public List<ReportDatasource> selectDatasourceList(String category) {
        return reportMapper.selectDatasourceList(category);
    }

    @Override
    public ReportDatasource selectDatasourceByCode(String dsCode) {
        if (StringUtils.isBlank(dsCode)) {
            return null;
        }
        return reportMapper.selectDatasourceByCode(dsCode);
    }

    @Override
    public ReportDatasource selectDatasourceDetail(String dsCode) {
        if (StringUtils.isBlank(dsCode)) {
            return null;
        }

        ReportDatasource datasource = reportMapper.selectDatasourceByCode(dsCode);
        if (datasource == null) {
            return null;
        }

        // 加载字段列表
        List<ReportField> fields = reportMapper.selectFieldsByDsCode(dsCode);
        datasource.setFields(fields);

        // 加载字段条件
        if (CollectionUtils.isNotEmpty(fields)) {
            List<ReportFieldCondition> allConditions = reportMapper.selectAllFieldConditions(dsCode);
            Map<String, List<ReportFieldCondition>> conditionMap = allConditions.stream()
                .collect(Collectors.groupingBy(ReportFieldCondition::getFieldCode));

            // 加载字段关联
            List<Map<String, String>> allRelations = reportMapper.selectAllFieldRelations(dsCode);
            Map<String, List<String>> fieldRelationMap = new HashMap<>();
            for (Map<String, String> rel : allRelations) {
                String fieldCode = rel.get("fieldCode");
                String relationCode = rel.get("relationCode");
                fieldRelationMap.computeIfAbsent(fieldCode, k -> new ArrayList<>()).add(relationCode);
            }

            for (ReportField field : fields) {
                field.setConditions(conditionMap.getOrDefault(field.getFieldCode(), Collections.emptyList()));
                field.setRelationCodes(fieldRelationMap.getOrDefault(field.getFieldCode(), Collections.emptyList()));
            }
        }

        // 加载关联配置
        List<ReportRelation> relations = reportMapper.selectRelationsByDsCode(dsCode);
        datasource.setRelations(relations);

        return datasource;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertDatasource(ReportDatasource datasource) {
        if (datasource == null || StringUtils.isBlank(datasource.getDsCode())) {
            return 0;
        }

        // 检查编码是否存在
        ReportDatasource existing = reportMapper.selectDatasourceByCode(datasource.getDsCode());
        if (existing != null) {
            throw new RuntimeException("数据源编码已存在: " + datasource.getDsCode());
        }

        // 设置默认值
        if (datasource.getMainAlias() == null) {
            datasource.setMainAlias("t");
        }
        if (datasource.getStatus() == null) {
            datasource.setStatus(1);
        }
        if (datasource.getSortOrder() == null) {
            datasource.setSortOrder(0);
        }

        return reportMapper.insertDatasource(datasource);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateDatasource(ReportDatasource datasource) {
        if (datasource == null || StringUtils.isBlank(datasource.getDsCode())) {
            return 0;
        }
        return reportMapper.updateDatasource(datasource);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteDatasource(String dsCode) {
        if (StringUtils.isBlank(dsCode)) {
            return 0;
        }

        // 删除关联数据
        reportMapper.deleteFieldConditions(dsCode, null);
        reportMapper.deleteFieldRelations(dsCode, null);
        reportMapper.deleteFieldsByDsCode(dsCode);
        reportMapper.deleteRelationsByDsCode(dsCode);

        return reportMapper.deleteDatasource(dsCode);
    }

    // ==================== 字段管理 ====================

    @Override
    public List<ReportField> selectFieldsByDsCode(String dsCode) {
        if (StringUtils.isBlank(dsCode)) {
            return Collections.emptyList();
        }
        return reportMapper.selectFieldsByDsCode(dsCode);
    }

    @Override
    public List<ReportFieldCondition> selectFieldConditions(String dsCode, String fieldCode) {
        if (StringUtils.isBlank(dsCode) || StringUtils.isBlank(fieldCode)) {
            return Collections.emptyList();
        }
        return reportMapper.selectFieldConditions(dsCode, fieldCode);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertField(ReportField field) {
        if (field == null || StringUtils.isBlank(field.getDsCode()) || StringUtils.isBlank(field.getFieldCode())) {
            return 0;
        }

        // 设置默认值
        if (field.getStatus() == null) {
            field.setStatus(1);
        }
        if (field.getIsDefault() == null) {
            field.setIsDefault(0);
        }
        if (field.getIsFilterable() == null) {
            field.setIsFilterable(1);
        }
        if (field.getIsSortable() == null) {
            field.setIsSortable(1);
        }
        if (field.getIsAggregatable() == null) {
            field.setIsAggregatable(0);
        }

        return reportMapper.insertField(field);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertFieldBatch(List<ReportField> fields) {
        if (CollectionUtils.isEmpty(fields)) {
            return 0;
        }

        for (ReportField field : fields) {
            if (field.getStatus() == null) {
                field.setStatus(1);
            }
            if (field.getIsDefault() == null) {
                field.setIsDefault(0);
            }
        }

        return reportMapper.insertFieldBatch(fields);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateField(ReportField field) {
        if (field == null || StringUtils.isBlank(field.getDsCode()) || StringUtils.isBlank(field.getFieldCode())) {
            return 0;
        }
        return reportMapper.updateField(field);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteField(String dsCode, String fieldCode) {
        if (StringUtils.isBlank(dsCode) || StringUtils.isBlank(fieldCode)) {
            return 0;
        }

        // 删除字段条件
        reportMapper.deleteFieldConditions(dsCode, fieldCode);
        // 删除字段关联映射
        reportMapper.deleteFieldRelations(dsCode, fieldCode);
        // 删除字段
        return reportMapper.deleteField(dsCode, fieldCode);
    }

    // ==================== 关联管理 ====================

    @Override
    public List<ReportRelation> selectRelationsByDsCode(String dsCode) {
        if (StringUtils.isBlank(dsCode)) {
            return Collections.emptyList();
        }
        return reportMapper.selectRelationsByDsCode(dsCode);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertRelation(ReportRelation relation) {
        if (relation == null || StringUtils.isBlank(relation.getDsCode()) || StringUtils.isBlank(relation.getRelationCode())) {
            return 0;
        }

        if (relation.getJoinType() == null) {
            relation.setJoinType("LEFT");
        }
        if (relation.getIsAutoJoin() == null) {
            relation.setIsAutoJoin(1);
        }
        if (relation.getStatus() == null) {
            relation.setStatus(1);
        }

        return reportMapper.insertRelation(relation);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateRelation(ReportRelation relation) {
        if (relation == null || StringUtils.isBlank(relation.getDsCode()) || StringUtils.isBlank(relation.getRelationCode())) {
            return 0;
        }
        return reportMapper.updateRelation(relation);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteRelation(String dsCode, String relationCode) {
        if (StringUtils.isBlank(dsCode) || StringUtils.isBlank(relationCode)) {
            return 0;
        }
        return reportMapper.deleteRelation(dsCode, relationCode);
    }

    // ==================== 模板管理 ====================

    @Override
    public List<ReportTemplate> selectTemplateList(ReportTemplate query) {
        return reportMapper.selectTemplateList(query);
    }

    @Override
    public ReportTemplate selectTemplateByCode(String templateCode) {
        if (StringUtils.isBlank(templateCode)) {
            return null;
        }

        ReportTemplate template = reportMapper.selectTemplateByCode(templateCode);
        if (template != null && StringUtils.isNotBlank(template.getConfigJson())) {
            try {
                ReportQueryConfig config = JSON.parseObject(template.getConfigJson(), ReportQueryConfig.class);
                template.setQueryConfig(config);
            } catch (Exception e) {
                logger.warn("解析模板配置JSON失败: {}", e.getMessage());
            }
        }
        return template;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int saveTemplate(ReportTemplate template) {
        if (template == null || StringUtils.isBlank(template.getDsCode())) {
            return 0;
        }

        // 生成模板编码
        if (StringUtils.isBlank(template.getTemplateCode())) {
            template.setTemplateCode("tpl_" + System.currentTimeMillis());
        }

        // 检查编码是否存在
        int count = reportMapper.checkTemplateCodeExists(template.getTemplateCode());
        if (count > 0) {
            throw new RuntimeException("模板编码已存在: " + template.getTemplateCode());
        }

        // 设置默认值
        if (template.getStatus() == null) {
            template.setStatus(1);
        }
        if (template.getIsPublic() == null) {
            template.setIsPublic(0);
        }
        if (template.getIsSystem() == null) {
            template.setIsSystem(0);
        }

        return reportMapper.insertTemplate(template);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateTemplate(ReportTemplate template) {
        if (template == null || StringUtils.isBlank(template.getTemplateCode())) {
            return 0;
        }
        return reportMapper.updateTemplate(template);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteTemplate(String templateCode) {
        if (StringUtils.isBlank(templateCode)) {
            return 0;
        }
        return reportMapper.deleteTemplate(templateCode);
    }

    @Override
    public int incrementTemplateUseCount(String templateCode) {
        if (StringUtils.isBlank(templateCode)) {
            return 0;
        }
        return reportMapper.incrementTemplateUseCount(templateCode);
    }

    // ==================== 动态查询执行 ====================

    @Override
    public ReportQueryResult executeQuery(ReportQueryConfig queryConfig) {
        try {
            // 1. 解析配置
            ReportQueryConfig effectiveConfig = resolveQueryConfig(queryConfig);
            if (effectiveConfig == null) {
                return ReportQueryResult.error("无法解析查询配置");
            }

            String dsCode = effectiveConfig.getDsCode();
            if (StringUtils.isBlank(dsCode)) {
                return ReportQueryResult.error("数据源编码不能为空");
            }

            // 2. 加载数据源配置
            ReportDatasource datasource = selectDatasourceDetail(dsCode);
            if (datasource == null) {
                return ReportQueryResult.error("数据源不存在: " + dsCode);
            }

            // 3. 构建字段Map和关联Map
            Map<String, ReportField> fieldMap = datasource.getFields().stream()
                .collect(Collectors.toMap(ReportField::getFieldCode, Function.identity()));

            Map<String, ReportRelation> relationMap = datasource.getRelations().stream()
                .collect(Collectors.toMap(ReportRelation::getRelationCode, Function.identity()));

            // 构建字段关联映射
            Map<String, List<String>> fieldRelationMap = new HashMap<>();
            for (ReportField field : datasource.getFields()) {
                if (CollectionUtils.isNotEmpty(field.getRelationCodes())) {
                    fieldRelationMap.put(field.getFieldCode(), field.getRelationCodes());
                }
            }

            // 4. 构建SQL
            DynamicSqlBuilder.BuildResult buildResult = DynamicSqlBuilder.buildQuerySql(
                datasource, fieldMap, relationMap, fieldRelationMap, effectiveConfig);

            if (!buildResult.isSuccess()) {
                return ReportQueryResult.error(buildResult.getErrorMsg());
            }

            // 5. 执行查询
            Map<String, Object> execParams = new HashMap<>(buildResult.getParams());

            // 处理分页
            if (!Boolean.TRUE.equals(effectiveConfig.getExportAll())) {
                int pageNum = effectiveConfig.getPageNum() != null ? effectiveConfig.getPageNum() : 1;
                int pageSize = effectiveConfig.getPageSize() != null ? effectiveConfig.getPageSize() : 20;
                execParams.put("pageNum", pageNum);
                execParams.put("pageSize", pageSize);
                execParams.put("offset", (pageNum - 1) * pageSize);
            }

            logger.info("执行报表查询SQL: {}", buildResult.getSql());
            logger.info("查询参数: {}", execParams);

            // 执行数据查询
            List<Map<String, Object>> rows = reportMapper.executeDynamicQuery(buildResult.getSql(), execParams);

            // 执行计数查询
            Long total = 0L;
            if (!Boolean.TRUE.equals(effectiveConfig.getExportAll())) {
                total = reportMapper.executeDynamicCount(buildResult.getCountSql(), execParams);
            } else {
                total = rows != null ? (long) rows.size() : 0L;
            }

            // 6. 构建结果
            ReportQueryResult result = ReportQueryResult.success(
                rows != null ? rows : Collections.emptyList(),
                total,
                buildResult.getColumns()
            );

            // 开发环境返回SQL（生产环境应该移除）
            result.setSql(buildResult.getSql());

            return result;

        } catch (Exception e) {
            logger.error("执行报表查询异常", e);
            return ReportQueryResult.error("查询异常: " + e.getMessage());
        }
    }

    @Override
    public Map<String, Object> executeSummaryQuery(ReportQueryConfig queryConfig) {
        try {
            // 1. 解析配置
            ReportQueryConfig effectiveConfig = resolveQueryConfig(queryConfig);
            if (effectiveConfig == null) {
                logger.warn("无法解析查询配置");
                return Collections.emptyMap();
            }

            String dsCode = effectiveConfig.getDsCode();
            if (StringUtils.isBlank(dsCode)) {
                logger.warn("数据源编码为空");
                return Collections.emptyMap();
            }

            // 2. 加载数据源配置
            ReportDatasource datasource = selectDatasourceDetail(dsCode);
            if (datasource == null) {
                logger.warn("数据源不存在: {}", dsCode);
                return Collections.emptyMap();
            }

            // 3. 构建字段Map和关联Map
            Map<String, ReportField> fieldMap = datasource.getFields().stream()
                .collect(Collectors.toMap(ReportField::getFieldCode, Function.identity()));

            Map<String, ReportRelation> relationMap = datasource.getRelations().stream()
                .collect(Collectors.toMap(ReportRelation::getRelationCode, Function.identity()));

            Map<String, List<String>> fieldRelationMap = new HashMap<>();
            for (ReportField field : datasource.getFields()) {
                if (CollectionUtils.isNotEmpty(field.getRelationCodes())) {
                    fieldRelationMap.put(field.getFieldCode(), field.getRelationCodes());
                }
            }

            // 4. 构建汇总SQL
            DynamicSqlBuilder.BuildResult buildResult = DynamicSqlBuilder.buildSummarySql(
                datasource, fieldMap, relationMap, fieldRelationMap, effectiveConfig);

            if (!buildResult.isSuccess()) {
                logger.warn("构建汇总SQL失败: {}", buildResult.getErrorMsg());
                return Collections.emptyMap();
            }

            // 5. 执行查询
            logger.info("执行汇总查询SQL: {}", buildResult.getSql());

            Map<String, Object> summary = reportMapper.executeDynamicSummary(buildResult.getSql(), buildResult.getParams());
            return summary != null ? summary : Collections.emptyMap();

        } catch (Exception e) {
            logger.error("执行汇总查询异常", e);
            return Collections.emptyMap();
        }
    }

    @Override
    public void exportToExcel(HttpServletResponse response, ReportQueryResult result, String fileName) {
        if (result == null || CollectionUtils.isEmpty(result.getRows())) {
            logger.warn("导出数据为空");
            return;
        }

        try (Workbook workbook = new XSSFWorkbook()) {
            Sheet sheet = workbook.createSheet("报表数据");

            // 创建表头样式
            CellStyle headerStyle = workbook.createCellStyle();
            headerStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
            headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
            headerStyle.setAlignment(HorizontalAlignment.CENTER);
            headerStyle.setBorderBottom(BorderStyle.THIN);
            headerStyle.setBorderTop(BorderStyle.THIN);
            headerStyle.setBorderLeft(BorderStyle.THIN);
            headerStyle.setBorderRight(BorderStyle.THIN);

            Font headerFont = workbook.createFont();
            headerFont.setBold(true);
            headerStyle.setFont(headerFont);

            // 创建数据样式
            CellStyle dataStyle = workbook.createCellStyle();
            dataStyle.setAlignment(HorizontalAlignment.CENTER);
            dataStyle.setBorderBottom(BorderStyle.THIN);
            dataStyle.setBorderTop(BorderStyle.THIN);
            dataStyle.setBorderLeft(BorderStyle.THIN);
            dataStyle.setBorderRight(BorderStyle.THIN);

            // 数值样式
            CellStyle numberStyle = workbook.createCellStyle();
            numberStyle.cloneStyleFrom(dataStyle);
            numberStyle.setAlignment(HorizontalAlignment.RIGHT);

            List<ReportQueryResult.ColumnDefine> columns = result.getColumns();
            List<Map<String, Object>> rows = result.getRows();

            // 创建表头
            Row headerRow = sheet.createRow(0);
            for (int i = 0; i < columns.size(); i++) {
                Cell cell = headerRow.createCell(i);
                ReportQueryResult.ColumnDefine col = columns.get(i);
                String label = col.getLabel();
                if (StringUtils.isNotBlank(col.getUnit())) {
                    label += "(" + col.getUnit() + ")";
                }
                cell.setCellValue(label);
                cell.setCellStyle(headerStyle);

                // 设置列宽
                int width = col.getMinWidth() != null ? col.getMinWidth() : 100;
                sheet.setColumnWidth(i, width * 40);
            }

            // 填充数据
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            SimpleDateFormat datetimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            for (int rowIdx = 0; rowIdx < rows.size(); rowIdx++) {
                Row dataRow = sheet.createRow(rowIdx + 1);
                Map<String, Object> rowData = rows.get(rowIdx);

                for (int colIdx = 0; colIdx < columns.size(); colIdx++) {
                    Cell cell = dataRow.createCell(colIdx);
                    ReportQueryResult.ColumnDefine col = columns.get(colIdx);
                    Object value = rowData.get(col.getProp());

                    if (value == null) {
                        cell.setCellValue("");
                        cell.setCellStyle(dataStyle);
                    } else if ("number".equals(col.getType())) {
                        if (value instanceof Number) {
                            cell.setCellValue(((Number) value).doubleValue());
                        } else {
                            cell.setCellValue(value.toString());
                        }
                        cell.setCellStyle(numberStyle);
                    } else if ("date".equals(col.getType()) && value instanceof Date) {
                        cell.setCellValue(dateFormat.format((Date) value));
                        cell.setCellStyle(dataStyle);
                    } else if ("datetime".equals(col.getType()) && value instanceof Date) {
                        cell.setCellValue(datetimeFormat.format((Date) value));
                        cell.setCellStyle(dataStyle);
                    } else {
                        cell.setCellValue(value.toString());
                        cell.setCellStyle(dataStyle);
                    }
                }
            }

            // 输出文件
            String exportFileName = StringUtils.isNotBlank(fileName) ? fileName : "报表";
            exportFileName = exportFileName + "_" + System.currentTimeMillis() + ".xlsx";

            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(exportFileName, "UTF-8"));

            OutputStream outputStream = response.getOutputStream();
            workbook.write(outputStream);
            outputStream.flush();

            logger.info("导出Excel成功: {}, 行数: {}", exportFileName, rows.size());

        } catch (Exception e) {
            logger.error("导出Excel异常", e);
            throw new RuntimeException("导出失败: " + e.getMessage());
        }
    }

    // ==================== 私有辅助方法 ====================

    /**
     * 解析查询配置（处理模板和变量替换）
     */
    private ReportQueryConfig resolveQueryConfig(ReportQueryConfig queryConfig) {
        if (queryConfig == null) {
            return null;
        }

        // 如果指定了模板，加载模板配置
        if (StringUtils.isNotBlank(queryConfig.getTemplateCode())) {
            ReportTemplate template = selectTemplateByCode(queryConfig.getTemplateCode());
            if (template == null) {
                logger.warn("模板不存在: {}", queryConfig.getTemplateCode());
                return null;
            }

            ReportQueryConfig templateConfig = template.getQueryConfig();
            if (templateConfig == null) {
                logger.warn("模板配置解析失败: {}", queryConfig.getTemplateCode());
                return null;
            }

            // 合并配置：用户传入的参数覆盖模板默认值
            mergeQueryConfig(templateConfig, queryConfig);
            return templateConfig;
        }

        return queryConfig;
    }

    /**
     * 合并查询配置
     */
    private void mergeQueryConfig(ReportQueryConfig target, ReportQueryConfig source) {
        // 合并数据源
        if (StringUtils.isNotBlank(source.getDsCode())) {
            target.setDsCode(source.getDsCode());
        }

        // 合并字段选择
        if (CollectionUtils.isNotEmpty(source.getSelectedFields())) {
            target.setSelectedFields(source.getSelectedFields());
        }

        // 合并分页
        if (source.getPageNum() != null) {
            target.setPageNum(source.getPageNum());
        }
        if (source.getPageSize() != null) {
            target.setPageSize(source.getPageSize());
        }

        // 合并导出标志
        if (source.getExportAll() != null) {
            target.setExportAll(source.getExportAll());
        }

        // 合并参数值（用于模板变量替换）
        if (source.getParams() != null) {
            if (target.getParams() == null) {
                target.setParams(new HashMap<>());
            }
            target.getParams().putAll(source.getParams());
        }

        // 处理条件中的模板变量替换
        if (CollectionUtils.isNotEmpty(target.getConditions()) && source.getParams() != null) {
            for (ReportQueryConfig.QueryCondition condition : target.getConditions()) {
                if (condition.getValue() instanceof String) {
                    String strValue = (String) condition.getValue();
                    if (strValue.startsWith("${") && strValue.endsWith("}")) {
                        String varName = strValue.substring(2, strValue.length() - 1);
                        Object replacement = source.getParams().get(varName);
                        if (replacement != null) {
                            condition.setValue(replacement);
                        }
                    }
                }
                if (condition.getValue2() instanceof String) {
                    String strValue = (String) condition.getValue2();
                    if (strValue.startsWith("${") && strValue.endsWith("}")) {
                        String varName = strValue.substring(2, strValue.length() - 1);
                        Object replacement = source.getParams().get(varName);
                        if (replacement != null) {
                            condition.setValue2(replacement);
                        }
                    }
                }
            }
        }
    }
}