package com.tax.file.utils;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.google.common.collect.Maps;
import com.tax.file.constants.FileConstants;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* 钉钉开发文档 https://ding-doc.dingtalk.com/doc#/serverapi2/qf2nxq
*/
public class DingdingUtil {

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

	public static final String ACCESS_TOKEN = FileConstants.ddAccessToken;
	public static final String DING_URL = FileConstants.ddUrl;
	public static final String SECRET = FileConstants.ddSecret;
	
    /**
    * @描述:发送群通知
    * @作者：bree
    * @日期：2020年2月3日 上午10:13:05
    * @param content 消息内容
    * @param isAtAll 是否通知所有人
    * @param mobileList 通知具体人的手机号码列表
    * @return 返回结果
    */
	public static String send(String content,boolean isAtAll,List<String> mobileList) {
		Long timestamp = System.currentTimeMillis();

        String result = "";
        try {
            String sign = getSign(timestamp);
            String url = String.format(DING_URL, ACCESS_TOKEN,timestamp,sign);

            Map paramMap = new HashMap();
            Map contentMap = new HashMap();
            contentMap.put("content", content);

            Map<String, Object> atMap = Maps.newHashMap();
            atMap.put("isAtAll", isAtAll);
            if(!isAtAll){
                atMap.put("atMobiles", mobileList);
            }

            paramMap.put("msgtype", "text");
            paramMap.put("text", contentMap);
            paramMap.put("at", atMap);

			result = HttpUtil.post(url, JSONUtil.parseFromMap(paramMap).toString());
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(content +  " send message is errro!" + e.getMessage());
		}
		return result;
	}
	   /**
	    * @描述:获取钉钉签名
	    * @作者：bree
	    * @日期：2020年2月3日 上午10:13:05
	    * @param timestamp 时间戳
	    * @return 返回结果
	    */
	public static String getSign(Long timestamp)throws Exception{
		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");
		return sign;
	}

	public static void main(String[] args) {
		try {
			String result = send("333",true,null);
			System.out.println(result);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
