package com.gingersoft.gsa.cloud.common.config.globalconfig.applyOptions;

import android.app.Activity;
import android.content.Context;
import android.net.ParseException;
import android.text.TextUtils;

import com.gingersoft.gsa.cloud.common.core.user.UserContext;
import com.gingersoft.gsa.cloud.common.R;
import com.gingersoft.gsa.cloud.app.GsaCloudApplication;
import com.gingersoft.gsa.cloud.common.utils.toast.ToastUtils;
import com.gingersoft.gsa.cloud.common.logan.LoganManager;
import com.google.gson.JsonIOException;
import com.google.gson.JsonParseException;
import com.jess.arms.utils.ArmsUtils;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;

import org.json.JSONException;

import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

import me.jessyan.rxerrorhandler.handler.listener.ResponseErrorListener;
import retrofit2.HttpException;
import timber.log.Timber;


public class MyResponseErrorListener implements ResponseErrorListener {

    private final String TAG = getClass().getSimpleName();

    private boolean showloggedDialog = false;

    @Override
    public void handleResponseError(Context context, Throwable t) {
        /* 用来提供处理所有错误的监听rxjava必要要使用ErrorHandleSubscriber(默认实现Subscriber的onError方法),此监听才生效 */
        Timber.tag("Catch-Error").w(t.getMessage());
        //这里不光是只能打印错误,还可以根据不同的错误作出不同的逻辑处理
        String msg = ArmsUtils.getString(context, R.string.response_error_unknown_error);
        if (t instanceof UnknownHostException) {
            msg = ArmsUtils.getString(context, R.string.response_error_network_unavailable);
        } else if (t instanceof SocketTimeoutException) {
            msg = ArmsUtils.getString(context, R.string.response_error_request_timeout);
        } else if (t instanceof HttpException) {
            HttpException httpException = (HttpException) t;
            msg = convertStatusCode(context, httpException);
        } else if (t instanceof JsonParseException || t instanceof ParseException || t instanceof JSONException || t instanceof JsonIOException) {
            msg = ArmsUtils.getString(context, R.string.response_error_data_parsing_error);
        }
//        ArmsUtils.snackbarText(msg);
//        LogUtil.d("handleResponseError: " + t.getMessage());

        LoganManager.w_code(TAG,"請求錯誤:  "+t.getMessage());

        if (!TextUtils.isEmpty(msg)) {
            ToastUtils.show(context, msg);
        }
    }

    private String convertStatusCode(Context context, HttpException httpException) {
        String msg = null;
        if (httpException.code() == 500) {
            msg = ArmsUtils.getString(context, R.string.response_error_server_error);
        } else if (httpException.code() == 404) {
            msg = ArmsUtils.getString(context, R.string.response_error_address_does_not_exist);
        } else if (httpException.code() == 403) {
            msg = ArmsUtils.getString(context, R.string.response_error_request_rejected_by_server);
        } else if (httpException.code() == 307) {
            msg = ArmsUtils.getString(context, R.string.response_error_request_was_redirected_to_another_page);
        } else if (httpException.code() == 401) {
            Activity activity = GsaCloudApplication.getAppContext().getCurrentActivity();
//            if (!showloggedDialog && activity != null) {
            if (activity != null) {
                showloggedDialog = true;
                showloggedDialog(activity, ArmsUtils.getString(context, R.string.response_error_request_logged));
            }
        } else {
//            if (httpException.code() == 400) {
//                //Bad Request
//                Activity activity = GsaCloudApplication.getAppContext().getCurrentActivity();
//                if (activity == null || !activity.getClass().getSimpleName().equals("LoginActivity")) {
//                    //不处于登录页面  返回到登录页
//                    ArmsUtils.killAll();
//                    toLoginActivity(activity);
//                }
//            }
            msg = httpException.message();
        }
        return msg;
    }

    private void showloggedDialog(Activity context, String msg) {
        QMUIDialog.MessageDialogBuilder dialogBuilder = new QMUIDialog.MessageDialogBuilder(context);
        dialogBuilder.setMessage(msg);
        dialogBuilder.setTitleIcon(R.drawable.qmui_icon_dialog_warn);
        dialogBuilder.addAction(0, "確認", QMUIDialogAction.ACTION_PROP_NEGATIVE, (dialog, index) -> {
            toLoginActivity(context);
            dialog.dismiss();
        });
        dialogBuilder.setCancelable(false);
        dialogBuilder.setCanceledOnTouchOutside(false);
        dialogBuilder.create(R.style.MyDialogTheme2).show();
    }

    private void toLoginActivity(Activity context) {
        ArmsUtils.killAll();

        UserContext.newInstance().logOut();
//        //清空用戶信息
//        GsaCloudApplication.clearMemberInfo();
//        //修改登錄狀態
//        GsaCloudApplication.isLogin = false;
//        //清空堂食訂單信息
//        CC.obtainBuilder("Component.Base.Order")
//                .setActionName("clearDoshokuOrder")
//                .build()
//                .call();
//        //跳轉登錄頁面
//        CC.obtainBuilder(ComponentName.COMPONENT_LOGIN)
//                .setActionName(ComponentAction.Login.OPEN_LOGIN)
//                .build()
//                .call();
        showloggedDialog = false;
        context.finish();
    }

}
