package com.reyun.saas.common.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpResponse;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

public class DingDingSendMsgUtil {

    protected Logger logger = LoggerFactory.getLogger(DingDingSendMsgUtil.class);
    public static final String KEY_USER_REG_MSG = "SECd2d97f7e01afbfe6dff6357200627ef08dd61072758eeafa606f1a73560ac57e";
    public static final String TOKEN_USER_REG_MSG = "0d0e61bed679887b2f9fbe40d7e6bec884d24399b0585730b0256c906f9084de";
    public static final String KEY_PWD_MSG = "SEC4b14e7e40c2509a2f52ff9a313f07604291f6665a2d39449dc46e821cd26722d";
    public static final String TOKEN_PWD_MSG = "d4cca03cf3069a37d0f6e4d2ebf5042278bff98884482d782ed92668817660bc";
    public static final String KEY_EXCEPTION_PUSH_MSG = "SECb4c8930d030ae57266ce78b0eaa889ec1d7b2e2ad294fbada59ae775cac4a150";
    public static final String TOKEN_EXCEPTION_PUSH_MSG = "875c331316e5d8cd2a4177b195098670e127ac23a38d518b5cbb8f59a37e554f";

    private String dingToken;
    private String dingKey;


    public DingDingSendMsgUtil(String dingToken, String dingKey) {
        this.dingToken = dingToken;
        this.dingKey = dingKey;
    }

    public DingDingSendMsgUtil() {

    }

    public void sendMsg(String content) {
        StringBuffer url = new StringBuffer("https://oapi.dingtalk.com/robot/send?access_token=");
        long timesamp = System.currentTimeMillis();
        url.append(dingToken).append("&timestamp=").append(timesamp).append("&sign=").append(getSignNew(timesamp, dingKey));
        sendMsg(url.toString(), content);
    }

    public void sendMsg(String url, String content) {
        HttpClient httpclient = HttpClients.createDefault();

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

        String textMsg = "{ \"msgtype\": \"text\", \"text\": {\"content\": \"" + content + "\"}}";
        StringEntity se = new StringEntity(textMsg, "utf-8");
        httppost.setEntity(se);
        try {
            HttpResponse response = httpclient.execute(httppost);
            String result = EntityUtils.toString(response.getEntity(), "utf-8");
            JSONObject jsonObject = JSONObject.parseObject(result);
            if (jsonObject.get("errcode") != null && !"0".equals(jsonObject.get("errcode").toString())) {
                logger.warn("钉钉消息发送失败：\n\nURL：" + url + "\n\nContent:" + content + "\n\n失败原因：" + result);
            }
        } catch (Exception e) {
            logger.error("钉钉消息发送失败：\n\nURL：" + url + "\n\nContent:" + content, e);
        }

    }

    /**
     * 功能描述:机器人加签所需，获取签名
     *
     * @param secret    密钥，机器人安全设置页面，加签一栏下面显示的SEC开头的字符串
     * @param timestamp 当前时间戳，单位是毫秒，与请求调用时间误差不能超过1小时
     * @author liyin
     * @date 2019/11/26
     */
    public String getSignNew(Long timestamp, String secret) {
        try {
            String stringToSign = timestamp + "\n" + secret;
            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
            byte[] signData = mac.doFinal(stringToSign.getBytes(StandardCharsets.UTF_8));
            return URLEncoder.encode(new String(Base64.encodeBase64(signData)), "UTF-8");
        } catch (Exception e) {
            logger.warn(e.getMessage());
            return null;
        }
    }

    public static void main(String[] args) {
        DingDingSendMsgUtil dingDingUtil = new DingDingSendMsgUtil();
        long timeMillis = System.currentTimeMillis();
        String sign = dingDingUtil.getSignNew(timeMillis, DingDingSendMsgUtil.KEY_USER_REG_MSG);
        String url = "https://oapi.dingtalk.com/robot/send?access_token=0d0e61bed679887b2f9fbe40d7e6bec884d24399b0585730b0256c906f9084de&timestamp=" + timeMillis + "&sign=" + sign;
        StringBuilder sb = new StringBuilder("Company：");
        sb
                .append("热云Mob").append("\n")
                .append("Email：").append("243242@reyun.com").append("\n")
                .append("姓名：").append("先生").append("\n")
                .append("手机号：").append("13209348934").append("\n")
                .append("微信：").append("wx123").append("\n")
                .append("QQ：").append("413747222");
        dingDingUtil.sendMsg(url, sb.toString());
    }
}
