package com.yutou.jianr_mg.Network;


import com.yutou.jianr_mg.Application;
import com.yutou.jianr_mg.Data.AppData;
import com.yutou.jianr_mg.Interfaces.DownloadFileInerface;
import com.yutou.jianr_mg.Interfaces.HttpInterface;
import com.yutou.jianr_mg.Tools.Log;
import com.yutou.jianr_mg.Tools.Utils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by 58381 on 2018/1/20.
 */

public class HttpUtils {
    private static OkHttpClient client;

    private static OkHttpClient getClient() {
        return new OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS).build();

    }

    public static void get(final String url, final HttpInterface httpInterface) {
        if (client == null) {
            client = getClient();
        }
        Request request = new Request.Builder().url(url).build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                httpInterface.httpError(e);
            }

            @Override
            public void onResponse(Call call, Response response) {
                try {
                    String http = response.body().string();
                    if (httpInterface != null)
                        httpInterface.httpGetData(http, response.code());
                    Log.i(url, "传参：" + url.replace(HttpApi.HOME_URL, "") + " 接收：" + http);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public static void post(final String url, final JSONObject json, final HttpInterface httpInterface) {
        if (client == null) {
            client = getClient();
        }
        Request request = new Request.Builder().url(url).post(mapToBody(json)).removeHeader("User-Agent").build();
        Call call = client.newCall(request);
        try {
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    if (httpInterface != null)
                        httpInterface.httpError(e);
                    e.printStackTrace();
                    Log.e(e, HttpUtils.class);
                }

                @Override
                public void onResponse(Call call, Response response) {
                    try {
                        String http = response.body().string();
                        if (httpInterface != null)
                            httpInterface.httpGetData(http, response.code());
                        Log.i(url, "传参：" + json.toString() + " 接收：" + http);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static void downloadFile(final String url, final String srcPath, final DownloadFileInerface downloadFileInerface) {
        if (client == null)
            client = getClient();
        File path = new File(srcPath);
        if (!path.exists())
            path.mkdirs();
        Request request = new Request.Builder().url(url).build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
                AppData.handler.post(() -> downloadFileInerface.over(false));
            }

            boolean isflag = true;

            @Override
            public void onResponse(Call call, Response response) {
                InputStream is = null;
                byte[] buf = new byte[1024];
                int len = 0;
                FileOutputStream fos = null;
                try {
                    is = response.body().byteStream();
                    long total = response.body().contentLength();
                    File file = new File(srcPath, getNameFromUrl(url));
                    fos = new FileOutputStream(file);
                    long sum = 0;
                    int pr = -1;
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                        sum += len;
                        int progress = (int) (sum * 1.0f / total * 100);
                        // 下载中
                        if (progress == pr) {
                            isflag = false;
                        } else {
                            isflag = true;
                            pr = progress;
                        }
                        if (progress == 100) {
                            isflag = true;
                            pr = progress;
                        }
                        if (isflag)
                            while (!downloadFileInerface.downloading(getNameFromUrl(url), progress, total)) {
                                Thread.sleep(10);
                            }
                        System.out.println("下载：" + progress);
                    }
                    fos.flush();
                    // 下载完成
                    AppData.handler.post(() -> downloadFileInerface.over(true));
                } catch (Exception e) {
                    e.printStackTrace();
                    AppData.handler.post(() -> downloadFileInerface.over(false));
                    Utils.toast(Application.application,"下载文件发生错误！");
                }
            }
        });
    }

    public static String getNameFromUrl(String url) {
        return url.substring(url.lastIndexOf("/") + 1);
    }

    public static String getHtml(String url) {
        Log.i("获取网页源码:" + url);
        if (client == null)
            client = getClient();
        Request request = new Request.Builder().url(url).build();
        try {
            Response response = client.newCall(request).execute();
            return response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "<html><body></body></html>";
    }

    private static FormBody mapToBody(JSONObject json) {
        FormBody.Builder builder = new FormBody.Builder();
        if (json == null) {
            return builder.build();
        }
        Iterator<String> keys = json.keys();
        while (keys.hasNext()) {
            String key = keys.next();
            try {
                builder.add(key, json.get(key) + "");

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        if (json.isNull("token"))
            builder.add("token", AppData.Token);
        if (json.isNull("uid"))
            builder.add("uid", AppData.user.getId() + "");
        if (json.isNull("imei"))
            builder.add("imei", Utils.getIMEI());
        if (json.isNull("clientVersion"))
            builder.add("clientVersion", Utils.getVersion());
        return builder.build();
    }

}
