package com.mmc.iuav.user.model.vo;

import com.alibaba.fastjson2.JSONObject;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springframework.util.CollectionUtils;

import javax.validation.constraints.NotNull;
import java.io.Serializable;
import java.util.List;

/**
 * @author: zj
 * @Date: 2023/5/23 19:24
 */
@Builder
@Data
@NoArgsConstructor
@AllArgsConstructor
public class WxMsgVO implements Serializable {
    private static final long serialVersionUID = 107288179600606045L;
    @ApiModelProperty(value = "用户id-仅适用云享飞客户端")
    private Integer userAccountId;
    @ApiModelProperty(value = "公众号的openId")
    private String openId;
    @ApiModelProperty(value = "unionId-全局通用")
    private String unionId;
    @ApiModelProperty(value = "模板id")
    @NotNull(message = "模板id不能为空")
    private String templemteId;
    @ApiModelProperty(value = "网页跳转连接")
    private String url;
    @ApiModelProperty(value = "小程序APPID")
    private String wxAppltAppId;
    @ApiModelProperty(value = "小程序跳转连接")
    private String appletPath;
    @ApiModelProperty(value = "标题")
    private MsgData title;
    @ApiModelProperty(value = "消息数组")
    private List<MsgData> data;
    @ApiModelProperty(value = "消息备注")
    private MsgData remark;

    public String buildMsgJson() {
        JSONObject obj = new JSONObject();
        obj.put("touser", this.openId);
        obj.put("template_id", this.templemteId);
        if (!StringUtils.isBlank(this.url)) {
            obj.put("url", this.url);
        }

        if (!StringUtils.isBlank(this.wxAppltAppId) && !StringUtils.isBlank(this.appletPath)) {
            JSONObject mini = new JSONObject();
            mini.put("appid", this.wxAppltAppId);
            mini.put("pagepath", this.appletPath);
            obj.put("miniprogram", mini);
        }
        JSONObject jd = new JSONObject();
        jd.put("first", this.convertMsg(title));
        if (!CollectionUtils.isEmpty(this.data)) {
            for (int i = 0; i < data.size(); i++) {
                String key = "keyword" + (i + 1);
                jd.put(key, this.convertMsg(data.get(i)));
            }
        }

        if (this.remark != null && !StringUtils.isBlank(this.remark.getValue())) {
            jd.put("remark", this.convertMsg(this.remark));
        }

        obj.put("data", jd);
        return obj.toJSONString();
    }

    public JSONObject convertMsg(MsgData msg) {
        JSONObject jb = new JSONObject();
        jb.put("value", msg.getValue());
        jb.put("color", msg.getColor());
        return jb;
    }
}
