package com.unis.model;

import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.exception.HttpException;
import com.lzy.okgo.exception.StorageException;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;
import com.unis.model.event.LoginOutEvent;
import com.xyxsbj.mylibrary.tool.LogTool;
import com.xyxsbj.mylibrary.tool.SPTool;
import com.xyxsbj.mylibrary.tool.StringTool;
import com.xyxsbj.mylibrary.tool.ToastTool;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

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

/**
 * 创建人 mQ
 * 创建时间 2019/7/12 0012 22:18
 * 文件名称 MyStringCallback
 * 说明:
 **/
public abstract class MyStringCallback extends StringCallback {


    @Override
    public void onStart(Request<String, ? extends Request> request) {
        super.onStart(request);
        String token = SPTool.getString(Constant.KEY_HEAD_TOKEN, null);
        if (token != null) {
            request.headers("Authorization", token);
        }

//        CookieStore store = OkGo.getInstance().getCookieJar().getCookieStore();
//        List<Cookie> allCookie = store.getAllCookie();
//        LogTool.d("所有cookie如下：" + allCookie.toString());
    }

    protected abstract void onSuccessResult(Response<String> response) throws JSONException;

    @Override
    public void onSuccess(Response<String> response) {
        String body = response.body();
        if (StringTool.isEmpty(body)) {
            onError(response);
            return;
        }
        try {
            JSONObject object = new JSONObject(body);
            int code = object.optInt("code", -1);
            String msg = object.optString("msg", "");
            if (code == 200 || code == -1) {
                onSuccessResult(response);
            } else if (code == 401) {
                UserModel.get().removeUser();
                EventBus.getDefault().post(new LoginOutEvent(msg));
            } else {
                //其他错误提示信息
                if (!StringTool.isEmpty(msg)) {
                    response.setException(new IllegalStateException(msg));
                    LogTool.i("其他错误--" + msg);
                }
                onError(response);
            }
        } catch (JSONException e) {
            e.printStackTrace();
            if (body.contains("500错误")) {
                response.setException(new IllegalStateException("服务器错误"));
                onError(response);
            } else {
                response.setException(new IllegalStateException("解析错误"));
                onError(response);
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.setException(e);
            onError(response);
        }
    }

    @Override
    public void onError(Response<String> response) {
        LogTool.i("onError");
        Throwable exception = response.getException();
        LogTool.e("onErrorResult: " + exception.getMessage());
        if (exception instanceof UnknownHostException || exception instanceof ConnectException) {
            LogTool.e("网络连接失败,请连接网络");
            ToastTool.showShort("网络连接失败,请连接网络~");
        } else if (exception instanceof SocketTimeoutException) {
            LogTool.e("网络请求超时");
            ToastTool.showShort("网络请求超时~");
        } else if (exception instanceof HttpException) {
            LogTool.e("服务端响应码404和500");
            ToastTool.showShort("服务端响应码404和500~");
        } else if (exception instanceof StorageException) {
            LogTool.e("sd卡不存在或者没有权限");
            ToastTool.showShort("SD卡不存在或者没有权限~");
        } else {
            String errorMsg = getErrorMsg(response);
            LogTool.e("错误信息--" + errorMsg);
            ToastTool.showLong(errorMsg);
        }
        exception.printStackTrace();
        super.onError(response);
    }

    public String getErrorMsg(Response<String> response) {
        LogTool.i("获取错误信息--" + response.getException().toString());
        if (response.getException() != null)
            return response.getException().getMessage();
        else
            return response.message();
    }

    public String getDataJson(String body) throws JSONException {
        JSONObject object = new JSONObject(body);
        return object.optString("data");
    }

    public String getDataJson(Response<String> response) throws JSONException {
        return getDataJson(response.body());
    }

    public String getDataListJson(String body) throws JSONException {
        JSONObject object = new JSONObject(body);
        JSONObject data = object.optJSONObject("data");
        return data.optString("list");
    }


}
