package org.springblade.common.notify.dingding;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;

@Component
public class DingDingRobotMsgNotify {

    // public static String WEBHOOK_TOKEN =
    // "https://oapi.dingtalk.com/robot/send?access_token=d99a5ac3d336dea947195968221756dd8749f908b94505201c58fbf6e085c5ad";

    private String webhookUrl = "https://oapi.dingtalk.com/robot/send?access_token=%s";

    /**
     * 发送钉钉消息
     * @param accessToken 发送目标群对应的token值
     * @param message 消息内容
     * @return 发送结果，以JSON格式返回
     * @throws Exception
     */
    public String sendAlarmMsg(String accessToken, String message) throws Exception {
        String url = String.format(webhookUrl, accessToken);
        HttpClient httpclient = HttpClients.createDefault();

        HttpPost httppost = new HttpPost(url);
        httppost.addHeader("Content-Type", "application/json; charset=utf-8");

        String textMsg = getMessage(message);
        StringEntity se = new StringEntity(textMsg, "utf-8");
        httppost.setEntity(se);

        HttpResponse response = httpclient.execute(httppost);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            String result = EntityUtils.toString(response.getEntity(), "utf-8");
            return result;
        }
        return null;
    }

    private String getMessage(String message) {
        JSONObject subObj = new JSONObject();
        subObj.put("content", message);
        JSONObject obj = new JSONObject();
        obj.put("msgtype", "text");
        obj.put("text", subObj);
        String result = obj.toJSONString();
        return result;
    }
}