package tech.glinfo.enbao.common.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.SimpleTimeZone;
import java.util.UUID;

@Component
public class AliyunChatbotUtils {

    protected Logger logger = LoggerFactory.getLogger(getClass());

    @Value("${aliyunspeed.accessKeyId}")
    private String accessKeyId;

    @Value("${aliyunspeed.accessKeySecret}")
    private String accessKeySecret;


    public String chatbot(String text) {
        Map<String, String> map = Maps.newHashMap();
        map.put("Action", "Chat");
        map.put("InstanceId", "chatbot-cn-nrqMIZfqqa");
        map.put("Utterance", text);
        String url = null;
        try {
            url = getQueryUrl(map);
        } catch (Exception e) {
            logger.error("转换URL出错了:", e);
        }
//        System.err.println(url);
        if(url != null) {
            String result = HttpUtil.doGet(url);
            logger.info("机器对话返回：{}", result);
            if(result != null) {
                JSONObject json = JSONObject.parseObject(result);
                if (json.containsKey("Messages")) {
                    JSONArray messages = json.getJSONArray("Messages");
                    JSONObject object = messages.getJSONObject(0);
                    if(object.containsKey("Text")) {
                        return object.getJSONObject("Text").getString("Content");
                    }
                }
            }
        }
        return null;
    }

    private String getQueryUrl(Map<String, String> param) throws Exception {
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
        simpleDateFormat.setTimeZone(new SimpleTimeZone(0, "GMT"));
        String timestamp = simpleDateFormat.format(date);
        Map<String, String> publicParam = Maps.newHashMap();
        publicParam.put("AccessKeyId", accessKeyId);
        publicParam.put("Format", "json");
        publicParam.put("SignatureMethod", "HMAC-SHA1");
        publicParam.put("SignatureNonce", UUID.randomUUID().toString());
        publicParam.put("SignatureVersion", "1.0");
        publicParam.put("Timestamp", timestamp);
        publicParam.put("Version", "2017-10-11");

        if (param != null) {
            for (Map.Entry<String, String> entry : param.entrySet()) {
                publicParam.put(entry.getKey(), entry.getValue());
            }
        }

        String s = SignatureUtils.generateSignString("GET", publicParam);
        byte[] signBytes;
        signBytes = SignatureUtils.hmacSHA1Signature(accessKeySecret + "&", s);
        String signature = SignatureUtils.newStringByBase64(signBytes);

        publicParam.put("Signature", signature);

        String url = "http://chatbot.cn-shanghai.aliyuncs.com/?";
        //对参数进行url编码
        for (Map.Entry<String, String> entry : publicParam.entrySet()) {
            publicParam.put(entry.getKey(), URLEncoder.encode(entry.getValue().toString(), "UTF-8"));
        }
        //拼接请求url
        for (Map.Entry<String, String> entry : publicParam.entrySet()) {
            url = url + entry + "&";
        }
        //去掉最后一个&
        url = url.substring(0, url.length() - 1);
        return url;
    }


    public String doGet(String httpurl) {
        OkHttpClient client  = new OkHttpClient();
        // 2 request 默认是get请求
        Request request = new  Request.Builder().url(httpurl).build();
        // 3 进行请求操作
        String result = null;
        try {
            Response response = client.newCall(request).execute();
            // 4 判断是否请求成功
            if(response.isSuccessful()){
                // 得到响应体中的身体,将其转成  string
                result = response.body().string();
//                System.out.println(result);
            } else {
                logger.info("接口调用不成功：{}", response.toString());
            }

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return result;
    }

}
