package com.beanpodtech.allinone.utils;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.util.Log;

import androidx.appcompat.app.AlertDialog;

import com.beanpodtech.allinone.BuildConfig;
import com.beanpodtech.allinone.R;
import com.beanpodtech.allinone.activity.LoginActivity;
import com.beanpodtech.allinone.bean.BaseRequestBean;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.model.Response;

import okhttp3.RequestBody;

public class OkGoBuilder<T> {
    private int requestId;
    /**
     * get请求
     */
    public static final int GET = 1;
    /**
     * post请求
     */
    public static final int PSOT = 2;


    private Activity activity;
    /**
     * 请求网址
     */
    private String url;
    /**
     * 参数
     */
    private RequestBody body;
    /**
     * 实体类
     */
    private Class<T> clazz;
    /**
     * 回调
     */
    private OkGoUtil<T> callback;

    private int methodType;

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

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

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


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

    public OkGoBuilder RequestId(int requestId) {
        this.requestId = requestId;
        return this;
    }

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

    public OkGoBuilder method(int methodType) {
        this.methodType = methodType;
        return this;
    }

    public OkGoBuilder requestBody(RequestBody body) {
        this.body = body;
        return this;
    }

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

    public OkGoBuilder callback(OkGoUtil<T> callback) {
        this.callback = callback;
        return this;
    }


    public OkGoBuilder build() {
//        if (methodType == 1) {
//            getRequest();
//        } else {
        postRequest();
//        }
        return this;
    }

    public OkGoBuilder cancle() {
        OkGo.getInstance().cancelTag(this);
        return this;
    }

    /**
     * post请求
     */
    private void postRequest() {
        OkGo.getInstance()
                // 请求方式和请求url
                .<T>post(url)
                .upRequestBody(body)
                // 请求的 tag, 主要用于取消对应的请求
                .tag(this)
                // 设置当前请求的缓存key,建议每个不同功能的请求设置一个
//                .cacheKey("cacheKey")
                // 缓存模式，详细请看缓存介绍
                .cacheMode(CacheMode.DEFAULT)
                .execute(new OkGoUtil<T>(clazz) {
                    @Override
                    public void onSuccess(Response<T> response) {
                        T body = response.body();
                        if (body instanceof BaseRequestBean) {
                            if (((BaseRequestBean) body).getStatus() == -1) {

                                if (url.contains("pollCheckLogin")) {
                                    callback.onSuccess(response);
                                    if (BuildConfig.DEBUG) {
                                        Log.d("BOX===", "SUCCESS " + response.code() + " " + url + " " + new Gson().toJson(response.body()));
                                    }
                                    return;
                                }
                                // TODO: 2020/6/1 否则提示设备不可用 请重新登录
//                                ToastUtils.show(activity, "请重新登录");
                                AlertDialog alertDialog = new AlertDialog.Builder(activity)
                                        .setTitle(R.string.login)
                                        .setMessage(R.string.login_error)
                                        .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {//添加"Yes"按钮
                                            @Override
                                            public void onClick(DialogInterface dialogInterface, int i) {
                                                Intent intent = new Intent(activity, LoginActivity.class);
                                                activity.startActivity(intent);
                                                activity.finish();
                                            }
                                        })
                                        .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {//添加取消
                                            @Override
                                            public void onClick(DialogInterface dialogInterface, int i) {
                                            }
                                        })
                                        .create();
                                try {
                                    if (!activity.isFinishing()) {
                                        alertDialog.show();
                                    }
                                } catch (Exception ignored) {
                                }
                            } else {
                                callback.onSuccess(response);
                            }
                        } else {
                            callback.onError(response);
//                            callback.onSuccess(response);
                        }
                        if (BuildConfig.DEBUG) {
                            Log.d("BOX===", "SUCCESS " + response.code() + " " + url + " " + new Gson().toJson(response.body()));
                        }
                    }

                    @Override
                    public void onError(Response<T> response) {
                        super.onError(response);
                        Throwable throwable = response.getException();
                        if (throwable != null) {
                            throwable.printStackTrace();
                            callback.onError(response);
                        }
                        if (BuildConfig.DEBUG) {
                            Log.d("BOX===", "ERROR " + response.code() + " " + url + " " + new Gson().toJson(response.body()));
                        }
                    }

                });
    }

//    /**
//     * get请求
//     */
//    private void getRequest() {
//        OkGo
//                // 请求方式和请求url
//                .<T>get(url)
//                .(body)
//                // 请求的 tag, 主要用于取消对应的请求
//                .tag(this)
//                // 设置当前请求的缓存key,建议每个不同功能的请求设置一个
////                .cacheKey("cacheKey")
//                // 缓存模式，详细请看缓存介绍
//                .cacheMode(CacheMode.DEFAULT)
//                .execute(new DialogCallback<T>(activity, clazz) {
//                    @Override
//                    public void onSuccess(Response<T> response) {
//                        callback.onSuccess(response);
//                    }
//
//                    @Override
//                    public void onError(Response<T> response) {
//                        super.onError(response);
//                        Throwable throwable = response.getException();
//                        if (throwable != null) {
//                            throwable.printStackTrace();
//                            callback.onError(response);
//                        }
//                    }
//
//                });
//    }
}
