package com.yn.bftl.thirdparty.modules.umeng.util;

import com.alibaba.fastjson.JSONObject;
import com.yn.bftl.thirdparty.common.util.HttpClientUtil;
import com.yn.bftl.thirdparty.modules.umeng.abstracts.AbstractUmengNotification;
import com.yn.bftl.thirdparty.modules.umeng.vo.UmengResponseVO;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;


/**
 * 友盟推送工具类
 *
 * @author huabiao
 * @create 2023/12/5  16:37
 **/
public class UmengPushUtil {

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

    /**
     * user-agent定义
     */
    private static final String USER_AGENT = "Mozilla/5.0";

    private static final String REQUEST_METHOD = "POST";

    /**
     * 友盟推送-发送
     *
     * @param abstractUmengNotification 友盟消息
     * @param host                      域名
     * @param postPath                  请求路径
     * @return true:请求成功;false:请求失败
     * @author huabiao
     * @create 2023/12/5  16:48
     */
    public static boolean send(AbstractUmengNotification abstractUmengNotification, String host, String postPath) {
        try {
            String timestamp = Integer.toString((int) (System.currentTimeMillis() / 1000));
            abstractUmengNotification.setPredefinedKeyValue("timestamp", timestamp);
            // 拼接请求路径
            String url = host + postPath;
            // 获取请求体的json字符串
            String postBody = abstractUmengNotification.getPostBody();
            // 计算sign
            String sign = DigestUtils.md5Hex((REQUEST_METHOD + url + postBody + abstractUmengNotification.getAppMasterSecret()).getBytes("utf8"));
            // 发送请求
            JSONObject jsonObject = HttpClientUtil
                    .getInstance()
                    .setHeaderMap(new HashMap<String, String>() {{
                        put("User-Agent", USER_AGENT);
                    }})
                    .sendPost(url + "?sign=" + sign, abstractUmengNotification.getPostBody());
            UmengResponseVO umengResponseVO = jsonObject.toJavaObject(UmengResponseVO.class);
            if ("SUCCESS".equals(umengResponseVO.getRet())) {
                return true;
            } else {
                logger.error("友盟发送消息失败：错误码[%s],错误信息[%s]", umengResponseVO.getData().getErrorCode(), umengResponseVO.getData().getErrorMsg());
                return false;
            }
        } catch (Exception exception) {
            logger.error("友盟发送消息异常：" + exception.getMessage());
        }
        return true;
    }
}
