package com.navinfo.outdoor.http;

import android.app.Activity;
import android.widget.Toast;

import com.github.lazylibrary.util.DES;
import com.github.lazylibrary.util.MD5;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.HttpHeaders;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.PostRequest;
import com.navinfo.outdoor.bean.PoiUploadBean;
import com.navinfo.outdoor.util.Md5Util;
import com.umeng.umcrash.UMCrash;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.FormBody;
import okhttp3.RequestBody;

/**
 * 作用：OKGO帮助类-建造者模式
 */

public class OkGoBuilder<T> {
    private Activity activity;
    /**
     * 请求网址
     */
    private String url;
    private String file;
    /**
     * 参数
     */
    private HttpParams params;
    private String json;
    /**
     * 实体类
     */
    private Class<T> clazz;
    private List<File> files;

    private String token;

    /**
     * 单列模式
     **/
    private static OkGoBuilder mOkGoBuilder = null;

    /**
     * 构造函数私有化
     **/
    private OkGoBuilder() {

    }

    /**
     * 公有的静态函数，对外暴露获取单例对象的接口
     **/
    public static OkGoBuilder getInstance() {
//        if (mOkGoBuilder == null) {
//            synchronized (OkGoBuilder.class) {
//                if (mOkGoBuilder == null) {
        mOkGoBuilder = new OkGoBuilder();
//                }
//            }
//        }
        return mOkGoBuilder;
    }

    public OkGoBuilder Builder(Activity activity) {
        this.activity = activity;
        return this;
    }

    public OkGoBuilder url(String url) {
        this.url = url;
        this.url = url;
        return this;
    }

    public OkGoBuilder file(String file) {
        this.file = file;
        return this;
    }


    public OkGoBuilder params(HttpParams params) {
        this.params = params;
        return this;
    }

    public OkGoBuilder token(String token) {
        this.token = token;
        return this;
    }

    public OkGoBuilder fileList(List<File> files) {
        this.files = files;
        return this;
    }


    public OkGoBuilder json(String json) {
        this.json = json;
        return this;
    }

    public OkGoBuilder cls(Class<T> clazz) {
        this.clazz = clazz;
        return this;
    }


    /**
     * post异步请求
     */
    public void postRequest(Callback<T> callback) {
        OkGo
                // 请求方式和请求url
                .<T>post(url)
                .isMultipart(true)
                .headers(getHeader())
                .params(params)
//                .upJson(json)
                // 请求的 tag, 主要用于取消对应的请求
                .tag(this)

                // 设置当前请求的缓存key,建议每个不同功能的请求设置一个
//                .cacheKey("cacheKey")
                // 缓存模式，详细请看缓存介绍
//                .cacheMode(CacheMode.DEFAULT)
                .execute(new DialogCallback<T>(clazz) {
                    @Override
                    public void onSuccess(Response<T> response) {
                        if (response.code()==200){
                            callback.onSuccess(response.body(), 1);
                        }else {
                            Toast.makeText(activity, response.message(), Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onError(Response<T> response) {
                        super.onError(response);
                        Throwable throwable = response.getException();
                        if (throwable != null) {
                            throwable.printStackTrace();
                            callback.onError(throwable, 2);
                            /**
                             * 友盟+
                             * 使用自定义错误，查看时请在错误列表页面选择【自定义异常】
                             */
                            UMCrash.generateCustomLog("网络请求报错-位置：OKGOBuilder" + throwable, "UmengException");
                        }
                    }
                });

    }

    public HttpHeaders getHeader() {
        HttpHeaders headers = new HttpHeaders();
        try {
            if (token == null) {
                headers.put("Authorization", "Basic YXBwOmFwcHNlY3JldA==");
            } else {
                headers.put("Authorization", "bearer " + token);
            }
            String util = "";//k1=v1&k2=v2&k3=v3
            if (params != null && params.urlParamsMap != null) {
                for (Map.Entry<String, List<String>> entry : params.urlParamsMap.entrySet()) {
                    if (!"file".equals(entry.getKey())) {
                        util += entry.getKey() + "=" + entry.getValue().get(0).toString() + "&";
                    }
                }
                if (util != null && !util.equals("")) {
                    util = util.substring(0, util.length() - 1);
                }
            }
            headers.put("key", Md5Util.toMD5("dtxb_2021_navinfo" + util));
            return headers;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * post 文件 同步请求
     *
     * @param
     * @return
     */
    public okhttp3.Response postFileSynchronization() {
        long time = System.currentTimeMillis();
        params.put("datetime", time);
        try {
            okhttp3.Response execute = OkGo
                    // 请求方式和请求url
                    .<PoiUploadBean>post(url)
                    .headers(getHeader())
                    // 请求的 tag, 主要用于取消对应的请求
                    .params(params)
                    .addFileParams("file", files)

                    .tag(this)
                    .execute();
            return execute;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * post 文件 异步请求
     *
     * @param
     * @param callback
     * @return
     */
    public void postFileAsynchronous(Callback callback) {
        long time = System.currentTimeMillis();
        params.put("datetime", time);
        OkGo
                // 请求方式和请求url
                .<T>post(url)
                .headers(getHeader())
                .params(params)
                .addFileParams("file", files)
//                .upJson(json)
                // 请求的 tag, 主要用于取消对应的请求
                .tag(this)
                // 设置当前请求的缓存key,建议每个不同功能的请求设置一个
//                .cacheKey("cacheKey")
                // 缓存模式，详细请看缓存介绍
//                .cacheMode(CacheMode.DEFAULT)
                .execute(new DialogCallback<T>(clazz) {
                    @Override
                    public void onSuccess(Response<T> response) {
                        if (response.code()==200){
                            callback.onSuccess(response.body(), 1);
                        }else {
                            Toast.makeText(activity, response.message(), Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onError(Response<T> response) {
                        super.onError(response);
                        Throwable throwable = response.getException();
                        if (throwable != null) {
                            throwable.printStackTrace();
                            callback.onError(throwable, 2);
                            /**
                             * 友盟+
                             * 使用自定义错误，查看时请在错误列表页面选择【自定义异常】
                             */
                            UMCrash.generateCustomLog("网络请求报错-位置：OKGOBuilder" + throwable, "UmengException");
                        }
                    }
                });

    }

    /**
     * get异步请求
     */
    public void getRequest(Callback<T> callback) {
        long time = System.currentTimeMillis();
        params.put("datetime", time);
        OkGo
                // 请求方式和请求url
                .<T>get(url)
                .headers(getHeader())
                .params(params)
                // 请求的 tag, 主要用于取消对应的请求
                .tag(this)
                // 设置当前请求的缓存key,建议每个不同功能的请求设置一个
//                .cacheKey("cacheKey")
                // 缓存模式，详细请看缓存介绍
//                .cacheMode(CacheMode.DEFAULT)
                .execute(new DialogCallback<T>(clazz) {
                    @Override
                    public void onSuccess(Response<T> response) {
                        if (response.code()==200){
                            callback.onSuccess(response.body(), 1);
                        }else {
                            Toast.makeText(activity, response.message(), Toast.LENGTH_SHORT).show();
                        }

                    }

                    @Override
                    public void onError(Response<T> response) {
                        super.onError(response);
                        Throwable throwable = response.getException();
                        if (throwable != null) {
                            throwable.printStackTrace();
                            callback.onError(throwable, 2);
                        }
                    }
                });

    }

    /**
     * get同步请求
     *
     * @return
     */
    public okhttp3.Response getSynchronization() {
        long time = System.currentTimeMillis();
        params.put("datetime", time);
        try {
            okhttp3.Response execute = OkGo.<String>get(url)
                    .headers(getHeader())
                    .params(params)
                    .tag(this)
                    .execute();
            return execute;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
