package com.ag.util;

import com.alibaba.fastjson.JSON;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.net.URI;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HttpRequestor {

    private static String charset = "utf-8";
    private static Log log = LogFactory.getLog(HttpRequestor.class);
    public static String Content_Type_FORM = "application/x-www-form-urlencoded;charset=utf-8";
    public static String Content_Type_UPLOAD = "multipart/form-data;charset=utf-8";
    public static String Content_Type_JSON = "application/json;charset=utf-8";
    public static String Content_Type_HTML = "text/html;charset=utf-8";
    public static String Content_Type_XML = "text/xml;charset=utf-8";



    /**
     * Do GET request
     */
    public static String doGet(String url) {
        try {
            HttpClient client = createHttpsClient();
            //发送get请求
            HttpGet request = new HttpGet(url);
            HttpResponse response = client.execute(request);
            /**请求发送成功，并得到响应**/
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                /**读取服务器返回过来的json字符串数据**/
                return EntityUtils.toString(response.getEntity());
            }
        }
        catch (Exception e) {
            log.error("请求失败!" + e.getLocalizedMessage());
            e.printStackTrace();
        }
        return null;
    }

    /**
     * post请求(用于key-value格式的参数)
     */
    public static String doPost(String url, Map params){
        String result = "";
        try {
            // 定义HttpClient
            CloseableHttpClient client = createHttpsClient();
            // 实例化HTTP方法
            HttpPost httppost = new HttpPost();
            httppost.setURI(new URI(url));
            //设置参数
            List<NameValuePair> nvps = new ArrayList<>();
            for (Object key : params.keySet()) {
                String name = (String)key;
                String value = String.valueOf(params.get(name));
                nvps.add(new BasicNameValuePair(name, value));
                //System.out.println(name +"-"+value);
            }
            httppost.setEntity(new UrlEncodedFormEntity(nvps, charset));
            HttpResponse response = client.execute(httppost);
            HttpEntity httpEntity2 = response.getEntity();
            // 如果状态码为200,就是正常返回
            int rspCode = response.getStatusLine().getStatusCode();
            if (rspCode == HttpStatus.SC_OK) {
                result = EntityUtils.toString(httpEntity2);
                log.error(httpEntity2);
            } else {
                result = EntityUtils.toString(httpEntity2);
                // 得到返回的字符串
            }
            //关闭连接
            client.close();
        }
        catch(Exception e){
            log.error("执行http请求失败" + e.fillInStackTrace());
            e.printStackTrace();
            throw new RuntimeException("请求接口出错!请求数据["+JSON.toJSONString(params)+"]");
        }
        return result.replaceAll("&quot;", "\"");
    }

    public static String doPost(String url, String requestSoap, String contentType)  {
        BasicHeader[] headers = new BasicHeader[]{new BasicHeader("Content-Type", Content_Type_JSON)};;
        if (!StrUtil.isEmpty(contentType)){
            headers = new BasicHeader[]{new BasicHeader("Content-Type", contentType)};
        }
        return doPost(url, requestSoap, headers);
    }
    /**
     * 请求https的接口
     *
     * @param url         接口地址
     * @param requestSoap 请求报文
     * @return
     * @throws Exception
     */
    private static String doPost(String url, String requestSoap, BasicHeader[] headers)  {

        String result = "";
        try {
            CloseableHttpClient closeableHttpClient = createHttpsClient();
            // 建立HttpPost对象
            //PostMethod postMethod = new PostMethod(url);
            HttpPost httppost = new HttpPost(url);
            byte[] b = requestSoap.getBytes(charset);
            InputStream is = new ByteArrayInputStream(b, 0, b.length);
            HttpEntity httpEntity = new InputStreamEntity(is, b.length);
            httppost.setEntity(httpEntity);
            if (headers != null){
                httppost.setHeaders(headers);
            }
            //httppost.addHeader("Content-Type", Content_Type_JSON);
            //httppost.addHeader("Content-Type", "text/html;charset=utf-8");
//            httppost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");

            //发送Post,并返回一个HttpResponse对象
            HttpResponse httpResponse = closeableHttpClient.execute(httppost);
            HttpEntity httpEntity2 = httpResponse.getEntity();
            // 如果状态码为200,就是正常返回
            int rspCode = httpResponse.getStatusLine().getStatusCode();
            if (rspCode == HttpStatus.SC_OK) {
                result = EntityUtils.toString(httpEntity2);
                log.error(httpEntity2);
            } else {
                result = EntityUtils.toString(httpEntity2);
                // 得到返回的字符串
            }
            //关闭连接
            closeableHttpClient.close();
        } catch (Exception e) {
            log.error("执行http请求失败" + e.fillInStackTrace());
            throw new RuntimeException("请求接口出错!请求数据["+requestSoap+"]");
        }
        return result.replaceAll("&quot;", "\"");
    }

    /**
     * 处理https请求安全证书问题（默认接受所有证书）
     *
     * @return
     * @throws Exception
     */
    public static CloseableHttpClient createHttpsClient() throws Exception {
        X509TrustManager x509mgr = new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] xcs, String string) {
            }
            @Override
            public void checkServerTrusted(X509Certificate[] xcs, String string) {
            }
            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };
// 设置超时时间: 读取超时,连接超时,请求超时时间
        RequestConfig defaultRequestConfig = RequestConfig.custom()
                .setSocketTimeout(60000).setConnectTimeout(3000)
                .setConnectionRequestTimeout(3000)
                .setStaleConnectionCheckEnabled(false).build();
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, new TrustManager[]{x509mgr},
                new java.security.SecureRandom());
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                sslContext,
                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        return HttpClients.custom().setSSLSocketFactory(sslsf)
                .setDefaultRequestConfig(defaultRequestConfig).build();
    }


    public static void main(String[] args) throws Exception {
        /*String url = "http://localhost:8088/m?xwl=WeixinSelect/planOrderSelect";
        Map<String, Object> map = new HashMap<>();
        map.put("ORDER_NO", "0");
        map.put("ck", "MZ");
        HttpRequestor requestor = new HttpRequestor();
        String str = requestor.doPost(url, map);*/

        /*String url = "http://wx.46202.yq-ic.com/Api/JT.ashx?action=DJK-001";
        Map<String, String> map = new HashMap<>();
        map.put("username", "JT20190531");
        map.put("timestamp", String.valueOf(System.currentTimeMillis()));

        String key = "vVrepYXntsovfebDMnOOL1OzPZHRYxtj";
        String token = MD5Util.getMD5(key + map.get("timestamp"));
        map.put("token", token);
        map.put("billNo", "DWHPW1906244");
        //map.put("cntr", "AAMU2502495");
        String sendStr = JSON.toJSONString(map);
        System.out.println(sendStr);
        String str = HttpRequestor.doPost(url, JSON.toJSONString(map));

        System.out.println(str);*/

//        String url = "http://192.168.1.215:8762/DemoController/home";
        String url = "http://192.168.1.215:8765/fa";
        Map<String, Object> map = new HashMap<>();
        map.put("bean", "service-hi");
        map.put("method", "/DemoController/save");
        map.put("sys.username", "yxh");
        //String str = HttpRequestor.doPost(url, map);
        //String json="{\"sys.dispname\":\"管理员\",\"sys.userIpAddress\":\"127.0.0.1\",\"sys.date\":1686813321877,\"sys.theme\":\"classic\",\"data\":\"[{\\\"S_ID\\\":\\\"00ee893e3f244cd1bd0ac4a2d43e6303\\\",\\\"NAME\\\":\\\"test11\\\",\\\"%SEX\\\":\\\"女\\\",\\\"SEX\\\":\\\"2\\\",\\\"AGE\\\":\\\"33\\\",\\\"GRADE_COD\\\":\\\"\\\",\\\"CREATED_BY\\\":\\\"22\\\",\\\"CREATED_ON\\\":\\\"2023-02-24T16:00:00.000Z\\\",\\\"UPDATED_BY\\\":\\\"admin\\\",\\\"UPDATED_ON\\\":\\\"2023-02-24T16:00:00.000Z\\\",\\\"#NAME\\\":\\\"test11\\\",\\\"#SEX\\\":\\\"2\\\",\\\"#AGE\\\":33,\\\"#CREATED_BY\\\":\\\"22\\\",\\\"#CREATED_ON\\\":\\\"2023-02-24T16:00:00.000Z\\\",\\\"#UPDATED_BY\\\":\\\"admin\\\",\\\"#UPDATED_ON\\\":\\\"2023-02-25T02:57:29.000Z\\\"}]\",\"basicsLust\":\"\",\"sys.id\":\"004M395CHDLM7\",\"selectUseRole\":{null:\"222\",\"admin/rolemanage.xwl\":\"角色管理\",\"log/operLog.xwl\":\"数据修改日志\",\"admin/dept.xwl\":\"部门管理\",\"common/S_Code/S_PARM1.xwl\":\"系统参数\",\"baseCode/C_Client.xwl\":\"客户管理\",\"sys/msg/topicEdit.xwl\":\"消息订阅\",\"log/sysOperLog.xwl\":\"系统操作日志\",\"sys/msg/websocketModel/personMsg.xwl\":\"我的消息\",\"admin/wbTenancy.xwl\":\"租户管理\",\"feeManage/tariffFee.xwl\":\"合同费率\",\"feeManage/points.xwl\":\"计费事件\",\"common/S_Code/S_Code.xwl\":\"系统代码维护\",\"feeManage/baseDict.xwl\":\"计费元素维护\",\"examples/tabulator/bigdata-table-tabulator.xwl\":\"大数据表格\",\"admin/perm.xwl\":\"权限设置\",\"common/codeSet.xwl\":\"系统下拉代码维护\",\"admin/wbMenu.xwl\":\"菜单维护2\",\"feeManage/item.xwl\":\"费目模板\",\"log/sysExceptionLog.xwl\":\"系统异常日志\",\"examples/basic/dropUpload.xwl\":\"测试\",\"examples/tabulator/group-table-tabulator.xwl\":\"分组表格示例tabulator\",\"feeManage/cate.xwl\":\"费类维护\",\"admin/user.xwl\":\"测试功能\",\"log/userDefineLog.xwl\":\"用户自定义日志\",\"examples/tabulator/simple-table-tabulator.xwl\":\"简单表格示例tabulator\"},\"xwl\":\"common/save-all\",\"sys.roles\":[\"default\",\"administrator\",\"shao\",\"fee\",\"admin\"],\"sys.username\":\"admin\",\"sys.tenancyId\":\"default\",\"mapMenuRes\":{\"admin\":[{\"ename\":\"itemTest\",\"url\":\"common/codeSet.xwl\",\"enabled\":\"0\"},{\"ename\":\"itemTest\",\"url\":\"common/S_Code/S_PARM1.xwl\",\"enabled\":\"0\"},{\"ename\":\"saveBtn\",\"url\":\"feeManage/baseDict.xwl\",\"enabled\":\"1\"},{\"ename\":\"itemTest1\",\"url\":\"common/codeSet.xwl\",\"enabled\":\"1\"},{\"ename\":\"panelTitle\",\"url\":\"common/codeSet.xwl\",\"enabled\":\"1\"}]},\"debugSuffix\":\"-debug\",\"sys.editTheme\":\"default\",\"bean\":\"service-hi\",\"sys.lang\":\"auto\",\"sys.TENANCY_ID\":\"default\",\"sys.userid\":\"admin\",\"subsList\":\"<li><img src=\\\"wb/images/photos/user.png\\\" style=\\\"margin-bottom:3px\\\"/><a onclick=\\\"subsclick('004CH3D8MP8Z4','admin')\\\">市场管理</a></li><li><img src=\\\"wb/images/photos/order.png\\\" style=\\\"margin-bottom:3px\\\"/><a onclick=\\\"subsclick('004CH3D8MOL2G','admin')\\\">客户管理</a></li><li><img src=\\\"wb/images/photos/settle.png\\\" style=\\\"margin-bottom:3px\\\"/><a onclick=\\\"subsclick('004CH3D8MP90F','admin')\\\">代码管理</a></li><li><img src=\\\"wb/images/photos/user.png\\\" style=\\\"margin-bottom:3px\\\"/><a onclick=\\\"subsclick('55cede9c-20b7-4728-9072-c03b6a4cd965','admin')\\\">系统管理</a></li><li><img src=\\\"wb/images/photos/order.png\\\" style=\\\"margin-bottom:3px\\\"/><a onclick=\\\"subsclick('004KC3HC0NO37','admin')\\\">框架示例</a></li>\",\"method\":\"/DemoController/home\",\"sys.useLang\":\"zh_CN\",\"sys.menuid\":\"004CH3D8MP8Z4\",\"sys.logined\":true,\"useRole\":{\"admin\":\"admin\"},\"roleIds\":\",administrator,shao,fee,admin,\",\"sys.ip\":\"127.0.0.1\",\"sys.user\":\"admin\",\"menuid\":\"-1\",\"sys.dataPermSql\":\"select USER_NAME from wb_user where DEPT_ID in(select DATA_DEPT_ID from wb_dept_perm where DEPT_ID in (select DEPT_ID from wb_user wu where USER_NAME ='admin'))\",\"sys.roleList\":\"default,administrator,shao,fee,admin\"}";
        String str = HttpRequestor.doPost(url, JSON.toJSONString(map), Content_Type_JSON);
        System.out.println(str);



    }

}
