package com.artfess.base.huawei.message.demo;

import com.artfess.base.huawei.message.utils.Constant;
import com.artfess.base.huawei.message.utils.HttpsUtil;
import com.artfess.base.huawei.message.utils.JsonUtil;
import com.artfess.base.huawei.message.utils.StreamClosedHttpResponse;
import com.artfess.base.huawei.message.utils.StringUtil;

import java.util.HashMap;
import java.util.Map;

import javax.net.ssl.HttpsURLConnection;


public class VoiceVerificationCode {
    // 语音验证码API的URL
    private String urlVoiceVerificationCode;
    // 接口响应的消息体
    private Map<String, String> responsebody;
    // Https实体
    private HttpsUtil httpsUtil;

    public VoiceVerificationCode() {
        // 商用地址
        urlVoiceVerificationCode = Constant.VOICE_VERIFICATION_COMERCIAL;
        responsebody = new HashMap<>();
    }

    @SuppressWarnings("unchecked")
    /*
     * 该示例只仅体现必选参数,可选参数根据接口文档和实际情况配置. 该示例不体现参数校验,请根据各参数的格式要求自行实现校验功能.
     */
    public String voiceVerificationCodeAPI(String displayNbr, String calleeNbr, int languageType, String preTone,
            String verifyCode) throws Exception {

        httpsUtil = new HttpsUtil();

        // 忽略证书信任问题
        httpsUtil.trustAllHttpsCertificates();
        HttpsURLConnection.setDefaultHostnameVerifier(httpsUtil.hv);

        // 请求Headers
        Map<String, String> headerMap = new HashMap<>();
        headerMap.put(Constant.HEADER_APP_AUTH, Constant.AUTH_HEADER_VALUE);
        headerMap.put(Constant.HEADER_APP_WSSE,
                StringUtil.buildWsseHeader(Constant.CALLVERIFY_APPID, Constant.CALLVERIFY_SECRET));

        // 构造消息体
        Map<String, Object> bodys = new HashMap<String, Object>();
        bodys.put("displayNbr", displayNbr);//主叫用户手机终端的来电显示号码。
        bodys.put("calleeNbr", calleeNbr);//发起呼叫时所拨打的被叫号码。
        bodys.put("languageType", languageType);//验证码播放的语言类型。
        bodys.put("preTone", preTone);//播放语音验证码之前需要播放的放音文件名
        bodys.put("verifyCode", verifyCode);//验证码：只支持0～9的数字，最大8位。
        String jsonRequest = JsonUtil.jsonObj2Sting(bodys);

        /*
         * Content-Type为application/json且请求方法为post时, 使用doPostJsonGetStatusLine方法构造http
         * request并获取响应.
         */
        StreamClosedHttpResponse responseVoiceVerificationCode = httpsUtil
                .doPostJsonGetStatusLine(urlVoiceVerificationCode, headerMap, jsonRequest);

        // 响应的消息体写入responsebody.
        responsebody = JsonUtil.jsonString2SimpleObj(responseVoiceVerificationCode.getContent(),
                responsebody.getClass());

        // 返回响应的status.
        return responseVoiceVerificationCode.getStatusLine().toString();
    }

    // 获取整个响应消息体
    public Map<String, String> getResponsebody() {
        return this.responsebody;
    }

    // 获取响应消息体中的单个参数
    public String getResponsePara(String paraName) {
        return this.responsebody.get(paraName);
    }
}