package com.fdkankan.modeling.utils;

import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiRobotSendRequest;
import com.dingtalk.api.response.OapiRobotSendResponse;
import com.fdkankan.utils.utils.Base64Converter;
import com.fdkankan.modeling.constants.SysConstants;
import com.taobao.api.ApiException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

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.ArrayList;

@Component
public class DingDingUtils {

    private static final Logger log = LoggerFactory.getLogger(DingDingUtils.class);

    private static String environment;

    private static String token;

    private static String secret="SECca5af660ed882a67d8bda469095bf8454831528bd25bc7b1a3ff5f686109b9e5";

    @Value("${environment:dev}")
    public void setEnvironment(String environment){
        DingDingUtils.environment = environment;
    }

    @Value("${dingtalk.token:e712c41d917b303e21c1550ad9966b33dad874043f2f73fb347dce67a0a201bc}")
    public void setToken(String token) {
        DingDingUtils.token = token;
    }

    @Value("${dingtalk.secret:SECca5af660ed882a67d8bda469095bf8454831528bd25bc7b1a3ff5f686109b9e5}")
    public void setSign(String secret) {
        DingDingUtils.secret = secret;
    }

    private static String msgPattern = "**环境**: %s\n\n" +
            "**服务器名称**: %s\n\n" +
            "**失败原因**: %s\n\n" +
            "**num**: %s\n\n" +
            "**server-path**: %s\n\n" +
            "**algorithm-log**: [https://4dkk.4dage.com/build_log/%s/console.log](https://4dkk.4dage.com/build_log/%s/console.log)";


    public static void sendMsgToDingRobot(String reason,String serverPath,String num) throws ApiException, UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException {
        String content = String.format(msgPattern,environment, SysConstants.hostName,reason,num,serverPath,num,num);
        //sendMsgToDingRobot(content);
    }

    public static void sendMsgToDingRobot(String content) throws ApiException, UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException {
        Long timestamp = System.currentTimeMillis();
        String sign = getSign(timestamp);
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/robot/send?" +
                "access_token="+token +
                "&timestamp=".concat(String.valueOf(timestamp)).concat("&sign=").concat(sign));
        OapiRobotSendRequest request = new OapiRobotSendRequest();
        request.setMsgtype("actionCard");
        OapiRobotSendRequest.Actioncard actioncard = new OapiRobotSendRequest.Actioncard();
        actioncard.setTitle("场景计算失败");
        actioncard.setText(content);
        request.setActionCard(actioncard);
        OapiRobotSendRequest.At at = new OapiRobotSendRequest.At();
        at.setAtMobiles(new ArrayList<>(0));
        // isAtAll类型如果不为Boolean，请升级至最新SDK
        at.setIsAtAll(true);
        request.setAt(at);
        OapiRobotSendResponse re = client.execute(request);
        System.out.println(re.getBody());
    }

    public static String getSign(Long timestamp) throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException {
        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"));
        System.out.println(new String(signData));
        return URLEncoder.encode(Base64Converter.encode(signData));
    }
}
