package com.baoshi.swms.net.callback;
import android.text.TextUtils;
import android.util.Log;

import androidx.annotation.NonNull;

import com.baoshi.swms.App;
import com.baoshi.swms.util.Hint;
import com.baoshi.swms.util.NetUtil;
import com.google.gson.Gson;

import org.json.JSONObject;

import okhttp3.ResponseBody;

/**
 * WAS
 * 统一处理的逻辑，都在类似这样的方法中处理。暴露在每个最外层的callback只处理指定场景下的业务逻辑。
 *
 * @author Zhendong Zhou
 * @date   2021/12/3 15:48
 */
public abstract class SwmsHandlerCallback<T> extends NetCallback<T> {
    @Override
    public void onNext(@NonNull ResponseBody body) {
        try {
            String result = body.string();
            //Log.e("e","响应数据为:"+result);
            JSONObject jsonObject = new JSONObject(result);
            int resultCode = jsonObject.getInt("code");
            if (resultCode == 200) {
                Gson gson = new Gson();
                String data = jsonObject.getString("data");
                if (!TextUtils.isEmpty(data)) {
                    T t = gson.fromJson(data, getType());
                    onSuccess(t);
                }
            } else {
                String errorMsg = jsonObject.getString("message");
                onFault(0, errorMsg);
            }
        } catch (Exception e) {
            e.printStackTrace();
            onError(e);
        }
    }

    @Override
    public void logout(){
    }

    @Override
    public void onFault(int code, String errorMsg) {
        super.onFault(code,errorMsg);
        if (code==0){
            Hint.toastShort(App.getAppContext(), errorMsg, Hint.COMMON);
        }
    }

    @Override
    public void onError(Throwable e) {
        super.onError(e);
        e.printStackTrace();
        if (NetUtil.isNetworkConnected(App.getAppContext())){
            Hint.toastShort(App.getAppContext(), "内部服务器错误", Hint.ERROR);
        }else{
            Hint.toastShort(App.getAppContext(),"网络连接失败",Hint.COMMON);
        }
    }
}
