package com.zd.common.core.template;

import lombok.Data;

import java.util.List;

/**
 *         Template template = new Template();
 *         template.setTemplateId("OsVgepQzR6ssWSJsQfttHn-aV61CMWPIn5CRM2Y9GL8");
 *         template.setToUser("oWO3z5IZ7eUGjMTFtVynzWZxhvGY");
 *         template.setPage("pages/index/index");
 *         List<TemplateParam> paras = new ArrayList<>();
 *         paras.add(new TemplateParam("thing1", "测试内容"));
 *         paras.add(new TemplateParam("thing2", "测试标题"));
 *         paras.add(new TemplateParam("time3", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime())));
 *         paras.add(new TemplateParam("thing4", "管理员"));
 *         template.setData(paras);
 */

@Data
public class Template {

    private String toUser;
    private String templateId;
    private String page;
    private List<TemplateParam> data;

    private String miniProgramState;

    private String lang = "zh_CN";

    public String toJSON() {
        StringBuilder builder = new StringBuilder();
        builder.append("{");
        builder.append(String.format("\"touser\":\"%s\"", this.toUser)).append(",");
        builder.append(String.format("\"template_id\":\"%s\"", this.templateId)).append(",");
        builder.append(String.format("\"page\":\"%s\"", this.page)).append(",");
        builder.append(String.format("\"miniprogram_state\":\"%s\"", this.miniProgramState)).append(",");
        builder.append(String.format("\"lang\":\"%s\"", this.lang)).append(",");
        builder.append("\"data\":{");

        TemplateParam param ;
        for (int i = 0; i < this.data.size(); i++) {
            param = data.get(i);
            // 判断是否追加逗号
            if (i < this.data.size() - 1) {
                builder.append(String.format("\"%s\": {\"value\":\"%s\"},", param.getKey(), param.getValue()));
            } else {
                builder.append(String.format("\"%s\": {\"value\":\"%s\"}", param.getKey(), param.getValue()));
            }
        }
        builder.append("}");
        builder.append("}");
        return builder.toString();
    }
}
