package com.kingdee.eas.custom.TestDemo;


import com.fasterxml.jackson.databind.ObjectMapper;

import okhttp3.*;
import org.apache.commons.codec.digest.DigestUtils;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.TimeUnit;

public class Demo1 {

    public static void main(String[] args) {
        try {
            //密钥
            String appSecret = "r6duQGOuwDw4QeF/TJi6tw==";
            //uuid
            String uuid = UUID.randomUUID().toString();
            //应用类型
            String appType = "2";
            //应用id
            String appId = "adrm";
            //url
            String url = "/spi/sendSms";
            //时间戳
            String time = String.valueOf(new Date().getTime());
            //参数
            Map params = new HashMap();
            params.put("appId", "adrm");
            params.put("templateId", "MSG_2024090901");
            params.put("signName", "登录验证");
            String phone = encrypt("13434413173", appSecret);
            params.put("phone", phone);
            params.put("appId", "adrm");
            String md5Sign = md5Sign(appSecret, url, params, appType, time, uuid);
            //发送请求
            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("https://msgdev.gooeto.com/api/spi/sendSms")
                    .post(body)
                    //X-*-Sign 指定的算法，可选范围目前只有 md5，后续如有必要会增添其他算法
                    .addHeader("X-message-Algorithm", "md5")
                    //时间戳，请求时间，防止重放攻击，目前后台最多延时 15 分钟
                    .addHeader("X-message-Time", String.valueOf(new Date().getTime()))
                    //终端应用类型，比如小程序设置为 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("Accept", "*/*")
                    //.addHeader("Accept-Encoding", "gzip, deflate, br")
                    .addHeader("User-Agent", "PostmanRuntime-ApipostRuntime/1.1.0")
                    .addHeader("Connection", "keep-alive")
                    .build();
            Response response = client.newCall(request).execute();

            ObjectMapper mapper = new ObjectMapper();
//            Map map = mapper.readValue(response.toString(), Map.class);
//            System.out.println(map.toString());
            System.out.println(response);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    /**
     * 获取 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) {
        //System.out.println(params.toString());
        String code = appSecret + url + params.toString() + appType + appTime + nonce;
        return DigestUtils.md5Hex(code).toLowerCase();
    }

    /**
     * aes加密
     *
     * @param phone
     * @param appSecret
     * @return
     * @throws Exception
     */
    public static String encrypt(String phone, String appSecret) throws Exception {
        // 将自定义的字符串密钥转换为字节数组，注意要确保长度符合要求（AES 128位对应16字节等）
        byte[] keyBytes = appSecret.getBytes(StandardCharsets.UTF_8);
        // 如果密钥长度不符合要求，这里可以进行适当处理，比如截取或填充等，示例采用简单截取到16字节长度（仅针对128位AES示例）
        if (keyBytes.length > 16) {
            keyBytes = java.util.Arrays.copyOf(keyBytes, 16);
        } else if (keyBytes.length < 16) {
            byte[] newKeyBytes = new byte[16];
            System.arraycopy(keyBytes, 0, newKeyBytes, 0, keyBytes.length);
            keyBytes = newKeyBytes;
        }

        SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, "AES");
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
        byte[] encryptedBytes = cipher.doFinal(phone.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }


}
