package com.bailuntec.utils;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.params.SetParams;

import java.io.IOException;


@Slf4j
public final class RobotWorkWeixin {
    private final static OkHttpClient client = OkHttpUtil.getInstance();
    /**
     * 推送消息到企业微信机器人
     * 如果计算的Key值在Redis存在, 则一天内不会重复推送
     * @param webhook 微信回调地址
     * @param content 异常内容
     */
    public static void push(final String  webhook, final String content)   {
        Jedis jedis = RedisUtil.getResource();
        String contentSub = content.length() > 2000?content.substring(0,2000):content;
        String key = DigestUtils.md5DigestAsHex((webhook + contentSub).getBytes());
        if (!jedis.exists(key)) {
            MediaType mediaType = MediaType.parse("application/json");
            RequestBody body = RequestBody.create(mediaType, "{\"msgtype\": \"text\",\"text\": {\"content\": \"" + contentSub  + "\"}}");
            Request request = new Request.Builder()
                    .url(webhook)
                    .post(body)
                    .addHeader("Content-Type", "application/json")
                    .build();
            Response response = null;
            try {
                response = client.newCall(request).execute();
            } catch (IOException e) {
                throw new RuntimeException("回调企业微信机器人失败", e);
            } finally {
                if (response != null ) {
                    response.close();
                }
            }
            jedis.setex(key,86400,contentSub);
        }
        jedis.close();
    }
}
