package com.weiqi.mis;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.io.IOUtils;
import org.apache.http.*;
import org.apache.http.HttpResponse;
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.ConnectTimeoutException;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;


public class HttpUtil {

    private static final Logger logger = LoggerFactory.getLogger(HttpUtil.class);

    private static CloseableHttpClient httpClient;
    private static PoolingHttpClientConnectionManager cm;

    static {
        init();
        closeExpiredConnectionsPeriodTask(60);
    }

    static void init() {
        cm = new PoolingHttpClientConnectionManager();
        // max connections
        cm.setMaxTotal(300);
        // max connections per route
        cm.setDefaultMaxPerRoute(60);
        // set max connections for a specified route
        cm.setMaxPerRoute(new HttpRoute(new HttpHost("locahost")), 100);
        cm.setValidateAfterInactivity(500);

        final RequestConfig requestConfig = RequestConfig.custom()
                // the socket timeout (SO_TIMEOUT) in milliseconds
                .setSocketTimeout(15000)
                // the timeout in milliseconds until a connection is established.
                .setConnectTimeout(15000)
                // the timeout in milliseconds used when requesting a connection from the connection pool.
                .setConnectionRequestTimeout(15000)
                .build();
        httpClient = HttpClients.custom().setConnectionManager(cm).setDefaultRequestConfig(requestConfig).build();
    }

    public static String sendGetRequest(String url, Map<String, String> paramMap) {
        return sendGetRequestSetEncoding(url, paramMap, "UTF-8");
    }

    public static String sendGetRequest(String url){
        HttpGet httpGet = new HttpGet(url);
        httpGet.setHeader("User-Agent", "");
 //       httpGet.setHeader("Cookie", "Token=49FCFB0599EC33D5F89141535CF90849");
        //httpGet.setHeader();
        HttpResponse response;
        String startTime =  null;
        try {
            startTime = DateUtils.getCurrDateTimeStr();
            response = httpClient.execute(httpGet);
            return parseResponse(url, response, "UTF-8");
        }catch (ConnectTimeoutException e){
            logger.error("request url:" + url + "startTime:" + startTime + ",ConnectTimeout", e);
            return null;
        }catch (SocketTimeoutException e){
            logger.error("request url:" + url + "startTime:" + startTime + ",SocketTimeout", e);
            return null;
        }catch (Exception e) {
            logger.error("request url:" + url + ",error", e);
            return null;
        }

    }

    public static String sendGetRequestSetEncoding(String url, Map<String, String> paramMap, String encoding) {
        StringBuilder urlBuffer = new StringBuilder(url);
        if (url.indexOf("?") < 0) {
            urlBuffer.append("?");
        }
        if (paramMap != null && !paramMap.isEmpty()) {
            Iterator<String> iterator = paramMap.keySet().iterator();
            while (iterator.hasNext()) {
                String paramName = iterator.next();
                if (urlBuffer.toString().endsWith("?")) {
                    urlBuffer.append(paramName).append("=").append(paramMap.get(paramName).toString());
                } else {
                    urlBuffer.append("&").append(paramName).append("=").append(paramMap.get(paramName).toString());
                }
            }
        }
        String requestUrl = urlBuffer.toString();
        HttpGet httpGet = new HttpGet(requestUrl);
        httpGet.setHeader("User-Agent", "");
        HttpResponse response;
        String startTime =  null;
        try {
            startTime = DateUtils.getCurrDateTimeStr();
            response = httpClient.execute(httpGet);
            return parseResponse(requestUrl, response, encoding);
        }catch (ConnectTimeoutException e){
            logger.error("request url:" + requestUrl + "startTime:" + startTime + ",ConnectTimeout", e);
            return null;
        }catch (SocketTimeoutException e){
            logger.error("request url:" + requestUrl + "startTime:" + startTime + ",SocketTimeout", e);
            return null;
        }catch (Exception e) {
            logger.error("request url:" + requestUrl + ",error", e);
            return null;
        }
    }

    /**
     * post方式请求
     *
     * @param url
     * @param paramMap
     * @return
     */

    public static String sendPostRequest(String url, Map<String, String> paramMap,String host) {
        return sendPostRequest(url, paramMap, "UTF-8",host);
    }


    public static String sendPostRequestByJson(String url, Map<String, String> paramMap) {
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
//        httpPost.setHeader("Host", "ngmgapi.in.weiqi.com.cn");
        StringEntity se = null;
        try {
            se = new StringEntity(JSON.toJSONString(paramMap), "UTF-8");
            se.setContentType("application/json;charset=UTF-8");

        } catch (Exception e) {
            e.printStackTrace();
        }
        httpPost.setEntity(se);
        HttpResponse response = null;
        try {
            response = httpClient.execute(httpPost);
        } catch (Exception e) {
            logger.error("request url:" + url + ",error", e);
            throw new RuntimeException(e);
        }
        return parseResponse(url, response, "UTF-8");
    }


    public static String sendPostRequestByJson(String url, String param) {
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
        httpPost.setHeader("Host", "ngmgapi.in.weiqi.com.cn");
        StringEntity se = null;
        try {
            se = new StringEntity(param, "UTF-8");
            se.setContentType("application/json;charset=UTF-8");
//            System.out.println("------" + JSON.toJSONString(paramMap));

        } catch (Exception e) {
            e.printStackTrace();
        }
        httpPost.setEntity(se);
        HttpResponse response = null;
        try {
            response = httpClient.execute(httpPost);
        } catch (Exception e) {
            logger.error("request url:" + url + ",error", e);
            throw new RuntimeException(e);
        }
        return parseResponse(url, response, "UTF-8");
    }


    public static String sendPostRequestByJsonObject(String url, Map<String, Object> paramMap) {
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
        StringEntity se = null;
        try {
            se = new StringEntity(JSON.toJSONString(paramMap), "UTF-8");
            se.setContentType("application/json;charset=UTF-8");

        } catch (Exception e) {
            e.printStackTrace();
        }
        httpPost.setEntity(se);
        HttpResponse response = null;
        try {
            response = httpClient.execute(httpPost);
        } catch (Exception e) {
            logger.error("request url:" + url + ",error", e);
            throw new RuntimeException(e);
        }
        return parseResponse(url, response, "UTF-8");
    }

    public static String sendPostRequestByJsonObject2(String url, Map<String, Object> paramMap) {
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Accept","text/plain");
        httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
        StringEntity se = null;
        try {
            se = new StringEntity(JSON.toJSONString(paramMap), "UTF-8");
            se.setContentType("application/json;charset=UTF-8");

        } catch (Exception e) {
            e.printStackTrace();
        }
        httpPost.setEntity(se);
        HttpResponse response = null;
        try {
            response = httpClient.execute(httpPost);
        } catch (Exception e) {
            logger.error("request url:" + url + ",error", e);
            throw new RuntimeException(e);
        }
        return parseResponse(url, response, "UTF-8");
    }




    /**
     * post方式请求
     *
     * @param url
     * @param paramMap
     * @return
     */

    public static String sendPostRequest(String url, Map<String, String> paramMap, String enc,String host) {
        HttpPost httpPost = new HttpPost(url);

        if(host!=null&&host.length()>1){
            httpPost.setHeader("Host", host);
        }

//        httpPost.setHeader("pcpopclub", "551521767E62D76CB2A5CE5BACC7772E5BC73D0B47947C7B1F84A434A0A74FA89754DD632F25BCD867D9AD6BD27DCDE2E5AA36A609F398CC5948C80AB4957C30AD32453CA0BBFB1B97DCB5D54D118997D734E111D8A0B1B38AB7B6CB55DADD4FD3A9C3C7649F940238A4D1A023E4D174254BAD9DD9E3DE3FA46F6C4AAF84D2A96E6956FB750D91B6AB2B84478EC883A8EC02DE35D320DB91CA0EBA9B25E6C604C338845EB4540B22E88CCB5A44051AE17237B39BF3966E999FA0FF0B92112273771ABDE0AF84D11B4C03869FC0E803743AB680D17F2C6EF17EA73EEC11F46C9E1D66B6A8AE52FDEE8E81F7138277BC8700F341A7610A19667A5F855C6CF02EB62FB1FA76BC94C5D3EFDDEC58EBBFA62C5669C9BD5AB4BEEF069C6E47251733576F5C3DC82484A61CE1356E1269EDB0FED256A3AC1E1FFE12B43BDD0F".toUpperCase());
        if (paramMap != null && !paramMap.isEmpty()) {
            Iterator<String> iterator = paramMap.keySet().iterator();
            List<BasicNameValuePair> params = new ArrayList<>(paramMap.size());
            while (iterator.hasNext()) {
                String paramName = iterator.next();
                params.add(new BasicNameValuePair(paramName, paramMap.get(paramName).toString()));
            }
            try {
                httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
            } catch (Exception e) {
                logger.error("can not request url:" + url, e);
                throw new RuntimeException(e);
            }
        }
        HttpResponse response = null;
        try {
            response = httpClient.execute(httpPost);
        } catch (Exception e) {
            logger.error("request url:" + url + ",error", e);
            throw new RuntimeException(e);
        }
        return parseResponse(url, response, enc);
    }

    /**
     * 解析返回结果
     *
     * @param url
     * @param response
     * @return
     */

    private static String parseResponse(String url, HttpResponse response, String encoding) {
        if (response == null) {
            logger.error("can not parse httpResponse,beacuse is null,url:" + url);
            return null;
        }
        InputStream inputStream = null;
        try {
            StatusLine status = response.getStatusLine();
            HttpEntity entity = response.getEntity();
            inputStream = entity.getContent();
            if (status.getStatusCode() != 200) {
                throw new RuntimeException("request url:" + url + ", status error, status is " + status.getStatusCode());
            }
            return IOUtils.toString(inputStream, encoding);
        } catch (Exception e) {
            logger.error("parse response error", e);
            throw new RuntimeException("parse response error", e);
        } finally {
            IOUtils.closeQuietly(inputStream);
        }
    }


    private static void closeExpiredConnectionsPeriodTask(int timeUnitBySecond) {
        Executors.newSingleThreadExecutor().execute(new Runnable() {
            @Override
            public void run() {
                while (!Thread.currentThread().isInterrupted()) {
                    try {
                        TimeUnit.SECONDS.sleep(timeUnitBySecond);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    cm.closeExpiredConnections();
                }
            }
        });
    }

    public static String multipartFormPost(String url, MultipartEntityBuilder builder) {
        try {
            String result = "";
            HttpPost httppost = new HttpPost(url);
            httppost.setEntity(builder.build());
            HttpResponse response = httpClient.execute(httppost);
            if (response.getStatusLine().getStatusCode() == 200) {
                result = EntityUtils.toString(response.getEntity());
            }
            return result;
        } catch (Exception e) {
            logger.error("parse multipartFormPost error", e);
            throw new RuntimeException("parse multipartFormPost error", e);

        }
    }

    /**post请求 raw 类型
     *
     * @param uri
     * @param content
     * @return
     */
    public static String postBodyRaw(String uri, String content)  {

        String result = null;
        try{
            HttpPost httpPost = new HttpPost(uri);
            StringEntity requestEntity = new StringEntity(content, "UTF-8");
            requestEntity.setContentType("application/json");
            httpPost.setEntity(requestEntity);
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            result = EntityUtils.toString(entity, "UTF-8");

        }catch (Exception e){
            logger.error("uri={},content={},异常={}",uri,content,e);
        }

        return result;
    }

    /**
     *
     * @param url 提交地址
     * @param charset 编码
     * @param params 提交参数
     * @return
     */
    public static String postHttpText(String url, String charset,String params) {

        URL myFileUrl = null;
        BufferedReader in = null;
        HttpURLConnection conn =null;
        OutputStreamWriter out=null;
        String result="";

        try {

            if(charset==null || "".equals(charset)){
                charset = "UTF-8";
            }

            myFileUrl = new URL(url);
            conn = (HttpURLConnection) myFileUrl.openConnection();
            conn.setRequestMethod("POST");//
            conn.setConnectTimeout(20*1000);
            conn.setReadTimeout(20*1000);
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.connect();
            out = new OutputStreamWriter(conn.getOutputStream(), charset); // utf-8编码
            out.append(params);
            out.flush();
            out.close();
            out=null;

            if (conn.getResponseCode() == 200) {
                in = new BufferedReader(
                        new InputStreamReader(conn.getInputStream(),charset));
                String line="";
                while ((line=in.readLine())!=null){
                    result+=line;
                }
                in.close();
                in=null;

                conn.disconnect();
                conn=null;
            } else {

            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if(null!=out){
                    out.close();
                    out=null;
                }
            } catch (IOException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            }
            try {
                if(null!=in){
                    in.close();
                    in=null;
                }
            } catch (IOException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            }
            if(null!=conn){
                conn.disconnect();
                conn=null;
            }
        }
        return result;
    }


    public static void main(String[] args) {
//        Map<String, String> map = new HashMap();
//        map.put("_appid", "jiage");
//        map.put("type", "2");
//        map.put("userid", "123");
//        map.put("info", "123");
//        System.out.println(HttpUtil.sendPostRequestByJson("http://dealercloudinnerapi.lq.weiqi.com.cn/api/ugc/sharepricecallback?_appid=jiage", map));
//
//        SavePriceVo savePriceVo = new SavePriceVo();
//        savePriceVo.setFeelContent("1");
//        savePriceVo.setweiqiua("iPhone\t11.0.0\tdealercloudapp\t2.0.0\tiPhone");
//        savePriceVo.setCityId(110100 + "");
//        savePriceVo.setUseTax(new BigDecimal(300));
//        savePriceVo.setPurchaseTax(new BigDecimal(8000));
//        savePriceVo.setInsurer(new BigDecimal(3000));
//        savePriceVo.set_appid("dealercloud.ios");
//        savePriceVo.setNakedPrice(new BigDecimal(100000));
//        savePriceVo.setLicenseFee(new BigDecimal(2000));
//
//        savePriceVo.setSeriesId(526 + "");
//        savePriceVo.setSpecId(24194 + "");
//        savePriceVo.setProvinceId(110000 + "");
//        savePriceVo.setPriceType(0);
//        savePriceVo.setInvoiceUrl("WER");
//        savePriceVo.setBrandId(3 + "");
//        savePriceVo.setUc_ticket("e58dd17110914d16ad574b38a1ed060a000f54eb");
//        savePriceVo.setBuycartime("2024-12-01");
//        savePriceVo.setTrafficInsurance(new BigDecimal(0.0));
//        savePriceVo.setFeellevel(2 + "");
//        savePriceVo.setDealerId(1111 + "");
//        Map m = new HashMap();
//        m.put("feelContent", "1");
//        m.put("weiqiua", "iPhone\t11.0.0\tdealercloudapp\t2.0.0\tiPhone");
//        m.put("cityId", "110100");
//        m.put("useTax", "300");
//        m.put("purchaseTax", "8000");
//        m.put("insurer", "3000");
//        m.put("_appid", "dealercloud.ios");
//        m.put("nakedPrice", "100000");
//        m.put("licenseFee", "2000");
//        m.put("SeriesId", "526");
//        m.put("SpecId", "24194");
//        m.put("provinceId", "110000");
//        m.put("invoiceUrl", "WER");
//        m.put("brandId", "3");
//        m.put("SeriesId", "526");
//        m.put("uc_ticket", "0AAB882A705D0507E90C10E41165878B53E75B2545201EB474022E0EA48B5CE2F410A34F816F06974D895F88159FE5057DC412FA83FD21CD2F2E584321A4074D21B907E1C9A6E2E4011F8CC86FF292692B2B03D53A68FFDC5AE7E5E152A5B349BB224635011C033E3EA307F1D3ACF2ED9F67862515D196DEEC1BC394CBDB57501A1A8BCD8D2445647AE6CB3316F803B8C75FBFEAAAA98B554614653DBB7FE8A50065E53E11F9E9F6094285B88137DB2512157578A28636C75AC4956792ECB0CBCA95DBA6458FD751ABD9277500B96A7AEF82434F7F4CAB851D1DE59B37ABF661AEFA16EDF94BBE07D762070285C2E2FD840047D48F149D5BAD2B5BACCC29F2C2CF9985397ACF6A55DA64FC7AFDFD94D543290D91052D5FB9101325DCF375923D075110781DC7023061C271AEF347FEAADFC4D478");
//        m.put("buycartime", "2024-12-01");
//        m.put("trafficInsurance", "0");
//        m.put("feellevel", "2");
//        m.put("dealerId", "111");
//        System.out.println(HttpUtil.sendPostRequest("http://jiage.api.weiqi.com.cn/api/carprice/SavePrice", m));

        JSONObject js = new JSONObject();
        js.put("dt","2019-01-01");
        js.put("category_type","浏览用户" );
        js.put("page","1");
        js.put("pageSize","10");

//        HttpClient httpClient = new DefaultHttpClient();
//        HttpPost post = new HttpPost("http://api.bdp.weiqi.com.cn/datacenter/common/output/ol/interactive_carowner_price_consult?APPKEY=008B97BF6F5F4A6A2C3058127FBA96A0");
//        StringEntity postingString = new StringEntity(js.toString());// json传递
//        post.setEntity(postingString);
//        post.addHeader("Content-type","application/json; charset=utf-8");
//
//        HttpResponse response = httpClient.execute(post);
//        String content = EntityUtils.toString(response.getEntity());
//        System.out.println(content);

//    String ret =  postBodyRaw("http://api.bdp.weiqi.com.cn/datacenter/common/output/ol/interactive_carowner_price_consult?APPKEY=008B97BF6F5F4A6A2C3058127FBA96A0",js.toString());
//        System.out.println(ret);



//        String str = "{\"data\":{\"cms_series_ids\":3170,\"jump_url\":\"http://jiage.m.weiqi.com.cn/mobile/pricenew?priceid=540f9026-cc80-4f51-917f-034147c0c83f\",\"recommend_time\":\"2019-03-21 15:46:45\",\"img_url\":\"https://car3.autoimg.cn/cardfs/product/g26/M05/8F/7E/weiqicar__ChcCP1wE9RCAMsnDAAamtqJFuJg855.jpg\",\"city\":\"北京\",\"publish_time\":\"2019-02-22 00:00:00\",\"modify_time\":\"\",\"img_url2\":\"\",\"cms_spec_ids\":36623,\"title\":\"加价8.19万 当前热门奥迪A3 2019款 Sportback 35 TFSI 时尚型 国V真实车主价是多少\",\"view_count\":\"\",\"city_id\":110100},\"object_class_id\":\"0027\",\"biz_type\":60200,\"object_line_id\":0018,\"biz_id\":1953664,\"push_time\":\"2019-03-21 15:47:02\",\"operation\":0}";

        String str = "{\n" +
                "\"scheme_url\":\"weiqi://insidebrowserwk?url=https://fs.weiqi.com.cn/spa/activity_calendar\",\n" +
                "\"extra_kwargs\":{\"plan_id\":355,\"bizCode\":\"duanxin001\"},\n" +
                "\"html_url\":\"https://fs.weiqi.com.cn/views/shorturl_comm_launch/index.html\",\n" +
                "\"_appid\":\"sms\"}";
        JSONObject js11 = JSON.parseObject(str);


        String ret =  postBodyRaw("https://fs.weiqi.com.cn/api/shorten/createShortUrl",js11.toString());
        System.out.println(ret);
}


    public static String getURLEncoderString(String str) {
        String result = "";
        if (null == str) {
            return "";
        }
        try {
            result = URLEncoder.encode(str, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return result;
    }

    public static String URLDecoderString(String str) {
        String result = "";
        if (null == str) {
            return "";
        }
        try {
            result = URLDecoder.decode(str, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * post请求 raw 类型 返回token  华为专用
     *
     * @param uri
     * @param content
     * @return
     */
    public static String postBodyRawReturnToken(String uri, String content) {

        String result = null;
        try {
            HttpPost httpPost = new HttpPost(uri);
            StringEntity requestEntity = new StringEntity(content, "UTF-8");
            requestEntity.setContentType("application/json");
            httpPost.setEntity(requestEntity);
            HttpResponse response = httpClient.execute(httpPost);
            Header[] headers = response.getHeaders("X-Subject-Token");
            result = headers[0].getValue();

        } catch (Exception e) {
            logger.error("uri={},content={},异常={}", uri, content, e);

        }

        return result;
    }
    /**
     * post请求 raw 类型
     *
     * @param uri
     * @param content
     * @return
     */
    public static String postBodyRawHuawei(String uri, String content,String token) {

        String result = null;
        try {
            HttpPost httpPost = new HttpPost(uri);
            StringEntity requestEntity = new StringEntity(content, "UTF-8");
            requestEntity.setContentType("application/json");
            if(token!=null&token.length()>0){

                httpPost.addHeader("X-Auth-Token", token);
            }
            httpPost.setEntity(requestEntity);
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            result = EntityUtils.toString(entity, "UTF-8");

        } catch (Exception e) {
            logger.error("uri={},content={},异常={}", uri, content, e);
        }

        return result;
    }

}
