package com.bxzk.afxj.retrofit;


import com.bxzk.afxj.BuildConfig;
import com.bxzk.afxj.application.BApplication;
import com.bxzk.afxj.util.Log;
import com.bxzk.afxj.util.MD5Util;
import com.bxzk.afxj.util.SPUtils;

import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.convert.AnnotationStrategy;
import org.simpleframework.xml.core.Persister;
import org.simpleframework.xml.strategy.Strategy;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.simplexml.SimpleXmlConverterFactory;

public class ApiManager {
    private Retrofit retrofit;
    private MyRetrofitService mYunxApi;
    private MyXmlRetroService mXmlApi;
    private static ApiManager sApiManager;
    private RxDownloadListener listener;
    //测试环境


    public static final String URL_MAIN = BuildConfig.API_URL;//内网 其他接口
    public static final String URL_WEBSER = BuildConfig.API_URL;//webservice
    private final OkHttpClient client;


    //获取ApiManager的单例
    public static ApiManager getInstence() {
        if (sApiManager == null) {
            synchronized (ApiManager.class) {
                if (sApiManager == null) {
                    sApiManager = new ApiManager();
                }
            }
        }
        return sApiManager;
    }

    private ApiManager() {
        this.listener = listener;
        interceptor.setLevel(HttpLoggingInterceptor.Level.HEADERS);
        RxDownloadInterceptor mInterceptor = new RxDownloadInterceptor(listener);
        //不需要使用拦截器就不创建
        client = new OkHttpClient.Builder()
                //添加应用拦截器
//                .addInterceptor(mInterceptor)
//                .addInterceptor(new BaseUrlInterceptor())
                .addInterceptor(interceptor)

                //添加网络拦截器
//                .addNetworkInterceptor(new MyOkhttpInterceptor())
//                .connectTimeout(5000, TimeUnit.MILLISECONDS)
//                .readTimeout(10000, TimeUnit.MILLISECONDS)
                .build();


        //到这一步创建完成
    }

    private Retrofit initRetrofit(String baseUrl) {
        interceptor.setLevel(HttpLoggingInterceptor.Level.HEADERS);
        retrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .client(client)

                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        return retrofit;
    }
    private Retrofit initRetrofitByXml(String baseUrl) {
        Strategy strategy = new AnnotationStrategy();
        Serializer serializer = new Persister(strategy);
        interceptor.setLevel(HttpLoggingInterceptor.Level.HEADERS);
        retrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(SimpleXmlConverterFactory.create(serializer))
                .build();
        return retrofit;
    }

    public Retrofit getRetrofit(String baseUrl) {
        return retrofit;
    }


    /**
     * 有参数的请求头
     *
     * @return
     */
    public OkHttpClient generiClient() {
        OkHttpClient httpClient = null;
        try {
            try {
                httpClient = new OkHttpClient.Builder()
                        .addInterceptor(new Interceptor() {
                            @Override
                            public okhttp3.Response intercept(Chain chain) throws IOException {
                                Request request = chain.request()
                                        .newBuilder()
//                                        .addHeader("apiCode", "kangwen")//账号测试环境
                                        .addHeader("apiCode", "LiveApi@Android")//账号
//                                        .addHeader("apiKey", "123456")//密码测试环境
                                        .addHeader("apiKey", "1bb3659eeb606deb")//密码
                                        .addHeader("timeSpan", "20181105")//当前时间戳
                                        .addHeader("sign", getsign())
                                        .addHeader("Authorization", (String) SPUtils.get(BApplication.getContext(), "token", "eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2tleSI6Ijg1OGYyOTY3LTJlOTAtNGI4YS1iNTYyLTQ4OThkZWE2ZjgxYiJ9.1jBWUPhCcI_jGBLwvo9whT9TCBdvqOzZ2zPIoVAVssm6xkEvoERdzlYVGb8aE65er9uHIzuBFQikBgrb7NlESA"))
                                        .build();
                                return chain.proceed(request);
                            }
                        })

//                      .addInterceptor(myOkHttpRetryInterceptor)
//                        .connectTimeout(5000, TimeUnit.MILLISECONDS)
//                        .readTimeout(10000, TimeUnit.MILLISECONDS)
                        .build();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return httpClient;
    }

    public String getsign() {
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("LiveApi@Android");
//        stringBuffer.append("kangwen");
//        stringBuffer.append("123456");
        stringBuffer.append("1bb3659eeb606deb");
        stringBuffer.append("20181105");
        return MD5Util.MD5(stringBuffer.toString());
    }



    /**
     * 封装配置
     */
    public MyRetrofitService getYunxService() {

        Retrofit retrofit = initRetrofit(URL_MAIN);
        if (mYunxApi == null) {
            mYunxApi = retrofit.create(MyRetrofitService.class);
        }
        return mYunxApi;
    }

    /**
     * 封装配置
     */
    public MyXmlRetroService getXmlService() {

        Retrofit retrofit = initRetrofitByXml(URL_WEBSER);
        if (mYunxApi == null) {
            mXmlApi = retrofit.create(MyXmlRetroService.class);
        }
        return mXmlApi;
    }


    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
        @Override
        public void log(String message) {
            try {
                String text = URLDecoder.decode(message, "utf-8");
                Log.e(text);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                Log.e("zhang_xin", message);
            }
        }


    });
}
