package com.crunii.micro.common.utils;

import com.crunii.micro.common.exception.BusinessException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author lmlksy
 * @date 2023/12/14 19:55
 */
public class SmsTemplateHandler {
    private static final Pattern PLACEHOLDER_PATTERN = Pattern.compile("\\$\\{([^}]+)\\}");


    public static List<String> convertMapValuesToStringList(Map<String, Object> paramsMap) {
        List<String> stringValues = new ArrayList<>();
        for (Object value : paramsMap.values()) {
            stringValues.add(String.valueOf(value));
        }
        return stringValues;
    }

    public static String fillTemplateAndStoreInDatabase(String smsTemplate, List<String> fillData) {
        smsTemplate = preprocessTemplate(smsTemplate);
        Map<String, String> dataMap = matchPlaceholdersWithFillData(smsTemplate, fillData);
        System.out.println(dataMap.toString());
        String textData = convertMapToString(dataMap);
        return textData;
    }

    private static Map<String, String> matchPlaceholdersWithFillData(String smsTemplate, List<String> fillData) {
        Matcher matcher = PLACEHOLDER_PATTERN.matcher(smsTemplate);
        Map<String, String> dataMap = new HashMap<>();
        int dataIndex = 0;

        while (matcher.find()) {
            if (dataIndex >= fillData.size()) {
                throw new BusinessException("占位符数量和填充数据数量不匹配");
            }
            String placeholder = matcher.group(1); // 获取匹配到的占位符内容
            dataMap.put(placeholder, fillData.get(dataIndex));
            dataIndex++;
        }

        if (dataIndex < fillData.size()) {
            throw new BusinessException("占位符数量和填充数据数量不匹配");
        }

        return dataMap;
    }

    private static String convertMapToString(Map<String, String> dataMap) {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            return objectMapper.writeValueAsString(dataMap);
        } catch (JsonProcessingException e) {
            throw new BusinessException("转换为JSON时出错");
        }
    }

    private static String preprocessTemplate(String smsTemplate) {
        return smsTemplate.replaceAll("\\[|\\]", ""); // 去除模板中的 []
    }
    public static void main(String[] args) {
        String smsTemplate = "${competition}开始报名了，快来看看吧"; // 传入的完整短信模板
        List<String> fillData = Arrays.asList("比赛A");

        String textData = SmsTemplateHandler.fillTemplateAndStoreInDatabase(smsTemplate, fillData);

        System.out.println("数据库格式: " + textData);
    }

}
