package com.fs.hisapi.util;

import com.fs.hisapi.domain.ApiResponse;
import com.google.gson.Gson;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class HttpUtil {
    public static ApiResponse endHisApi(String url , Object o){
        //获取sign
        Map<String, String> map = MapUtil.convertToMap(o);
        String sign = SignUtil.getSign(map);
        // 创建HttpPost对象，设置URL地址
        HttpPost httpPost = new HttpPost(url);
        // 设置Content-Type为application/x-www-form-urlencoded;charset=utf-8
        httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
        // 设置请求参数
        List<NameValuePair> params = new ArrayList<>();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            String value = entry.getValue();
                params.add(new BasicNameValuePair(entry.getKey(), value));
        }
        params.add(new BasicNameValuePair("sign", sign));
        // 将参数编码为URL格式
        String paramString = URLEncodedUtils.format(params, StandardCharsets.UTF_8);
        try {
            httpPost.setEntity(new StringEntity(paramString,"UTF-8"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        String s = HttpUtil.sendHttp(httpPost);
        Gson gson = new Gson();
        return  gson.fromJson(s,ApiResponse.class);
    }
    public static String sendHttp( HttpPost httpPost){
        String responseText=null;
        // 创建HttpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 发送请求，获取响应
        try {
            CloseableHttpResponse response = httpClient.execute(httpPost);
            // 获取响应实体
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                responseText = EntityUtils.toString(entity, "UTF-8");
            }
            // 关闭响应
            response.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭HttpClient
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return responseText;
    }
}
