package org.springblade.common.notify.dingding.handler;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
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.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class DingDingMsgSendHandler {

    @Value("${msg.notify.dingding.agentId:130557163}")
    private String agentId = "130557163"; //微应用ID

    /**
     * 发送钉钉消息
     *
     * @param accessToken 发送目标群对应的token值
     * @param userId      用户ID
     * @param message     消息内容
     * @return 发送结果，以JSON格式返回
     * @throws Exception
     */
    public String send(String accessToken, String userId, String message) throws Exception {
        String url = "https://oapi.dingtalk.com/message/send?access_token=" + accessToken;
        //String postJson = "{'touser':'115509541130014093','agentid':'130557163','msgtype':'text','text':{'content':'钉钉欢迎你,这个是测试消息5'}}";
        String postJson = this.getSendData(agentId, userId, message);
        HttpClient httpclient = HttpClients.createDefault();

        HttpPost post = new HttpPost(url);
        StringEntity se = new StringEntity(postJson, "utf-8");
        post.setEntity(se);

        HttpResponse response = httpclient.execute(post);
        log.info("调用钉钉接口的入参：{}", url);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            String result = EntityUtils.toString(response.getEntity(), "utf-8");
            log.info("DingDingMsgSendHandler.send dingding msg. result = {}", result);
            return result;
        } else {
            if (response.getEntity() != null) {
                log.error("DingDingMsgSendHandler.send dingding msg failure. result = {}",
                        EntityUtils.toString(response.getEntity(), "utf-8"));
            }
            return null;
        }

    }

    private String getSendData(String agentId, String userIds, String message) {
        JSONObject subObj = new JSONObject();
        subObj.put("content", message);
        JSONObject obj = new JSONObject();
        obj.put("touser", userIds);
        obj.put("agentid", agentId);
        obj.put("msgtype", "text");
        obj.put("text", subObj);
        String result = obj.toJSONString();
        return result;
    }

}