package com.qimai.android.fetch.convert

import android.text.TextUtils
import com.google.gson.Gson
import com.google.gson.JsonSyntaxException
import com.google.gson.TypeAdapter
import com.qimai.android.fetch.interceptors.GsonParseError
import com.qimai.android.fetch.interceptors.ServerError
import com.qimai.android.fetch.interceptors.TokenExpire
import com.qimai.android.fetch.model.BaseData
import okhttp3.ResponseBody
import retrofit2.Converter
import java.io.IOException
import java.lang.reflect.Type

/**
 *   created by wangwei   ON 2019-09-04  email:wangwei_5521@163.com
 *   @version 1.1.1
 *   @Description
 *   @param gsonParseError gson解析异常
 *  @param serverError 服务器返回的false
 *
 **/
class StandardGsonResponseBodyConverter<T> constructor(
    var adapter: TypeAdapter<T>,
    var gson: Gson,
    var type: Type,
    var expire: TokenExpire?
) :
    Converter<ResponseBody, T> {

    override fun convert(value: ResponseBody): T? {
        val reponseString = value.string()
        //  throw  TOKENExpireException("token过期")

        val baseData = gson.fromJson<BaseData<*>>(reponseString, BaseData::class.java)
        if (TextUtils.equals("false", baseData.status)) {
            value.close()
            if (baseData.code == 9001L) {
                //这里如果先结束
                expire?.let {
                    it.expre()
                }
                throw  TOKENExpireException("登录超时", reponseString)

            } else {
                throw BizException(baseData?.message ?: "操作失败", baseData.code, reponseString)
            }
        } else {
            try {
                return when {
                    TextUtils.equals(baseData.data.toString(), "[]") -> {
                        baseData as T
                    }
                    else -> {
                        gson.fromJson<BaseData<*>>(reponseString, type) as T
                    }
                }
            } catch (t: JsonSyntaxException) {
                //json解析异常
                throw GsonParseErrorException(t.message, reponseString)
            } catch (t: Throwable) {
                throw ServerResponseException(t.message, reponseString)
            } finally {
                value.close()
            }
        }
    }
}

class ServerResponseException(msg: String?, var responseMsg: String? = null) : IOException(msg)

// 业务返回问题
class BizException(msg: String, var code: Long = 0, var responseMsg: String? = null) :
    IOException(msg)

class TOKENExpireException(msg: String, var responseMsg: String? = null) : IOException(msg)
class GsonParseErrorException(msg: String? = null, var responseMsg: String? = null) :
    IOException(msg)