package cn.com.capcloud.core.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Author LiaoJiaHui
 * @Create 2025/8/20
 */
public class TemplateReplace {
    public static void main(String[] args) {
        // 示例数据：对象包含数组（子对象）
        Map<String, Object> projectMap = new HashMap<>();
        projectMap.put("name", "项目A");
        projectMap.put("end_time", "2023-12-31");
        projectMap.put("local_funds", 500);
        projectMap.put("project_progress", "08");

        // 子对象
        Map<String, Object> childObject = new HashMap<>();
        childObject.put("childName", "childObject子项目");
        childObject.put("childInvestment", 500);
        projectMap.put("childObject", childObject);

        // 子对象数组
        List<Map<String, Object>> childList = new ArrayList<>();
        Map<String, Object> childA = new HashMap<>();
        childA.put("childName", "childListObjectA子项目");
        childA.put("childInvestment", 1000);
        childList.add(childA);
        Map<String, Object> childB = new HashMap<>();
        childB.put("childName", "childListObjectB子项目");
        childB.put("childInvestment", 1000);
        childList.add(childB);
        projectMap.put("childList", childList);

        // HTML 模板
        String htmlTemplate = "<tr>\n" +
                "    <td align=\"center\">${name}</td>\n" +
                "    <td align=\"center\">${end_time}</td>\n" +
                "    <td align=\"center\">${local_funds}</td>\n" +
                "    <td align=\"center\">\n" +
                "        <span align=\"center\">${project_progress == 01 ? 待完成 : project_progress == 02 ? '已完成' : project_progress == 03 ? 停工 : project_progress == 04 ? 待开工 : project_progress == 05 ? 待开工2 : project_progress == 06 ? 待开工3 : project_progress == 07 ? 待开工4 : project_progress}</span>\n" +
                "    </td>\n" +
                "    <td align=\"center\">${childObject.childName}</td>\n" +
                "    <td align=\"center\">${childObject.childInvestment}</td>\n" +
                "</tr>\n" +
                "${#childList}\n" +
                "<tr>\n" +
                "    <td align=\"center\">${childName}</td>\n" +
                "    <td align=\"center\">${childInvestment}</td>\n" +
                "</tr>\n" +
                "${/childList}";

        // 渲染模板
        String result = renderTemplate(htmlTemplate, projectMap);
        System.out.println(result);
    }

    // 渲染模板
    public static String renderTemplate(String template, Map<String, Object> data) {
        // 处理循环块
        Pattern loopPattern = Pattern.compile("\\$\\{#([a-zA-Z0-9_]+)\\}([\\s\\S]*?)\\$\\{/\\1\\}");
        Matcher loopMatcher = loopPattern.matcher(template);
        StringBuffer sb = new StringBuffer();

        while (loopMatcher.find()) {
            String listName = loopMatcher.group(1);
            String loopContent = loopMatcher.group(2);
            Object listObj = data.get(listName);
            StringBuilder loopResult = new StringBuilder();

            if (listObj instanceof List) {
                List<?> list = (List<?>) listObj;
                for (int index = 0; index < list.size(); index++) {
                    Object item = list.get(index);
                    if (item instanceof Map) {
                        // 给模板内容替换时传入 index
                        Map<String, Object> itemMap = (Map<String, Object>) item;
                        itemMap.put("index", index + 1); // 索引从 1 开始
                        loopResult.append(replacePlaceholders(loopContent, itemMap));
                    }
                }
            }
            loopMatcher.appendReplacement(sb, Matcher.quoteReplacement(loopResult.toString()));
        }
        loopMatcher.appendTail(sb);

        // 处理普通占位符
        return replacePlaceholders(sb.toString(), data);
    }

    // 替换占位符
    public static String replacePlaceholders(String template, Map<String, Object> data) {
        // 正则匹配占位符，包括简单的和带有三元运算符的
        Pattern p = Pattern.compile("\\$\\{([^\\}]+)\\}");
        Matcher m = p.matcher(template);
        StringBuffer sb = new StringBuffer();

        while (m.find()) {
            String expression = m.group(1);

            // 检查表达式是否为三元运算符
            if (expression.contains("?")) {
                // 三元运算符处理
                Object value = evaluateExpression(expression, data);
                m.appendReplacement(sb, Matcher.quoteReplacement(value != null ? value.toString() : ""));
            } else {
                // 普通占位符处理
                Object value = getValue(data, expression);
                m.appendReplacement(sb, Matcher.quoteReplacement(value != null ? value.toString() : ""));
            }
        }
        m.appendTail(sb);
        return sb.toString();
    }

    // 获取嵌套值
    public static Object getValue(Map<String, Object> data, String key) {
        String[] parts = key.split("\\.");
        Object current = data;
        for (String part : parts) {
            if (current instanceof Map) {
                current = ((Map<?, ?>) current).get(part);
            } else {
                return null;
            }
        }
        return current;
    }

    // 解析三元运算符逻辑
    public static Object evaluateExpression(String expression, Map<String, Object> data) {
        // 匹配三元运算符条件：a == b 部分（忽略 ? : 部分）
        Pattern pattern = Pattern.compile("([a-zA-Z0-9_\\.]+)\\s*(==|!=|>=|<=|<|>)\\s*(\\d+)");
        Matcher matcher = pattern.matcher(expression);
        // 提取字典条件映射
        Map<String, String> dictionary = extractDictionaryFromExpression(expression);
        // 循环匹配所有条件
        while (matcher.find()) {
            String conditionKey = matcher.group(1);  // 项目进度（a）
            String operator = matcher.group(2);  // 比较符（==）
            String conditionValue = matcher.group(3);  // 比如 '01'（b）

            // 获取实际的值
            String conditionKeyValue = getValue(data, conditionKey) != null ? getValue(data, conditionKey).toString() : "";

            // 判断条件是否成立
            boolean conditionMet = false;
            switch (operator) {
                case "==":
                    conditionMet = conditionKeyValue.equals(conditionValue);
                    break;
                case "!=":
                    conditionMet = !conditionKeyValue.equals(conditionValue);
                    break;
                case ">":
                    conditionMet = Double.parseDouble(conditionKeyValue) > Double.parseDouble(conditionValue);
                    break;
                case "<":
                    conditionMet = Double.parseDouble(conditionKeyValue) < Double.parseDouble(conditionValue);
                    break;
                case ">=":
                    conditionMet = Double.parseDouble(conditionKeyValue) >= Double.parseDouble(conditionValue);
                    break;
                case "<=":
                    conditionMet = Double.parseDouble(conditionKeyValue) <= Double.parseDouble(conditionValue);
                    break;
            }

            // 如果条件成立，返回条件值
            if (conditionMet) {
                conditionValue=dictionary.get(conditionKeyValue);
                return conditionValue;  // 返回匹配的条件值
            }
        }
        return getValue(data, dictionary.get("false")) != null ? getValue(data, dictionary.get("false")).toString() : dictionary.get("false");
    }

    public static Map<String, String> extractDictionaryFromExpression(String expression) {
        Map<String, String> dictionary = new HashMap<>();

        // 更新正则表达式，匹配三元运算符的条件和值部分，及最后的默认值 "project_progress"
        Pattern pattern = Pattern.compile("(==\\s*(\\d+))\\s*\\?\\s*([^:]+?)\\s*(?=:)|([^?\\s]+(?=\\s*$))");
        Matcher matcher = pattern.matcher(expression);

        // 查找所有匹配项
        while (matcher.find()) {
            if (matcher.group(2) != null) { // 匹配到条件和值
                String key = matcher.group(2);   // 条件值，如 "01"
                String value = matcher.group(3); // 对应的值，如 "待完成"
                if (value.startsWith("'") && value.endsWith("'")) {  // 如果值两端有单引号
                    value = value.substring(1, value.length() - 1);  // 去掉单引号
                }
                dictionary.put(key, value);  // 放入字典
            } else if (matcher.group(4) != null) { // 匹配到默认值 "project_progress"
                String value = matcher.group(4).trim();
                if (value.startsWith("'") && value.endsWith("'")) {  // 如果值两端有单引号
                    value = value.substring(1, value.length() - 1);  // 去掉单引号
                }
                dictionary.put("false", value); // 不成立的部分
            }
        }
        return dictionary;
    }
}

