package cn.com.taiji.beidou.framework.web.util;

import com.alibaba.fastjson2.JSONObject;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Random;
import java.util.UUID;

/**
 * @Author CHEN
 * @Date 2022/11/8 9:34
 */
public class SmsUtil{

    private static String[] NUMBERS = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"};
    private static Random RANDOM = new Random();

    @Value("${sms.url-prefix}")
    private String url;
    @Value("${sms.port}")
    private String port;
    /**
     * 经办机构编码
     */
    private static final String JBJGBM = "460000008";

    /**
     * 接口账号用户名
     */
    private static final String AP_ID = "sgpttyrzzx";

    /**
     * 签名编码
     */
    private static final String SIGN = "zSp2Jjtnao1AikYI";

    /**
     * 密钥
     */
    private static final String SECRET_KEY = "tdOcOn";

    /**
     * 获取随机的数字
     * @param length
     * @return
     */
    public static String getRandomCode(Integer length) {
        StringBuilder builder = new StringBuilder(length);
        for (int i = 0; i < length; i++) {
            builder.append(NUMBERS[RANDOM.nextInt(NUMBERS.length)]);
        }

        return builder.toString();
    }


    /**
     * 拼接短信平台参数
     * @param mobiles
     * @param validCode
     * @return
     * @throws Exception
     */
    private static String GetSmsParam(String mobiles, String validCode) throws Exception {
        HashMap<String, String> submit = new HashMap<>();
        // 经办机构编码
        submit.put("jbjgbm",JBJGBM);
        System.out.println("jbjgbm："+ JBJGBM);

        // 接口账号用户名
        submit.put("apId",AP_ID);
        System.out.println("apId："+ AP_ID);

        // 短信流水号
        String uuid = UUID.randomUUID().toString();
        uuid = uuid.replace("-","");
        submit.put("dxId",uuid);
        System.out.println("dxId：" + submit.get("dxId"));

        // 短信类型
        submit.put("dxType","900");
        System.out.println("dxType："+ "900");

        // 收信手机号
        submit.put("mobiles",mobiles);
        System.out.println("mobiles："+ submit.get("mobiles"));

        // 短信内容
        submit.put("content","【海南社会管理信息化平台】 您的登录验证码为：" + validCode + "。有效时长为10分钟，请勿将验证码告知他人。");
        System.out.println("content："+ submit.get("content"));

        // 签名
        submit.put("sign",SIGN);
        System.out.println("sign："+ SIGN);

        // 短信优先级
        submit.put("priority","5");
        System.out.println("priority："+ "5");

        StringBuffer sb = new StringBuffer();
        //sb.append("【jbjgbm】");
        sb.append(submit.get("jbjgbm"));
        //sb.append("【apId】");
        sb.append(submit.get("apId"));
        //sb.append("【secretKey】");
        sb.append(SECRET_KEY);
        //sb.append("【dxId】");
        sb.append(submit.get("dxId"));
        //sb.append("【dxType】");
        sb.append(submit.get("dxType"));
        //sb.append("【mobiles】");
        sb.append(submit.get("mobiles"));
        //sb.append("【content】");
        sb.append(submit.get("content"));
        //sb.append("【sign】");
        sb.append(submit.get("sign"));
        //sb.append("【priority】");
        sb.append(submit.get("priority"));
        System.out.println("StringBuffer：" + sb.toString());


        // MD5 加密参数
        String recordMac = Md5Utils.md5(sb.toString());
        System.out.println("Mac：" + recordMac);
        submit.put("mac",recordMac);
        String params = JSONObject.toJSONString(submit);
        System.out.println("JSON Params：" + params);

        // BASE64加密参数
        String encode = Base64.encodeBase64String(params.getBytes(StandardCharsets.UTF_8));
        System.out.println("params：" + encode);
        return encode;
    }

    /**
     * 发送短信
     * @param mobiles
     * @param validCode
     * @return
     * @throws Exception
     */
    public static String sendSms(String mobiles, String validCode) throws Exception {
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setConnectTimeout(5000);
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        String data = GetSmsParam(mobiles,validCode);

        // post发送请求
        // 互联网地址测试：10.113.50.2:18010
        // 政务外网正式：172.19.150.2:18003
        ResponseEntity<String> exchange = restTemplate.exchange("http://10.113.50.2:18003/sms/api/smsData.do?addMessage&data=" + data, HttpMethod.POST, null, String.class);
        //获取idaas返回的json
        String resData = exchange.getBody();
        return resData;
    }
}
