package com.zm.order.tool.server.manager;

import java.net.URLEncoder;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiRobotSendRequest;
import com.dingtalk.api.response.OapiRobotSendResponse;
import com.google.common.base.Throwables;
import com.zm.order.tool.server.constants.ExceptionConstants;
import com.zm.util.dto.Result;

/**
 * @Description 钉钉提示manager
 * @Author: ph
 * @Date: 2019/11/22 14:09
 */
@Component
public class DingTalkManager {

    private static final Logger logger = LoggerFactory.getLogger(DingTalkManager.class);

    @Value("${dingTalk.url}")
    private String url;

    @Value("${dingTalk.secret}")
    private String secret;

    public Result sendTextMessage(String message) {
        Result result = new Result();
        try {
            String requestUrl = genRequestUrl();
            DingTalkClient client = new DefaultDingTalkClient(requestUrl);
            OapiRobotSendRequest request = new OapiRobotSendRequest();
            request.setMsgtype("text");
            OapiRobotSendRequest.Text text = new OapiRobotSendRequest.Text();
            text.setContent(message);
            request.setText(text);
            OapiRobotSendResponse response = client.execute(request);
            if (!response.isSuccess()) {
                result.setException(ExceptionConstants.SEND_DING_TALK_MESSAGE_ERROR);
                return result;
            }
            result.setStatus(true);
        } catch (Throwable throwable) {
            logger.error("DingTalkManager[sendTextMessage] failed, cause by:{}", Throwables.getStackTraceAsString(throwable));
            throw new RuntimeException(throwable.getMessage());
        }
        return result;
    }

    private String genRequestUrl() throws Exception {
        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");
        StringBuilder sb = new StringBuilder(url);
        sb.append("&").append("timestamp").append("=").append(timestamp).append("&").append("sign").append("=").append(sign);
        return sb.toString();
    }
}
