package com.bbitcn.silk.utils.network;

import android.app.Activity;
import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import com.bbitcn.silk.model.net.CommonResponse;
import com.bbitcn.silk.utils.log.MyLog;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.GsonUtils;

import org.json.JSONException;
import org.xutils.common.Callback;
import org.xutils.ex.HttpException;

import java.lang.reflect.ParameterizedType;
import java.net.UnknownHostException;

/**
 * @Author：BinJianXin
 * @Date：2022/5/30/9:49
 * @Declaration：用于减少逻辑界面xhttp需要实现的方法数
 */
public abstract class XHttpShorthand<T> implements Callback.CommonCallback<String> {

    public abstract void success(T result) throws JSONException;

    private Class<T> clazz;

    public XHttpShorthand() {
        try {
            ParameterizedType genericSuperclass = (ParameterizedType) getClass().getGenericSuperclass();
            clazz = (Class<T>) genericSuperclass.getActualTypeArguments()[0];
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public abstract void error(Throwable e);

    @Override
    public void onSuccess(String result) {
        MyLog.network("网络请求成功：" + result);
        Message message = new Message();
        try {
            CommonResponse temp = GsonUtils.fromJson(result, CommonResponse.class);
            MyLog.network("已转为通用请求内容");
            if (temp != null) {
//                MyLog.network("Code == 200");
                message.what = 0;
                message.obj = GsonUtils.fromJson(result, clazz);
            } else {
//                MyLog.network("Code != 200");
                message.what = 2;
                message.obj = temp;
            }
        } catch (Exception e) {
            message.what = 1;
            message.obj = e;
        }
        handler.sendMessage(message);
    }

    public void onSuccessError(CommonResponse data) {

    }

    @Override
    public void onError(Throwable ex, boolean isOnCallback) {
        MyLog.networkError("网络请求失败：错误消息：" + ex.getMessage() + "\t本地化消息：" + ex.getLocalizedMessage() + "\t原因：" + ex.getCause());
        if(ex instanceof UnknownHostException){
            //修改ex.getMessage()为"网络连接失败，请检查网络连接" 友好型提示
            ex = new Throwable("网络连接失败，请检查网络连接");
        }
//        if (401 == ((HttpException) ex).getCode()) {
//            MyLog.networkError("未授权");
//            //跳转到登录界面
//            Activity topActivity = ActivityUtils.getTopActivity();
//            ActivityUtils.startActivities(new Intent[]{new Intent(topActivity, LoginActivity.class)});
//            topActivity.finish();
//        } else {
            Message message = new Message();
            message.what = 1;
            message.obj = ex;
            handler.sendMessage(message);
//        }
    }

    @Override
    public void onCancelled(CancelledException cex) {
        MyLog.network("网络请求取消" + cex.getMessage());
    }

    @Override
    public void onFinished() {
        Message message = new Message();
        message.what = 3;
        handler.sendMessage(message);
    }

    public void myFinish() {
        MyLog.network("网络请求完成");
    }

    /**
     * 转回到主线程
     */
    public Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@androidx.annotation.NonNull Message msg) {
            super.handleMessage(msg);
            try {
                if (msg.what == 0) {
                    success((T) msg.obj);
                } else if (msg.what == 1) {
                    error((Throwable) msg.obj);
                } else if (msg.what == 2) {
                    onSuccessError((CommonResponse) msg.obj);
                } else if (msg.what == 3) {
                    myFinish();
                }
            } catch (Exception e) {
                MyLog.networkError("网络请求错误：" + e.getMessage());
            }
        }
    };
}