package com.hotent.uc.util;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hotent.base.util.StringUtil;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
@Component
public class AliSmsUtil {
    private static  String smskey;
    @Value(value = "${aliSms.key}")
    public  void setSmskey(String smskey) {
        AliSmsUtil.smskey = smskey;
    }

    private static  String secret;
    @Value(value = "${aliSms.secret}")
    public  void setSecret(String secret) {
        AliSmsUtil.secret = secret;
    }

    private static  String extno;
    @Value(value = "${aliSms.extno}")
    public  void setExtno(String extno) {
        AliSmsUtil.extno = extno;
    }

    private static  String sendUrl;
    @Value(value = "${aliSms.sendUrl}")
    public  void setSendUrl(String sendUrl) {
        AliSmsUtil.sendUrl = sendUrl;
    }

    private static  String signName;
    @Value(value = "${aliSms.signName}")
    public  void setSignName(String signName) {
        AliSmsUtil.signName = signName;
    }
    /**
     * Sign生成签名信息
     * 由4个参数的值和appkey的值，用字符串方式直接拼接，
     * 然后用md5 算法加密（MD5、32小写）md5(appid+extno+mobile+msg+appkey)
     * 中间无需空格、无需”+”号，这里的msg不需要urlencode。
     * appid、appkey 由平台分配
     */
    private static String getSign(String mobile, String msg, String aliSmsAppId, String aliSmsAppKey, String aliSmsExtNo){
        String encryptStr = "";
        if(StringUtils.isNotEmpty(mobile) && StringUtils.isNotBlank(msg)) {
            encryptStr = aliSmsAppId + aliSmsExtNo + mobile + msg + aliSmsAppKey;
        } else {
            encryptStr = aliSmsAppId + aliSmsAppKey;
        }
        return encrypt32(encryptStr);
    }

    /**
     * MD5 32位小写加密
     */
    public static String encrypt32(String encryptStr) {
        MessageDigest md5;
        try {
            md5 = MessageDigest.getInstance("MD5");
            byte[] md5Bytes = md5.digest(encryptStr.getBytes());
            StringBuffer hexValue = new StringBuffer();
            for (int i = 0; i < md5Bytes.length; i++) {
                int val = ((int) md5Bytes[i]) & 0xff;
                if (val < 16)
                    hexValue.append("0");
                hexValue.append(Integer.toHexString(val));
            }
            //默认小写，在tostring后加toUpperCase()即为大写加密
            encryptStr = hexValue.toString();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return encryptStr;
    }
    //发短信接口
    public static JSONObject sendMsg(String mobile,String content,String signNameStr){
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        JSONObject jsonObject = new JSONObject();
        try {
            httpClient = HttpClientBuilder.create().build();
            HttpPost post = new HttpPost(sendUrl);
            post.setHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
            String signNameTemp= "";
            if(StringUtil.isNotEmpty(signNameStr)){
                signNameTemp= "【"+signNameStr+"】";
            }else{
                signNameTemp= StringEscapeUtils.unescapeJava(signName);
            }

            String sign=getSign(mobile,URLEncoder.encode(signNameTemp+content),smskey,secret,extno);
            List<NameValuePair> params=new ArrayList<>();
            params.add(new BasicNameValuePair("appid",smskey));
            params.add(new BasicNameValuePair("extno",extno));
            params.add(new BasicNameValuePair("mobile",mobile));
            params.add(new BasicNameValuePair("msg", URLEncoder.encode(signNameTemp+content)));
            params.add(new BasicNameValuePair("sign",sign));
            System.out.println(params.toString());
//            StringEntity entity = new StringEntity(params.toString(), "utf-8");
            UrlEncodedFormEntity entity=new UrlEncodedFormEntity(params,"utf-8");
            post.setEntity(entity);
            response = httpClient.execute(post);
            HttpEntity responseEntity = response.getEntity();
            if (responseEntity != null) {
                String result = EntityUtils.toString(responseEntity); // responseEntity只能取一次
                System.out.println(result);
                if(result.contains(",")){
                    jsonObject.put("code",result.split(",")[0]);
                    jsonObject.put("tasked",result.split(",")[1]);
                    jsonObject.put("msg",result.split(",")[2]);
                    jsonObject.put("data",result);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            e.printStackTrace();
            String tmp = e.getMessage();
            jsonObject.put("code", "-1");
            jsonObject.put("tasked", "");
            jsonObject.put("msg", tmp.length()<=100? tmp: tmp.substring(0, 100));
            jsonObject.put("data", tmp.length()<=100? tmp: tmp.substring(0, 100));
            return jsonObject;
        } finally {
            try {
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return jsonObject;
    }

    public static void main(String[] args) {
    }

}
