package com.mosty.base.utils;

import com.alibaba.fastjson.JSON;
import okhttp3.*;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.codehaus.xfire.client.Client;
import org.codehaus.xfire.transport.http.CommonsHttpMessageSender;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class HttpUtils {
    private static Logger logger = LoggerFactory
            .getLogger(HttpUtils.class);
    public static final String POST = "POST";

    public static final String GET = "GET";

    public static final int CONNECTTIMEOUT = 10 * 60 * 1000;

    public static final int READTIMEOUT = 10 * 60 * 1000;

    public static final String charset = "utf-8";

    public static final String DEFAULT_CONTENT_TYPE = "application/x-www-form-urlencoded";

    public static final String JSON_CONTENT_TYPE = "application/json";

    public static final String XML_CONTENT_TYPE = "application/xml";

/*    public static void main(String[] args) {
        StringBuffer reqXml = new StringBuffer();
        reqXml.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        reqXml.append("<xml><sminfo_input><systemid>");
        reqXml.append("39a15b33e62e453d97378e326a3960f4");// 短信平台为我们分配的短信接口调用帐号
        reqXml.append("</systemid><extension_no>06666</extension_no><tousermobile>");
        reqXml.append("18108089373");
        reqXml.append("</tousermobile><content>");
        reqXml.append("高新短信测试");
        reqXml.append("</content><fromusername>高新智慧公安</fromusername></sminfo_input></xml>");
        Object[] webserviceR = HttpUtils.httprequest(
                "http://dx.sc/services/IMsInterfaceNewService?wsdl", reqXml.toString());// new
        if (webserviceR != null) {
            XML xml = HttpUtils.sendMessageAck(webserviceR[0].toString());
            System.out.println("12312312312312");

        } else {
            System.out.println("cssdasdasdas");
        }
        System.out.println("ssdasdasdas");
    }*/

    /*****
     * webservice请求发送
     *
     * @param wsdl
     * @param reqXml
     * @return
     */
//    public static Object[] httprequest(String wsdl, String reqXml) {
//        try {
//            URL _url = new URL(wsdl.trim());
//            HttpURLConnection httpConnection = (HttpURLConnection) _url
//                    .openConnection();
//            httpConnection.setConnectTimeout(5000);
//            httpConnection.setReadTimeout(3000);// 设置http连接的读超时,单位是毫秒
//            httpConnection.connect();
//            Client _client = new Client(httpConnection.getInputStream(), null);
//            _client.setProperty(CommonsHttpMessageSender.HTTP_TIMEOUT,
//                    String.valueOf(3000));// 设置发送的超时限制,单位是毫秒;
//            _client.setProperty(CommonsHttpMessageSender.DISABLE_KEEP_ALIVE,
//                    "true");
//            _client.setProperty(
//                    CommonsHttpMessageSender.DISABLE_EXPECT_CONTINUE, "true");
//            return _client.invoke("sendMessage",
//                    new Object[]{reqXml});
//        } catch (Exception e) {
//            logger.error(e.getMessage());
//        }
//        return null;
//    }


    /****
     * 将webservice请求结果生成对象
     *
     * @param sendMsgR
     * @return
     */
    public static XML sendMessageAck(String sendMsgR) {
        logger.info("短信接口反馈内容：" + sendMsgR);
        XML xml = new XML();
        try {
            List<Class> classes = new ArrayList<Class>();
            classes.add(XML.class);
            classes.add(Sminfo_return.class);
            try {
                xml = (XML) XStreamUtil.Xml2Object(classes, sendMsgR);
                if (xml == null) {
                    throw new Exception("数据为空");
                }
                if (xml.getSminfo_return() == null) {
                    throw new Exception("数据为空");
                }
                if (StringUtils.isBlank(xml.getSminfo_return().getRenturncode())) {
                    throw new Exception("数据为空");
                }
                if (xml.getSminfo_return()
                        .getRenturncode().equals("1")) {
                    throw new Exception("短信接口调用失败");
                }
                xml.setMsg("短信接口调用成功");
                xml.setState("1");
            } catch (Exception e) {
                throw new Exception("短信接口返回数据有异常");
            }
        } catch (Exception e) {
            xml.setMsg(e.getMessage());
            xml.setState("0");
            logger.error(e.getMessage());
            return xml;
        }
        return xml;
    }


    public static String executePost(String urlStr, Map<String, Object> params,
                                     Map<String, String> headerOpitions) {
        return executeHttpMethod(POST, urlStr, params, headerOpitions);
    }

    /**
     * post请求
     *
     * @param urlStr
     * @param params
     * @return
     */
    public static String executePost(String urlStr, Map<String, Object> params) {
        return executeHttpMethod(POST, urlStr, params);
    }

    /**
     * @param urlStr
     * @param jsonStr
     * @return
     * @Title http POST json数据
     * @author lijiaqi
     * @description
     */
    public static String executePostJSON(String urlStr, String jsonStr) {
        return executePost(urlStr, jsonStr, JSON_CONTENT_TYPE);
    }

    /**
     * @param urlStr
     * @param xmlStr
     * @return
     * @Title http post xml数据
     * @author lijiaqi
     * @description
     */
    public static String executePostXML(String urlStr, String xmlStr) {
        return executePost(urlStr, xmlStr, XML_CONTENT_TYPE);
    }

    public static String executePost(String urlStr, String postStr, String contenType) {
        String result = null;
        URL url = null;
        HttpURLConnection connection = null;
        String method = "POST";
        InputStreamReader in = null;
        try {

            url = new URL(urlStr);
            connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setRequestMethod(method);
            connection.setRequestProperty("Content-Type", contenType);
            connection.setRequestProperty("Charset", "UTF-8");
            connection.setConnectTimeout(CONNECTTIMEOUT);
            connection.setReadTimeout(READTIMEOUT);

            if (method.equals(POST)) {
                DataOutputStream dop = new DataOutputStream(connection.getOutputStream());
                dop.write(postStr.getBytes("UTF-8"));
                dop.flush();
                dop.close();
            }
            // 连接
            connection.connect();
            int code = connection.getResponseCode();
            // 如果返回状态码200
            if (200 == code) {
                // 读取返回数据
                in = new InputStreamReader(connection.getInputStream());
                BufferedReader bufferedReader = new BufferedReader(in);
                StringBuffer strBuffer = new StringBuffer();
                String line = null;
                while ((line = bufferedReader.readLine()) != null) {
                    strBuffer.append(line);
                }
                result = strBuffer.toString();
            }
            if (code > 400) {
                System.err.println("请求出错状态码： " + code);
                throw new RuntimeException("code " + code);

            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
            throw new RuntimeException("不合法的http地址", e);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("读取数据失败", e);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    throw new RuntimeException("关闭流失败", e);
                }
            }
        }
        return result;

    }

    /**
     * post请求
     *
     * @param urlStr
     * @return
     */
    public static String executePost(String urlStr, String postStr) {
        return executePost(urlStr, postStr, "application/x-www-form-urlencoded");
    }

    /**
     * get请求
     *
     * @param urlStr
     * @param params
     * @return
     */
    public static String executeGet(String urlStr, Map<String, Object> params) {
        return executeHttpMethod(GET, urlStr, params);
    }

    /**
     * get请求
     *
     * @param urlStr
     * @param params
     * @return
     */
    public static String executeGet(String urlStr, Map<String, Object> params,
                                    Map<String, String> headerOpitions) {
        return executeHttpMethod(GET, urlStr, params, headerOpitions);
    }

    public static String executeHttpMethod(String method, String urlStr,
                                           Map<String, Object> params) {
        return executeHttpMethod(method, urlStr, params, null);
    }

    public static String executeHttpMethod(String method, String urlStr, Map<String, Object> params,
                                           Map<String, String> headerOptions, String proxyHost,
                                           int proxyPort) {
        Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
        String result = null;
        URL url = null;
        HttpURLConnection connection = null;
        InputStreamReader in = null;
        try {
            if (method.equals(GET)) {
                urlStr = String.format("%s?%s", urlStr, buildParamsString(params));
            }
            url = new URL(urlStr);
            connection = (HttpURLConnection) url.openConnection(proxy);
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setRequestMethod(method);
            connection.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded; charset=UTF-8");
            connection.setRequestProperty("Charset", "UTF-8");

            if (headerOptions != null && headerOptions.size() > 0) {
                for (String key : headerOptions.keySet()) {
                    connection.setRequestProperty(key, headerOptions.get(key));
                }
            }

            connection.setConnectTimeout(5000);
            connection.setReadTimeout(10000);
            if (method.equals(POST)) {
                DataOutputStream dop = new DataOutputStream(connection.getOutputStream());
                // 构建传递参数
                String paramStr = buildParamsString(params);
                dop.write(paramStr.getBytes());
                dop.flush();
                dop.close();
            }
            // 连接
            connection.connect();
            int code = connection.getResponseCode();

            if (code > 400) {
                throw new RuntimeException("code " + code);
            }
            // 如果返回状态码200
            if (200 == code) {
                // 读取返回数据
                in = new InputStreamReader(connection.getInputStream());
                BufferedReader bufferedReader = new BufferedReader(in);
                StringBuffer strBuffer = new StringBuffer();
                String line = null;
                while ((line = bufferedReader.readLine()) != null) {
                    strBuffer.append(line);
                }
                result = strBuffer.toString();
            }
        } catch (MalformedURLException e) {
            throw new RuntimeException("不合法的http地址", e);
        } catch (IOException e) {
            throw new RuntimeException("读取数据失败", e);
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    throw new RuntimeException("关闭流失败", e);
                }
            }
        }
        return result;
    }

    public static String executeHttpMethod(String method, String urlStr, Map<String, Object> params,
                                           Map<String, String> headerOptions) {
        String result = null;
        URL url = null;
        HttpURLConnection connection = null;
        InputStreamReader in = null;
        try {
            if (method.equals(GET)) {
                urlStr = String.format("%s?%s", urlStr, buildParamsString(params));
            }
            url = new URL(urlStr);
            connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setConnectTimeout(60000);
            connection.setReadTimeout(60000);
            connection.setRequestMethod(method);
            connection.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded; charset=UTF-8");
            connection.setRequestProperty("Charset", "UTF-8");

            if (headerOptions != null && headerOptions.size() > 0) {
                for (String key : headerOptions.keySet()) {
                    connection.setRequestProperty(key, headerOptions.get(key));
                }
            }

            connection.setConnectTimeout(CONNECTTIMEOUT);
            connection.setReadTimeout(READTIMEOUT);
            if (method.equals(POST)) {
                DataOutputStream dop = new DataOutputStream(connection.getOutputStream());
                // 构建传递参数
                String paramStr = buildParamsString(params);
                dop.write(paramStr.getBytes());
                dop.flush();
                dop.close();
            }
            // 连接
            connection.connect();
            int code = connection.getResponseCode();

            if (code > 400) {
                throw new RuntimeException("code " + code);
            }
            // 如果返回状态码200
            if (200 == code) {
                // 读取返回数据
                in = new InputStreamReader(connection.getInputStream());
                BufferedReader bufferedReader = new BufferedReader(in);
                StringBuffer strBuffer = new StringBuffer();
                String line = null;
                while ((line = bufferedReader.readLine()) != null) {
                    strBuffer.append(line);
                }
                result = strBuffer.toString();
            }
        } catch (MalformedURLException e) {
            throw new RuntimeException("不合法的http地址", e);
        } catch (IOException e) {
            throw new RuntimeException("读取数据失败", e);
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    throw new RuntimeException("关闭流失败", e);
                }
            }
        }
        return result;
    }

    /**
     * 是否是存在的文件
     *
     * @param ulrStr
     * @return
     */
    public static boolean isNetFileAvailable(String ulrStr) {
        try {
            //设置此类是否应该自动执行 HTTP 重定向（响应代码为 3xx 的请求）。
            HttpURLConnection.setFollowRedirects(false);
            //到 URL 所引用的远程对象的连接
            HttpURLConnection con = (HttpURLConnection) new URL(ulrStr).openConnection();
            /* 设置 URL 请求的方法， GET POST HEAD OPTIONS PUT DELETE TRACE 以上方法之一是合法的，具体取决于协议的限制。*/
            con.setRequestMethod("HEAD");
            //从 HTTP 响应消息获取状态码
            return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 构建参数字符串
     *
     * @param params
     * @return
     * @throws UnsupportedEncodingException
     */
    private static String buildParamsString(Map<String, Object> params) throws UnsupportedEncodingException {
        StringBuffer paramsBuffer = new StringBuffer();
        int flag = 0;
        if (params != null) {
            for (String key : params.keySet()) {
                if (flag != 0) {
                    paramsBuffer.append("&");
                }
                String value = URLEncoder.encode(String.valueOf(params.get(key)), "utf-8");
                paramsBuffer.append(key).append("=").append(value);
                flag = 1;
            }
        }
        return paramsBuffer.toString();
    }

    public static byte[] getByteArrayFromUrl(String urlStr) {
        URL url = null;
        HttpURLConnection connection = null;
        InputStream in = null;
        byte[] content = null;
        try {
            url = new URL(urlStr);
            connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setRequestMethod("GET");
            connection.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded; charset=UTF-8");
            connection.setRequestProperty("Charset", "UTF-8");
            connection.setConnectTimeout(CONNECTTIMEOUT);
            connection.setReadTimeout(READTIMEOUT);
            // 连接
            connection.connect();
            int code = connection.getResponseCode();

            if (code > 400) {
                throw new RuntimeException("code " + code);
            }
            // 如果返回状态码200
            if (200 == code) {
                // 读取返回数据
                in = connection.getInputStream();
                content = IOUtils.toByteArray(in);
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
            throw new RuntimeException("不合法的http地址", e);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("读取数据失败", e);
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    throw new RuntimeException("关闭流失败", e);
                }
            }
        }
        return content;
    }


    public static String previewURLs1(String sbbh) throws Exception {

        OkHttpClient client = (new OkHttpClient()).newBuilder().build();
        Request request = (new Request.Builder()).url("http://80.75.112.19:18080/api/play/start/51050100002000111603/" + sbbh).method("GET", (okhttp3.RequestBody) null).addHeader("Cookie", "").build();
        Response response = client.newCall(request).execute();
        boolean isf = false;
        if (response.code() == 401) {
            Login();
            //String s = previewURLs1(sbbh);
            //return s;
            isf = true;
        }
        if (isf) {
            previewURLs1(sbbh);
        }
        String body = response.body().string();
        if (org.apache.commons.lang3.StringUtils.isNotBlank(body)) {
            Map<String, Object> hashMap = (Map) JSON.parseObject(body, HashMap.class);
            int code = (Integer) hashMap.get("code");
            if (code == 0) {
                Map<String, Object> urlMap = (Map) hashMap.get("data");
                String hls = urlMap.get("hls").toString();
                System.out.println(hls.toString());
                return hls;
            } else {
                String s = previewURLs1(sbbh);
                return s;
            }
        } else {
            return null;
        }

    }


    private static String Login() throws IOException {
        OkHttpClient client = (new OkHttpClient()).newBuilder().build();
        Request request = (new Request.Builder()).url("http://80.75.112.19:18080/api/user/login?username=admin&password=fad1b644f95eeaaf01816369e4209352").method("GET", (okhttp3.RequestBody) null).build();
        Response response = client.newCall(request).execute();
//        int code = response.code();
//        String body = response.body().string();
        Headers headers = response.headers();
        System.out.println(headers.get("Set-Cookie"));
        return headers.get("Set-Cookie");
    }

    public static void main(String[] args) throws Exception {

        String s = previewURLs1("51050200001310072154");

        System.out.println(s);
    }


}
