package com.jsowell.thirdparty.lianlian.util;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson2.JSON;
import com.google.common.collect.Maps;
import com.jsowell.common.util.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
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.HttpClients;
import org.apache.http.util.EntityUtils;

import java.util.Date;
import java.util.Map;

/**
 * @author 联联充电
 */
@Slf4j
@SuppressWarnings(value = "unused")
public class HttpRequestUtil {


    /**
     * httpClient--post请求--http
     *
     * @param url
     * @param json
     * @return
     */
    public static String httpPost(String url, String json, String token) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        try {
            //创建httpPost
            HttpPost httpPost = new HttpPost(url);

            //设置Content-Type
            httpPost.setHeader("Content-Type", "application/json");
            httpPost.setHeader("Authorization", token);

            //写入json数据
            httpPost.setEntity(new StringEntity(json));

            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectTimeout(50000)
                    .setConnectionRequestTimeout(50000)
                    .setSocketTimeout(50000)
                    .build();
            httpPost.setConfig(requestConfig);

            //发起请求，获取response对象
            response = httpClient.execute(httpPost);

            //获取结果状态码
            int resultCode = response.getStatusLine().getStatusCode();
            if (resultCode == 200) {
                //获取返回数据实体对象
                HttpEntity entity = response.getEntity();

                //转化为字符串
                String result = EntityUtils.toString(entity, "UTF-8");
                //封装统一的返回数据接收类
                //ResponseMsg responseMsg = (ResponseMsg) JSON.parse(result);
                return result;
            } else {
                log.info("http请求失败");
            }
        } catch (Exception e) {
            log.info("http请求异常");
        } finally {
            try {
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (Exception e) {
                log.info(e.getMessage(), e);
            }
        }

        return null;
    }

    /**
     * 联联平台发送请求
     *
     * @param token 联联平台令牌
     * @param data 要传输的JsonString格式数据
     * @param url 请求地址
     * @param dataSecret 消息密钥
     * @param dataSecretIV 消息密钥初始化向量
     * @param operatorId 运营商id
     * @param sigSecret 签名密钥
     * @return
     */
    public static String sendPost(String token, String data, String url, String dataSecret,
                                  String dataSecretIV, String operatorId, String sigSecret){
        //加密
        byte[] encryptText = Cryptos.aesEncrypt(data.getBytes(),
                dataSecret.getBytes(), dataSecretIV.getBytes());
        String encryptData = Encodes.encodeBase64(encryptText);
        System.out.println("加密数据:" + encryptData);

        Map<String, String> params = Maps.newLinkedHashMap();
        params.put("OperatorID", operatorId);
        params.put("Data", encryptData);
        params.put("TimeStamp", DateUtils.parseDateToStr(DateUtils.YYYYMMDDHHMMSS, new Date()));
        params.put("Seq", "001");
        String sign = GBSignUtils.sign(params, sigSecret);
        params.put("Sig", sign);

        String postData = JSON.toJSONString(params);
        log.info("最终提交数据:{}", postData);
        // System.out.println("最终提交数据:" + postData);

        String hutoolRequest = HttpRequest.post(url).header("Authorization", "Bearer " + token).body(postData).execute().body();

        log.info("接收到返回数据:{}", hutoolRequest);
        // System.out.println("接收到返回数据：" + hutoolRequest);

        Map<String, String> map = (Map<String, String>) JSON.parse(hutoolRequest);

        log.info("返回数据map:{}", JSON.toJSONString(map));
        String rData = map.get("Data");
        String resultMsg = map.get("Msg");

        byte[] plainText = Cryptos.aesDecrypt(Encodes.decodeBase64(rData),
                dataSecret.getBytes(), dataSecretIV.getBytes());
        String plainData = "";
        try {
            plainData = new String(plainText, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }

        log.info("解密数据:{}", plainData);
        // System.out.println("解密数据：" + plainData);
        return resultMsg;
    }
}
