package com.yutou.common.okhttp.api;

import com.alibaba.fastjson2.JSONObject;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.internal.bind.DateTypeAdapter;
import com.yutou.common.okhttp.HttpLoggingInterceptor;
import com.yutou.common.okhttp.ParamsContext;
import com.yutou.common.okhttp.converter.JsonCallAdapter;
import com.yutou.common.okhttp.converter.JsonConverterFactory;
import okhttp3.*;
import retrofit2.CallAdapter;
import retrofit2.Converter;
import retrofit2.Retrofit;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;

public class BaseApi {
    private String URL;
    private HashMap<String, String> params = new HashMap<>();
    private HashMap<String, String> headers = new HashMap<>();

    public BaseApi(String URL) {
        this.URL = URL;
    }

    public BaseApi setURL(String URL) {
        this.URL = URL;
        return this;
    }

    public BaseApi setHeaders(HashMap<String, String> headers) {
        this.headers = headers;
        return this;
    }
    public void addHeader(HashMap<String,String> headers){
        this.headers.putAll(headers);
    }


    public BaseApi setParams(HashMap<String, String> params) {
        this.params = params;
        return this;
    }
    public void useCookie(JSONObject json){
        StringBuilder ck = new StringBuilder();
        json.remove("sql_time");
        json.remove("gourl");
        for (String key : json.keySet()) {
            ck.append(key).append("=").append(json.getString(key)).append(";");
        }
        headers.put("Cookie", ck.toString());
        setHeaders(headers);
    }

    /**
     * 创建一个接口方法
     *
     * @param okHttpClient       okhttp客户端
     * @param converterFactory   处理工厂类
     * @param callAdapterFactory 请求适配器工厂
     * @param baseUrl            基础地质
     * @param service            接口
     * @param <T>                接口泛型
     * @return 接口
     */
    public <T> T create(OkHttpClient okHttpClient, Converter.Factory converterFactory, CallAdapter.Factory callAdapterFactory, String baseUrl, Class<T> service) {
        Retrofit.Builder builder = new Retrofit.Builder()
                //基础url
                .baseUrl(baseUrl)
                //客户端OKHttp
                .client(okHttpClient);
        //添加转换工厂
        if (null != converterFactory) {
            builder.addConverterFactory(converterFactory);
        }
        //添加请求工厂
        if (null != callAdapterFactory) {
            builder.addCallAdapterFactory(callAdapterFactory);
        }
        //创建retrofit对象
        Retrofit retrofit = builder.build();

        //返回创建的api
        return retrofit.create(service);
    }

    public <T> T createApi(Class<T> apiClass) {
        Gson gson = new GsonBuilder()
                .registerTypeAdapter(Date.class, new DateTypeAdapter())
                .create();
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor("http");
        loggingInterceptor.setPrintLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient.Builder builder = new OkHttpClient()
                .newBuilder()
                .addInterceptor(initQuery())
                .addInterceptor(loggingInterceptor);

        return create(builder.build(),
                JsonConverterFactory.create(gson),
                JsonCallAdapter.create(),
                URL,
                apiClass);
    }

    public Interceptor initQuery() {
        Interceptor addQueryParameterInterceptor = new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request request = chain.request();
                //配置公共参数
                request = new ParamsContext(headers, params, request).getInRequest();
                return chain.proceed(request);
            }
        };
        return addQueryParameterInterceptor;
    }
}
