package com.fq.channel.sdk.base.net.callback;

import android.text.TextUtils;

import com.fq.channel.sdk.base.exception.BaseException;
import com.fq.channel.sdk.base.net.HttpConstant;
import com.fq.channel.sdk.base.net.result.ResultHeader;
import com.fq.channel.sdk.base.utils.FqLog;
import com.fq.threelib.gson.Gson;
import com.fq.threelib.okhttp3.Call;
import com.fq.threelib.okhttp3.Callback;
import com.fq.threelib.okhttp3.Response;

import org.json.JSONObject;

import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * @Description:
 * @Author: FLuty
 * @CreateDate: 2020/4/2 11:30
 */
public abstract class BaseCallback<T> implements Callback {
    private static final String TAG = "FQSDKBaseCallback";

    @Override
    public void onFailure(Call call, IOException e) {
        FqLog.e(TAG, "请求失败：" + "i=" + e.getMessage());
        onFailure(new BaseException(HttpConstant.HTTP_CODE_ERROR,e.getMessage()));
    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {
        String body = response.body().string();
        if (response.isSuccessful()){
            FqLog.i(TAG, "请求成功：" + "i=" +body );
            try {
                JSONObject jsonObject = new JSONObject(body);
                String head = jsonObject.optString(HttpConstant.KEY_RESPONSE_HEAD);
                ResultHeader resultHeader =  new Gson().fromJson(head, ResultHeader.class);
                if (resultHeader!=null&&resultHeader.getResponseCode().equals("00000")){
                    successParseJson(jsonObject.optString(HttpConstant.KEY_RESPONSE_BODY));
                }else {
                    onFailure(new BaseException(HttpConstant.HTTP_NET_ERROR,resultHeader.getResponseMsg()));
                }
            } catch (Exception e) {
                e.printStackTrace();
                onFailure(new BaseException(HttpConstant.HTTP_NET_ERROR,HttpConstant.HTTP_MSG_PARSE_ERROR));
            }
        }else{
            FqLog.e(TAG, "请求失败：" + "i=" +body );
            onFailure(new BaseException(HttpConstant.HTTP_NET_ERROR,HttpConstant.HTTP_MSG_PARSE_ERROR));
        }

    }

    /**
     * 请求成功解析数据
     *
     * @param resultData
     */
    protected void successParseJson(String resultData) {
        T data = null;
        try {
            //获取泛型类型
            Type genericSuperclass = this.getClass().getGenericSuperclass();
            Type type = null;
            //有泛型参数时，genericSuperclass 是 ParameterizedType类型； 否则为 class
            if (genericSuperclass instanceof ParameterizedType){
                type = ((ParameterizedType) genericSuperclass).getActualTypeArguments()[0];
            }
            if (type == null) {
                data = (T) resultData;
            } else {
                String typeName = type.toString();
                if (!TextUtils.isEmpty(typeName)) {
                    String[] name = typeName.split(" ");
                    if (name.length > 1) {
                        typeName = name[1];
                    }
                }
                if (Byte.class.getName().equals(typeName) || Short.class.getName().equals
                        (typeName) || Integer.class.getName().equals(typeName) || Long.class.getName
                        ().equals(typeName) || Float.class.getName().equals(typeName) || Double
                        .class.getName().equals(typeName) || Character.class.getName().equals
                        (typeName) || Boolean.class.getName().equals(typeName) || String.class
                        .getName().equals(typeName)) {
                    data = (T) resultData;
                } else {
                    data = (T) new Gson().fromJson(resultData, type);
                }
            }
            FqLog.d(TAG, " data.className: " + (data != null ? data.getClass().getSimpleName(): "null"));
        } catch (Exception e) {
            onFailure(new BaseException(HttpConstant.HTTP_DATA_ERROR, HttpConstant.HTTP_MSG_PARSE_ERROR));
            return;
        }
        //解析映射成功,返回成功
        onSuccess(HttpConstant.HTTP_CODE_SUCCEED, "OK", data);
    }


    public abstract void onFailure(BaseException msg);

    public abstract void onSuccess(int code, String msg, T data);
}
