package com.ruoyi.quartz.task;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.Optional;

/**
 * @Describe 发送钉钉消息
 * @Author xiatao
 * @Date 2021/5/12 9:55
 **/
public class DingTalkUtil {

    // 请求地址
    private static final String URL = "https://oapi.dingtalk.com/robot/send?access_token=%s&timestamp=%s&sign=%s";
    enum DingRobot{
        BBB("服务崩了","53384b6cb0defa906d0dfd994ae71b66a1f49d0a8323092f1933eaa98c5a1f53", "SEC9f29863983dab7626066e4cf22ef59f63081f3af1f9da485701f5517408aca1f",true, new String[]{"15616193405"}),
        ;
        private String name;
        private String accessToken;
        private String secret;
        private boolean atAll;// true是全部，false发送给具体的手机号用户
        private String[] atPhone;

        DingRobot(String name, String accessToken, String secret, boolean atAll, String[] atPhone) {
            this.name = name;
            this.accessToken = accessToken;
            this.secret = secret;
            this.atAll = atAll;
            this.atPhone = atPhone;
        }
    }

    public static void sendMsg(String msg){
        sendMsgContent(msg, DingRobot.BBB);
    }
    public static void sendMsg(String msg, String... array){
        String format = Optional.ofNullable(array)
                .map(x->String.format(msg, x))
                .orElse(msg);
        sendMsgContent(format, DingRobot.BBB);
    }


    /**
     * @Author xiatao
     * @Description 发送dingDing消息
     * @Date 2021/5/12 10:34
     **/
    private static void sendMsgContent(String msg, DingRobot robot){
        try{
            // 钉钉的webhook
            Long timestamp = System.currentTimeMillis();
            String sign = getSign(timestamp, robot);
            String dingDingToken= String.format(URL, new String[]{robot.accessToken, timestamp + "",sign});;
            // 请求的JSON数据，这里我用map在工具类里转成json格式
            JSONObject json=new JSONObject();
            JSONObject text=new JSONObject();
            json.put("msgtype","text");
            text.put("content", DateUtil.format(new Date(), "[yyyy-MM-dd HH:mm:ss]") + msg);
            json.put("text",text);

            if (robot.atAll){// @所有人
                JSONObject at = new JSONObject();
                at.put("isAtAll",true);
                json.put("at", at);
            }else{// @指定用户
                JSONObject at = new JSONObject();
                at.put("isAtAll",false);
                at.put("atMobiles", robot.atPhone);
                json.put("at", at);
            }
            // 发送post请求
            String response = cn.hutool.http.HttpUtil.post(dingDingToken, json.toJSONString());
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        }
    }

    /**
     * @Author xiatao
     * @Description 签名方法
     * @Date 2021/5/12 10:33
     **/
    private static String getSign(Long timestamp, DingRobot robot) throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException {
        String secret = robot.secret;
        String stringToSign = timestamp + "\n" + secret;
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA256"));
        byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8"));
        return URLEncoder.encode(new String(Base64.encodeBase64(signData)),"UTF-8");
    }

    public static void main(String[] args) {
        DingTalkUtil.sendMsg("调试第一次！");
    }

}
