package com.gyt.shr.util;

import com.alibaba.fastjson.JSONObject;
import com.gyt.shr.config.settingConfig.MsgSendConfig;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class SendMsgUtils {

    @Autowired
    private MsgSendConfig msgSendConfig;

    public  boolean  sendCodeToPhone(String callPhone,String verifCode) throws IOException {
        String md5Sign = null;
        //密钥
        String appSecret = msgSendConfig.getAppSecret() ;
        //uuid
        String uuid = UUID.randomUUID().toString();
        System.out.println("uuid---" + uuid);
        //应用类型
        String appType = msgSendConfig.getAppType();
        //应用id
        String appId = msgSendConfig.getAppId();
        //url
        String url = msgSendConfig.getUrl();
        String signName = msgSendConfig.getSignName();
        log.error("url---" + url);
        //时间戳
        Date date = new Date();
        String time = String.valueOf(date.getTime());
        log.error("time---" + time);
        //参数
        JSONObject params = new JSONObject();
        params.put("appId", appId);
        params.put("templateId", msgSendConfig.getTemplateId());
        params.put("signName", signName);
        //批量发送才需要这个参数
        params.put("phone", callPhone);
//      params.put("phone", "18692279043");
        params.put("appId", appId);
        //验证码
        LinkedHashMap<String, String> param = new LinkedHashMap();
        param.put("param1", verifCode);
        //验证码
        params.put("params", param);
        //请求参数
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("time", time);
        jsonObject.put("uuid", uuid);
        jsonObject.put("phones", callPhone);
        md5Sign = md5Sign(appSecret, url, params, appType, time, uuid, jsonObject);
        jsonObject.put("md5Sign", md5Sign);
        log.error("md5Sign---" + md5Sign);
        log.error("params---" + params);
        Response resultResponse = sendMeesage(params, appType, appId, uuid, md5Sign, time);
        String body = resultResponse.body().string();
        log.error("body---" + body);
        JSONObject result = JSONObject.parseObject(body);
        String code = result.get("code").toString();
        if (!code.equals("200")) {
            return false;
        }
        return true;
    }

    private   Response sendMeesage(JSONObject params, String appType, String appId, String uuid, String md5Sign, String time) throws IOException {
        //发送请求
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(30, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .build();
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, params.toString());
        Request request = new Request.Builder()
                //.url(propt.getProperty("sendMessageTaskUrl")) //批量发送消息
                .url(msgSendConfig.getSendMessageUrl())
                .post(body)
                //X-*-Sign 指定的算法，可选范围目前只有 md5，后续如有必要会增添其他算法
                .addHeader("X-message-Algorithm", "md5")
                //时间戳，请求时间，防止重放攻击，目前后台最多延时 15 分钟
                .addHeader("X-message-Time", time)
                //终端应用类型，比如小程序设置为 1、WEB 端设置为 2、APP 端设 置为 3，建议设置 2
                .addHeader("X-message-AppType", appType)
                //应用唯一标识，用于判断是那个应用调用消息中心
                .addHeader("X-message-AppID", appId)
                //随机码，防止重放攻击，延时时间之内不能重复，客户端可以采 用 UUID 生成
                .addHeader("X-message-Nonce", uuid)
                //签名 Sign，具体说明看下文
                //MD5( APPSECRET+路径+参数 +X-*-AppType +X-*-Time +X-*-Nonce )
                .addHeader("X-message-Sign", md5Sign)
                .addHeader("Content-Type", "application/json")
                .addHeader("User-Agent", "PostmanRuntime-ApipostRuntime/1.1.0")
                .addHeader("Connection", "keep-alive")
                .addHeader("Accept", "*/*")
                .build();
        return client.newCall(request).execute();
    }


    /**
     * 获取 sign
     * @param appSecret 密钥
     * @param url       url
     * @param params    参数
     * @param appType   类型 建议为2
     * @param appTime   时间戳
     * @param nonce     随机码
     * @return
     */
    public static String md5Sign(String appSecret, String url, Map params, String appType, String appTime, String nonce, JSONObject jsonObject) {
        String code = appSecret + url + params.toString() + appType + appTime + nonce;
        log.error("code---" + code);
        jsonObject.put("code", code);
        return DigestUtils.md5Hex(code).toLowerCase();
    }

}
