package com.chuanglan.intsms.tools.sign;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.util.DigestUtils;

import java.io.IOException;
import java.util.Map;
import java.util.TreeMap;

/**
 * ChuanglanInterMessageDemo
 *
 * @author EDY
 * @createdAt 2023/11/6 14:54
 * @description
 */
@Slf4j
public class ChuanglanInterMessageDemo {
    private RequestConfig requestConfig = RequestConfig.custom()
            .setConnectTimeout(10000)
            .setSocketTimeout(10000).build();
    private CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(requestConfig).build();

    public static void main(String[] args) {
        new ChuanglanInterMessageDemo().sendSms();
    }

    public void sendSms() {
        String password = "You account password";
        SmsSendRequest smsRequest = new SmsSendRequest();
        smsRequest.setAccount("IM123456");
        smsRequest.setMobile("008618900000001");
        smsRequest.setMsg("这是一条测试短信");
        smsRequest.setUid("112233445566778899");

        String nonce = String.valueOf(System.currentTimeMillis());
        TreeMap<String, String> paramMap = JSON.parseObject(JSON.toJSONString(smsRequest), new TypeReference<TreeMap<String, String>>() {
        });
        paramMap.put("nonce", nonce);
        String sign = generateSign(password, paramMap);

        HttpEntity httpEntity = null;
        CloseableHttpResponse httpResponse = null;
        try {
            StringEntity stringEntity = new StringEntity(JSON.toJSONString(smsRequest), ContentType.APPLICATION_JSON);
            HttpPost httpPost = new HttpPost("https://intapi.253.com/send/sms");
            httpPost.addHeader("Content-Type", "application/json");
            httpPost.addHeader("nonce", nonce);
            httpPost.addHeader("sign", sign);
            httpPost.setEntity(stringEntity);
            httpResponse = httpClient.execute(httpPost);
            httpEntity = httpResponse.getEntity();
            String result = EntityUtils.toString(httpEntity);
            System.out.println(result);
            JSONObject rtn = JSON.parseObject(result);
            String code = rtn.getString("code");
            if("0".equals(code)) {
                System.out.println("提交成功");
                String messageId = rtn.getJSONObject("data").getString("messageId");
                System.out.println("messageId=" + messageId);
            } else {
                System.out.println(String.format("提交失败:code=%s, message=%s", code, rtn.getString("message")));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                EntityUtils.consume(httpEntity);
            } catch (IOException e) {
                e.printStackTrace();
            }
            if(httpResponse != null) {
                try {
                    httpResponse.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    private String generateSign(String password, TreeMap<String, String> paramMap) {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, String> entry : paramMap.entrySet()) {
            if (StringUtils.isNotBlank(entry.getValue())) {
                sb.append(entry.getKey());
                sb.append(entry.getValue());
            }
        }
        return DigestUtils.md5DigestAsHex((sb.toString() + password).getBytes()).toLowerCase();
    }
}
