package cn.reghao.autodop.dmaster.notification.service.notifier.ding;

import cn.reghao.autodop.common.http.WebRequest;
import cn.reghao.autodop.common.http.WebResponse;
import cn.reghao.jdkutil.serializer.JsonConverter;
import cn.reghao.autodop.dmaster.notification.model.po.DingAccount;
import cn.reghao.autodop.dmaster.notification.service.notifier.Notify;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

/**
 * 钉钉通知
 *
 * @author reghao
 * @date 2020-05-07 01:31:03
 */
public class DingNotify implements Notify<DingMsg> {
    private WebRequest webRequest;
    private DingAccount dingAccount;

    public DingNotify(WebRequest webRequest, DingAccount dingAccount) {
        this.webRequest = webRequest;
        this.dingAccount = dingAccount;
    }

    @Override
    public void send(String receiver, DingMsg msg) throws Exception {
        if (!"none".equals(dingAccount.getPassword())) {
            receiver = getReceiver(receiver, dingAccount.getPassword());
        }

        WebResponse webResponse = webRequest.postJson(receiver, JsonConverter.objectToJson(msg));
        if (webResponse.getStatusCode() != 200) {
            throw new Exception("通知发送失败, " + webResponse.getBody());
        }
    }

    private String getReceiver(String receiver, String secret) throws InvalidKeyException, NoSuchAlgorithmException {
        long timestamp = System.currentTimeMillis();
        //String secret = "SEC4d7e0c126147b3679c4d15e47dc26311ca053bd47b21f4025832a6e246a93ec4";
        String sign = calcSign(timestamp, secret);
        return receiver + String.format("&timestamp=%s&sign=%s", timestamp, sign);
    }

    /**
     * 钉钉机器人计算签名
     *
     * @param
     * @return
     * @date 2021-06-24 下午3:47
     */
    private String calcSign(long timestamp, String secret) throws NoSuchAlgorithmException, InvalidKeyException {
        String stringToSign = timestamp + System.lineSeparator() + 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.getEncoder().encode(signData)), StandardCharsets.UTF_8);
    }
}
