SmsMessage.java 1.93 KB
package com.diligrp.assistant.sms.domain;

import com.diligrp.assistant.shared.util.ObjectUtils;
import org.apache.commons.text.StringSubstitutor;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SmsMessage {
    // 短信服务通道模版标识 - 支持短信模版的服务通道使用
    private String templateId;
    // 手机号
    private List<String> telephones;
    // 解析模版变量前的原始内容
    private String rawContent;
    // 解析模版变量后的短信内容
    private String content;
    // 模版变量
    private List<ParamPair> params;
    // 消息签名
    private String signature;

    public SmsMessage(String templateId, List<String> telephones, String rawContent, List<ParamPair> params, String signature) {
        this.templateId = templateId;
        this.telephones = telephones;
        this.rawContent = rawContent;
        this.params = params;
        this.signature = signature;
    }

    public String getTemplateId() {
        return templateId;
    }

    public List<String> getTelephones() {
        return telephones;
    }

    public String getContent() { // 延迟解析模版变量
        if (content == null) {
            content = parseContent(rawContent, params);
        }

        return content;
    }

    public String getRawContent() {
        return rawContent;
    }

    public List<ParamPair> getParams() {
        return params;
    }

    public String getSignature() {
        return signature;
    }

    private String parseContent(String rawContent, List<ParamPair> params) {
        if (!ObjectUtils.isEmpty(params)) { // 解析模版变量
            Map<String, String> paramMap = new HashMap<>(params.size());
            params.forEach(p -> paramMap.put(p.getKey(), p.getValue()));
            StringSubstitutor engine = new StringSubstitutor(paramMap);
            return engine.replace(rawContent);
        }

        return rawContent;
    }
}