package com.fjs.scenic.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fjs.scenic.cyt.utils.Base64Util;
import com.fjs.scenic.cyt.utils.EncryptUtil;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
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.HashMap;
import java.util.Map;

public class HttpReq {

    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url   发送请求的 URL
     * @param param 请求参数
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String url, String param) {
        HttpPost httpPost = new HttpPost(url);
        StringEntity stringEntity = new StringEntity(param, "UTF-8");
        httpPost.setEntity(stringEntity);
        String result = null;

        try {
            CloseableHttpClient client = HttpClients.createDefault();
            HttpResponse response = client.execute(httpPost);
            HttpEntity httpEntity = response.getEntity();
            result = EntityUtils.toString(httpEntity);
        } catch (Throwable var8) {
            var8.printStackTrace();
        }

        return result;
    }

    /**
     * @param url    发送请求的 URL
     * @param method 请求的方法
     * @param data   请求的条件
     * @return
     * @throws Exception
     */
    public static JSONObject sendPost(String url, String method, String data) throws Exception {
        //data数据 加密为base64
        String dataByBase64 = Base64Util.getBASE64(data);
        //key+data+方法名大写 MD5加密 传参
        String sign = EncryptUtil.MD5Hex("123456" + dataByBase64 + method.toUpperCase());
        Map<String, String> map = new HashMap<String, String>();
        map.put("sign", sign);
        map.put("method", method);
        map.put("data", dataByBase64);
        Object json = JSONObject.toJSON(map);
        String responseStr = HttpReq.sendPost(url, json.toString());
        //解密
        return JSONArray.parseObject(responseStr);

    }

    /**
     * 获取 数据解密
     *
     * @param parseObject2
     * @return
     * @throws Exception
     */
    public static String getDataStr(JSONObject parseObject2) throws Exception {
        String object = (String) parseObject2.get("data");
        return Base64Util.decodeData(object);
    }
}