package com.ym.zxhcsdk;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class HttpClientUtils {
    private static final String TAG = "HttpClientUtils";

    public static void GetEvent(String url) {
        new Thread() {
            public void run() {
                getRequest(releactReportUrl(url), new OnRequestCallBack() {
                    @Override
                    public void onSuccess(String json) {
//                        Log.d("wxw", "GetEvent url"+url);
//                        Log.d("wxw", "GetEvent json"+json);
                    }

                    @Override
                    public void onError(String errorMsg) {
//                        Log.d("wxw", "GetEvent url" + url);
//                        Log.d("wxw", "GetEvent errorMsg" + errorMsg);
                    }
                });
            }
        }.start();
    }

    public static void get(final String requestUrl, Map<String, String> map, final OnRequestCallBack callBack) {
        new Thread() {
            public void run() {
                getRequest(requestUrl + "?" + addParams(map), callBack);
            }
        }.start();
    }

    public static void post(final String requestUrl, final String params, final OnRequestCallBack callBack) {
        new Thread() {
            public void run() {
                postRequest(requestUrl, params, callBack);
            }
        }.start();
    }

    private static void getRequest(String requestUrl, OnRequestCallBack callBack) {
        Log.d("wxw","LoadURL  "+requestUrl);
        boolean isSuccess = false;
        String message;
        InputStream inputStream = null;
        ByteArrayOutputStream baos = null;
        try {
            URL url = new URL(requestUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setInstanceFollowRedirects(true);
            connection.setConnectTimeout(50000);
            connection.setReadTimeout(50000);
            // User-Agent  IE9的标识
            //connection.setRequestProperty("User-Agent", "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0;");
            connection.setRequestProperty("Accept-Language", "zh-CN");
            connection.setRequestProperty("Connection", "Keep-Alive");
            connection.setRequestProperty("Charset", "UTF-8");

            /*Zx
             * 当我们要获取我们请求的http地址访问的数据时就是使用connection.getInputStream().read()方式时我们就需要setDoInput(true)，
             * 根据api文档我们可知doInput默认就是为true。我们可以不用手动设置了，如果不需要读取输入流的话那就setDoInput(false)。
             * 当我们要采用非get请求给一个http网络地址传参 就是使用connection.getOutputStream().write() 方法时我们就需要setDoOutput(true), 默认是false
             */
            // 设置是否从httpUrlConnection读入，默认情况下是true;
            connection.setDoInput(true);
            // 设置是否向httpUrlConnection输出，如果是post请求，参数要放在http正文内，因此需要设为true, 默认是false;
            //connection.setDoOutput(true);//Android  4.0 GET时候 用这句会变成POST  报错java.io.FileNotFoundException
            connection.setUseCaches(false);
            connection.connect();//

            Log.d("wxw","connection.getURL();  "+connection.getURL());
            int contentLength = connection.getContentLength();
            if (connection.getResponseCode() == 200) {
                inputStream = connection.getInputStream();//会隐式调用connect()
                baos = new ByteArrayOutputStream();
                int readLen;
                byte[] bytes = new byte[1024];
                while ((readLen = inputStream.read(bytes)) != -1) {
                    baos.write(bytes, 0, readLen);
                }
                String result = baos.toString();
                message = result;

                isSuccess = true;
            } else {
                //Log.d("wxw","errorUrl "+requestUrl);
                message = "请求失败 code:" + connection.getResponseCode() + connection.getResponseMessage();
            }

        } catch (MalformedURLException e) {
            message = e.getMessage();
            e.printStackTrace();
        } catch (IOException e) {
            message = e.getMessage();
            e.printStackTrace();
        } finally {
            try {
                if (baos != null) {
                    baos.close();
                }
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                message = e.getMessage();
                e.printStackTrace();
            }
        }
        if (callBack != null) {
            if (isSuccess) {
                callBack.onSuccess(message);
            } else {
                callBack.onError(message);
            }
        }
    }

    private static void postRequest(String requestUrl, String params, OnRequestCallBack callBack) {
        boolean isSuccess = false;
        String message;
        InputStream inputStream = null;
        ByteArrayOutputStream baos = null;
        try {
            URL url = new URL(requestUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            // 设定请求的方法为"POST"，默认是GET
            connection.setRequestMethod("POST");
            connection.setConnectTimeout(50000);
            connection.setReadTimeout(50000);
            // User-Agent  IE9的标识
            connection.setRequestProperty("User-Agent", "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0;");
            connection.setRequestProperty("Accept-Language", "zh-CN");
            connection.setRequestProperty("Connection", "Keep-Alive");
            connection.setRequestProperty("Charset", "UTF-8");
            /*
             * 当我们要获取我们请求的http地址访问的数据时就是使用connection.getInputStream().read()方式时我们就需要setDoInput(true)，
             * 根据api文档我们可知doInput默认就是为true。我们可以不用手动设置了，如果不需要读取输入流的话那就setDoInput(false)。
             * 当我们要采用非get请求给一个http网络地址传参 就是使用connection.getOutputStream().write() 方法时我们就需要setDoOutput(true), 默认是false
             */
            // 设置是否从httpUrlConnection读入，默认情况下是true;
            connection.setDoInput(true);
            // 设置是否向httpUrlConnection输出，如果是post请求，参数要放在http正文内，因此需要设为true, 默认是false;
            connection.setDoOutput(true);
            connection.setUseCaches(false);

            // set  params three way  OutputStreamWriter
            OutputStreamWriter out = new OutputStreamWriter(
                    connection.getOutputStream(), "UTF-8");
            // 发送请求params参数
            out.write(params);
            out.flush();
            connection.connect();

            int contentLength = connection.getContentLength();
            if (connection.getResponseCode() == 200) {
                // 会隐式调用connect()
                inputStream = connection.getInputStream();
                baos = new ByteArrayOutputStream();
                int readLen;
                byte[] bytes = new byte[1024];
                while ((readLen = inputStream.read(bytes)) != -1) {
                    baos.write(bytes, 0, readLen);
                }
                String backStr = baos.toString();
                message = backStr;
                isSuccess = true;
            } else {
                message = "请求失败 code:" + connection.getResponseCode();
            }

        } catch (MalformedURLException e) {
            message = e.getMessage();
            e.printStackTrace();
        } catch (IOException e) {
            message = e.getMessage();
            e.printStackTrace();
        } finally {
            try {
                if (baos != null) {
                    baos.close();
                }
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                message = e.getMessage();
                e.printStackTrace();
            }
        }
        if (isSuccess) {
            callBack.onSuccess(message);
        } else {
            callBack.onError(message);
        }
    }

    public interface OnRequestCallBack {
        void onSuccess(String json);

        void onError(String errorMsg);
    }


    public static void LoadImg(final String imgUrl, final OnRequestImgCallBack callBack) {
        new Thread() {
            public void run() {
                getImg(imgUrl, callBack);
            }
        }.start();
    }

    private static void getImg(String url, OnRequestImgCallBack callBack) {
        boolean isSuccess = false;
        String message = "";
        URL imgUrl = null;
        Bitmap bitmap = null;
        InputStream is = null;
        try {
            imgUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) imgUrl
                    .openConnection();
            conn.setDoInput(true);
            conn.connect();
            if (conn.getResponseCode() == 200) {
                is = conn.getInputStream();
                bitmap = BitmapFactory.decodeStream(is);
                isSuccess = true;
            } else {
                message = "请求失败 code:" + conn.getResponseCode();
            }
        } catch (MalformedURLException e) {
            message = e.getMessage();
            e.printStackTrace();
        } catch (IOException e) {
            message = e.getMessage();
            e.printStackTrace();
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
            } catch (IOException e) {
                message = e.getMessage();
                e.printStackTrace();
            }

        }
        if (isSuccess) {
            callBack.onSuccess(bitmap);
        } else {
            callBack.onError(message);
        }
    }

    public interface OnRequestImgCallBack {
        void onSuccess(Bitmap bitmap);

        void onError(String errorMsg);
    }

    //添加公共参数
    public static String addParams(Map<String, String> request) {
        if (request == null) {
            request = new HashMap<>();
        }
        String str = "";
////        request.put("pid","2100154");
////        request.put("type","api");
////        request.put("ad_type","3");
////        request.put("ad_w","720");
////        request.put("ad_h","1280");
//        request.put("app_id", ZXHCConstant.ZXHC_APPID);
//        request.put("app_package","com.popcap.pvz2cthd");
//        request.put("app_name","com.popcap.pvz2cthd");
//        request.put("app_version","1005");
//        request.put("device_imei","X6GNU17524105082");
//        request.put("device_adid","d0cf1c3d5280f16b");
//        request.put("device_mac","F0:C8:50:A1:4E:8E");
//        request.put("device_width","1920");
//        request.put("device_height","1132");
//        request.put("device_imsi","460000501365163");
//        request.put("device_network","1");
//        request.put("device_os","Android");
//        request.put("device_os_version","device_os_version");
//        request.put("device_density","2.0");
//        request.put("device_ppi","2.0");
//        request.put("device_ip","183.211.87.156");
//        request.put("device_ua","Dalvik%2F2.1.0+%28Linux%3B+U%3B+Android+9%3B+Redmi+Note+8+Pro+MIUI%2FV10.4.9.0.PGGCNXM%29");
//        request.put("device_type","0");
//        request.put("is_mobile","1");
//        request.put("device_model","FLA-AL10");
//        request.put("device_brand","HUAWEI");
        request.put("app_id", ZXHCConstant.ZXHC_APPID);
        request.put("app_package", ZXHCConstant.app_package);
        request.put("app_name", ZXHCConstant.app_name);
        request.put("app_version", ZXHCConstant.app_version);
        request.put("device_imei", ZXHCConstant.device_imei);
        request.put("device_oaid", ZXHCConstant.device_oaid);
        request.put("device_adid", ZXHCConstant.device_adid);
        request.put("device_mac", ZXHCConstant.device_mac);
        request.put("device_width", ZXHCConstant.device_width);
        request.put("device_height", ZXHCConstant.device_height);
        request.put("device_imsi", ZXHCConstant.device_imsi);
        request.put("device_network", ZXHCConstant.device_network);
        request.put("device_os", ZXHCConstant.device_os);
        request.put("device_os_version", ZXHCConstant.device_os_version);
        request.put("device_density", ZXHCConstant.device_density);
        request.put("device_ppi", ZXHCConstant.device_ppi);
        request.put("screen_size", ZXHCConstant.screen_size);
        request.put("device_ip", ZXHCConstant.device_ip);
        request.put("device_ua", ZXHCConstant.device_ua);
        request.put("device_type", ZXHCConstant.device_type);
        request.put("is_mobile", "1");
        request.put("device_model", ZXHCConstant.device_model);
        request.put("device_brand", ZXHCConstant.device_brand);
        request.put("device_geo_lat", ZXHCConstant.device_geo_lat);
        request.put("device_geo_lon", ZXHCConstant.device_geo_lon);
        request.put("device_geo_city", ZXHCConstant.device_geo_city);
        Iterator entries = request.entrySet().iterator();
        while (entries.hasNext()) {
            Map.Entry entry = (Map.Entry) entries.next();
            if (entry.getKey() != null && entry.getValue() != null) {
                str += entry.getKey() + "=" + entry.getValue() + "&";
            }
            entries.remove();
        }
        str = str.substring(0, str.length() - 1);
        return str;
    }
    //上报参数替换
    private static String releactReportUrl(String url){
        url = url.replace("__RE_DOWN_X__", ZXHCConstant.downX + "");//手指按下时相对于广告位左上角的横坐标
        url = url.replace("__RE_DOWN_Y__", ZXHCConstant.downY + "");//手指按下时相对于广告位左上角的纵坐标
        url = url.replace("__RE_UP_X__", ZXHCConstant.upX + "");//手指抬起时相对于广告位左上角的横坐标
        url = url.replace("__RE_UP_Y__", ZXHCConstant.upY + "");//手指抬起时相对于广告位左上角的纵坐标
        url = url.replace("__DOWN_X__", ZXHCConstant.downRawX + "");//手指按下时相对于屏幕左上角的横坐标
        url = url.replace("__DOWN_Y__", ZXHCConstant.downRawY + "");//手指按下时相对于屏幕左上角的纵坐标
        url = url.replace("__UP_X__", ZXHCConstant.upRawX + "");//手指抬起时相对于屏幕左上角的横坐标
        url = url.replace("__UP_Y__", ZXHCConstant.upRawY + "");//手指抬起时相对于屏幕左上角的纵坐标
        url = url.replace("__UTC_TS__", System.currentTimeMillis() + "");//客户端触发时间戳,自 1970 年起的毫秒 ，13 位
        url = url.replace("__UTC_TS_SECOND__", System.currentTimeMillis() / 1000 + "");//客户端触发时间戳,自 1970 年起的秒 ，10 位
        url = url.replace("__WIDTH__", "-999");//实际广告位的宽，单位为像素
        url = url.replace("__HEIGHT__", "-999");//实际广告位的高，单位为像素
        url = url.replace("__LATITUDE__", ZXHCConstant.device_geo_lat);//地理位置信息, 纬度
        url = url.replace("__LONGITUDE__", ZXHCConstant.device_geo_lon);//地理位置信息, 经度
        url = url.replace("__IP__", ZXHCConstant.device_ip);
        return  url;
    }

}
