package com.renrenliao.im.http;

import android.util.Log;

import com.google.gson.Gson;

import com.google.gson.JsonObject;
import com.google.gson.TypeAdapter;
import com.renrenliao.im.bean.AppConfigEntity;
import com.renrenliao.im.bean.LineEntity;
import com.renrenliao.im.provider.ClarityPotion;
import com.renrenliao.im.ui.activity.SplashActivity;
import com.renrenliao.im.utils.DataCacheUtils;
import com.renrenliao.im.utils.Des3Util;
import com.renrenliao.im.utils.RouteUtils;
import com.renrenliao.im.utils.StringUtils;

import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import okhttp3.ResponseBody;
import retrofit2.Converter;

import org.apache.commons.lang3.StringEscapeUtils;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * *@ClassName MyGsonResponseBodyConverter
 * *@Description
 * *@Author gan
 * *@Date 2022/5/25 11:39
 **/
public class MyGsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {
    private static final String TAG = MyGsonResponseBodyConverter.class.getSimpleName();

    private final Gson gson;
    private final TypeAdapter<T> adapter;

    MyGsonResponseBodyConverter(Gson gson, TypeAdapter<T> adapter) {
        this.gson = gson;
        this.adapter = adapter;
    }

    @Override
    public T convert(ResponseBody responseBody) throws IOException {

        String strResponse = responseBody.string();
        Log.i(TAG, "返回的response:" + strResponse);

        BaseResult<String> baseResult = gson.fromJson(strResponse, BaseResult.class);
        BaseResult<Object>  bO = new BaseResult<Object>(baseResult.getCode(), baseResult.getMsg(),null,baseResult.getOK());
    //    Log.i(TAG, "返回的baseResult:" + gson.toJson(baseResult));

        //5001 登录信息已过期，请重新登录  500 参数校验不通过
        if (baseResult.getCode() == 5001){
            DataCacheUtils.isLogin = false;
            DataCacheUtils.INSTANCE.clearUserInfo();
            RouteUtils.INSTANCE.exitAndLogin();
        }
        //解密操作
        String decryptString;
        if (baseResult.getData() != null) {
            try {
                decryptString = Des3Util.decode(baseResult.getData());
                Log.i(TAG, "解密data: " + decryptString);
                baseResult.setData(decryptString);
                Object object = gson.fromJson(decryptString,Object.class);
                Log.i(TAG, "替换的baseResult:" + gson.toJson(baseResult));
                bO.setData(object);
             //   bO = new BaseResult<Object>(baseResult.getCode(), baseResult.getMsg(), object,baseResult.getOK());
        //        Log.i(TAG, "替换的baseObject:" + gson.toJson(bO));

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        try{
            //判断是否是线路配置文件返回
            if (baseResult.getMsg()==null&&baseResult.getData()==null&&baseResult.getOK()==null){
                LineEntity lineEntity = gson.fromJson(strResponse,LineEntity.class);
                if (!StringUtils.isEmpty(lineEntity.getName())){
                    return adapter.fromJson(strResponse);
                }
            }
            //判断是否是配置entity 因为   "iosUpdateContent":"[修复]1、修复闪退#@2、修复部分手机流畅度", 不号过滤
            if (ClarityPotion.Companion.currentActivity() instanceof SplashActivity){
                AppConfigEntity appConfigEntity = gson.fromJson(baseResult.getData(),AppConfigEntity.class);
                if (!StringUtils.isEmpty(appConfigEntity.getWithdrawMinAmount())){
                    return adapter.fromJson(gson.toJson(bO));
                }
            }

            String json = gson.toJson(baseResult);
            json = StringEscapeUtils.unescapeJava(json);
            json = json.replace("\"{","{");
            json = json.replace("}\"","}");
            json = json.replace("\"[{","[{");
            json = json.replace("}]\"","}]");
            json = json.replace("\"[","[");
            json = json.replace("]\"","]");
            Log.i(TAG, "xx:" + json);
            return adapter.fromJson(json);
    //        return adapter.fromJson(gson.toJson(bO));
        }finally {
            responseBody.close();
        }
    }

//    /**
//     * String转Reader
//     *
//     * @param json
//     * @return
//     */
//    private Reader StringToReader(String json) {
//        Reader reader = new StringReader(json);
//        return reader;
//    }

}