package com.thinkgem.jeesite.modules.message;

import com.alibaba.fastjson.JSONObject;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.utils.IdGen;
import com.thinkgem.jeesite.modules.user.bean.IdentityCodeRequest;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.client.fluent.Request;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author niehh
 * @Description: 短信工具类
 * @date 2018年03月22日 13:54
 */
public class MessageUtils {
    public static JSONObject sendMessage(String mobile,String code,String message) throws IOException, NoSuchAlgorithmException {


        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String timestamp = sdf.format(new Date());
        //		// 必须的验证参数
        String username = Global.getConfig("message.username");
        String password = Global.getConfig("message.password");
        String url = Global.getConfig("message.url");

        String extendCode = code;

        int dataCoding = 15; // UNICODE 编码
        int responseFormat = 2; // 返回格式为 Json 格式

        long externalId = 0x123456789L; // 自定义消int dataCoding = 8; // UNICODE 编码
        int transferEncoding = 3; // URLEncode+UTFint responseFormat = 2; // 返回格式为 Json 格String message = "这是一条测试短信,返回 J// 计算密码摘要
//        SimpleDateFormat sdf = new SimpleDateFormString timestamp = sdf.format(new Date() );
        MessageDigest md5 = null;
        md5 = MessageDigest.getInstance("MD5");

        md5.update( username.getBytes("utf8") );
        md5.update( password.getBytes("utf8") );
        md5.update( timestamp.getBytes("utf8") );
        md5.update( message.getBytes("utf8") );
        password = Base64.encodeBase64String( md5.digest() );
        StringBuilder sb = new StringBuilder();
        sb.append(url)
                .append("?un=").append( username )
                .append("&pw=").append( URLEncoder.encode(password,"utf8") )
                .append("&ts=").append( timestamp )
                .append("&da=").append( mobile )
                .append("&sa=").append( extendCode )
                .append("&ex=").append( externalId )
                .append("&dc=").append( dataCoding )
                .append("&tf=").append( transferEncoding )
                .append("&rf=").append( responseFormat )
                .append("&sm=").append( URLEncoder.encode(message, "utf8") );
        String req = sb.toString();
        System.out.println("request: " + req);
        // 以GET方式发起请求
        String result = Request.Get( req ).execute().returnContent().asString();
        System.out.println( "response: " + result );
        return JSONObject.parseObject(result);
    }


    public static void main(String[] args) throws IOException, NoSuchAlgorithmException {


    }

}
