/**
 * Copyright (C), 2015-2020, XXX有限公司
 * FileName: DingdingService
 * Author:   a112233
 * Date:     2020/7/3 6:24 PM
 * Description:
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package com.cretin.notice.dingding;

import com.cretin.webdb.utils.ParamUtils;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiRobotSendRequest;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.util.TextUtils;
import org.springframework.stereotype.Service;

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

/**
 * 〈〉
 *
 * @author a112233
 * @create 2020/7/3
 * @since 1.0.0
 */
@Service
public class DingdingService {


    /**
     * 发送钉钉消息
     *
     * @param title
     * @param markdownMsg
     */
    public void sendMarkdownMsg(String title, String markdownMsg) {
        String serverAddress = getNoticeDingding();
        if (TextUtils.isEmpty(serverAddress)) {
            return;
        }
        String secret = ParamUtils.getParamsByName(serverAddress, "token");
        try {
            if (!TextUtils.isEmpty(secret)) {
                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");
                serverAddress = serverAddress + "&sign=" + sign + "&timestamp=" + timestamp;
            }

            DingTalkClient client = new DefaultDingTalkClient(serverAddress);
            OapiRobotSendRequest request = new OapiRobotSendRequest();
            request.setMsgtype("markdown");
            OapiRobotSendRequest.Markdown markdown = new OapiRobotSendRequest.Markdown();
            markdown.setTitle(title);
            markdown.setText(markdownMsg);
            request.setMarkdown(markdown);
            client.execute(request);
        } catch (Exception e) {

        }
    }

    private String getNoticeDingding() {
        return "https://oapi.dingtalk.com/robot/send?access_token=f39ab3a7cd4e6268fb69bb6ed62a650321192bd70956dc3e898b0a41ddce210f&token=SECfeb033c067e2bdb928f13197f8771403cda705d39184143630b260aeedceb2c7";
    }
}