package com.xydl.cac.util;

import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiRobotSendRequest;
import com.dingtalk.api.response.OapiRobotSendResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLEncoder;

/**
 * 钉钉推送工具类
 */
@Component
@Slf4j
public class DingTalkPushUtil {

    @Value("${cac.dingding.send:false}")
    private boolean send;
    @Value("${cac.dingding.token}")
    private String token;
    @Value("${cac.dingding.secret}")
    private String secret;
    private String KEY_WORD = "CAC告警: ";


    public void pushText(String content) {
        if (send) {
            try {
                Long timestamp = System.currentTimeMillis();
                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"));
                String sign = URLEncoder.encode(new String(Base64.encodeBase64(signData)), "UTF-8");

                //sign字段和timestamp字段必须拼接到请求URL上，否则会出现 310000 的错误信息
                DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/robot/send?sign=" + sign + "&timestamp=" + timestamp);
                OapiRobotSendRequest req = new OapiRobotSendRequest();
                /**
                 * 发送文本消息
                 */
                //定义文本内容
                OapiRobotSendRequest.Text text = new OapiRobotSendRequest.Text();
                text.setContent(KEY_WORD + content);
                //设置消息类型
                req.setMsgtype("text");
                req.setText(text);
                OapiRobotSendResponse rsp = client.execute(req, token);
            } catch (Exception e) {
                log.error("钉钉发送失败", e);
            }
        }
    }

}

