package com.kingdee.eas.custom.erp.util;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import com.alibaba.fastjson.JSONObject;
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.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.HttpStatus;

import java.io.OutputStream;


public class HttpsReqUtil {

    private static Logger log = LoggerFactory.getLogger(HttpsReqUtil.class);
    
    private static CloseableHttpClient httpClient;

    public static String postByHttps(String sendUrl, String param) throws Exception {

        URL url = new URL(sendUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);

        // 设置请求头，如Content-Type
        conn.setRequestProperty("Content-Type", "application/json");

        // 发送请求参数
        //String postParams = "{\"appId\":\"gtiit_sq\",\"appSecret\":\"Kingdee@2024Kingdee@2024\",\"tenantid\":\"ierp-client\",\"accountId\":\"1917417602120941568\"}";
        byte[] outputInBytes = param.getBytes("UTF-8");
        OutputStream os = conn.getOutputStream();
        os.write(outputInBytes);
        os.close();

        // 获取响应码
        int responseCode = conn.getResponseCode();
        log.info("postByHttps.POST Response Code :: " + responseCode);

        if (responseCode == HttpURLConnection.HTTP_OK) {
            // 处理响应
            log.info("POST request succeeded");
        } else {
            log.info("POST request failed");
        }
        StringBuilder response = new StringBuilder();
        // 接收响应内容
        if (responseCode == HttpURLConnection.HTTP_OK) {
            BufferedReader in = new BufferedReader(new InputStreamReader(
                    conn.getInputStream()));
            String inputLine;


            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            // 打印结果
            log.info("postByHttps.POST Response:" + response.toString());
        } else {
            log.info("POST NOT Worked");
        }
        // 关闭连接
        conn.disconnect();

        return response.toString();
    }


    public static String getByHttps(String httpUrl, String requestMethod) {
        StringBuilder response = new StringBuilder();
        try {
            URL url = new URL(httpUrl);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();

            // 设置请求方法
            con.setRequestMethod("GET");

            // 发送请求并获取响应码
            int responseCode = con.getResponseCode();

            // 检查响应码是否为200
            if (responseCode == HttpURLConnection.HTTP_OK) {
                // 获取输入流
                BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
                String inputLine;

                // 读取响应数据，直到没有更多数据
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();
            } else {
                // 响应码不是200，打印错误信息
                System.out.println("GET request not worked");
            }

            // 关闭连接
            con.disconnect();

        } catch (Exception e) {
            log.error("getByHttps.e:" + e.getMessage());
        }

        // 返回响应字符串
        return response.toString();
    }

    
    
    
    /**
     * 数据保存接口
     * @param sendUrl
     * @param param
     * @param accessToken
     * @return
     * @throws Exception 
     */
    public static String postByHttps(String sendUrl, String param,String accessToken) throws Exception {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(sendUrl);
        String responseMsg = null;
        log.info("postByHttps.sendUrl:" + sendUrl);
        log.info("postByHttps.param:" + param);
        log.info("postByHttps.accessToken:" + accessToken);
        try {
            StringEntity re = new StringEntity(param, "utf-8");
            re.setContentType("application/json");
            httppost.setHeader("accessToken", accessToken);
            httppost.setEntity(re);
            HttpResponse response = httpClient.execute(httppost);
            HttpEntity entity = response.getEntity();
            responseMsg = EntityUtils.toString(entity, "utf-8");
            
            log.info("postByHttps.responseMsg:" + responseMsg);
        } catch (Exception e) {
        	throw new Exception("请求星瀚接口抛异常："+e.getMessage());
        } finally {
            httpClient.getConnectionManager().shutdown();
        }
        return responseMsg;
    }
    
    
    
    
    

    public static String doPost(String url, JSONObject json) {

        try {
            httpClient = HttpClients.createDefault();
            HttpPost post = new HttpPost(url);

            post.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");

            StringEntity s = new StringEntity(json.toString(), "UTF-8");
            s.setContentType("application/json");
            //设置请求参数
            post.setEntity(s);
            HttpResponse response = httpClient.execute(post);
            response.setHeader("Content-type", "text/html;charset=UTF-8");
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                //返回json格式
                String res = EntityUtils.toString(response.getEntity(), "utf-8");
                return res;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (httpClient != null) {
                try {
                    httpClient.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }


}
