package com.bxzk.afxj.retrofit;


import com.google.gson.Gson;
import com.bxzk.afxj.Entity.BaseListBean;
import com.bxzk.afxj.Entity.BaseResponse;
import com.bxzk.afxj.Entity.BaseResponse1;
import com.bxzk.afxj.util.Log;

import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.ObservableSource;
import io.reactivex.ObservableTransformer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

public class ModelFilteredFactory {
    //    private final static Observable.Transformer transformer ;
    private final static ObservableTransformer transformer = new SampleTransformer();
    private final static ObservableTransformer transformer1 = new SampleTransformer1();
    private static ObservableTransformer transformer2 = new SampleTransformer2();

    @SuppressWarnings("unchecked")
    public static Observable compose(Observable observable) {
        return observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .unsubscribeOn(Schedulers.io())
                .timeout(5, TimeUnit.SECONDS)//重连间隔时间
                .retry(5);//重连次数;
    }

    public static <T>Observable<T> simpleCompose(Observable<T> observable) {
        return observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .unsubscribeOn(Schedulers.io());
    }
    public static <T>Observable<T> simpleCompose1(Observable<T> observable) {
        return observable.subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .unsubscribeOn(AndroidSchedulers.mainThread());
    }
    public static <T>Observable<T> simpleCompose2(Observable<T> observable) {
        return observable.subscribeOn(Schedulers.io())
                .observeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io());
    }


    public static <T> Observable<T> compose1(Observable<T> observable) {
        return observable.compose(transformer1);
    }

    public static <T> Observable<T> compose2(Observable<BaseResponse<T>> observable) {
        return observable.compose(transformer);
    }

    //代理字段变动，不得已改框架。。。
    public static <T> Observable<T> compose3(Observable<BaseResponse1<T>> observable) {
        return observable.compose(transformer2);
    }

    /**
     * 这个类的意义就是转换Observable.
     */
    private static class SampleTransformer2<T> implements ObservableTransformer<BaseResponse1<T>, T> {
        //这里对Observable,进行一般的通用设置.不用每次用Observable都去设置线程以及重连设置

        @Override
        public Observable<T> apply(final  Observable<BaseResponse1<T>> observable) {
            return observable.subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .unsubscribeOn(Schedulers.io())
                    .timeout(5, TimeUnit.SECONDS)//重连间隔时间
                    .retry(5)//重连次数
                    .doOnNext(tBaseResponse1 -> {

                    })
                    .flatMap(new Function<BaseResponse1<T>, Observable<T>>() {
                        @Override
                        public Observable<T> apply(BaseResponse1<T> tBaseResponse) throws Exception {
                            return flatResponse2(tBaseResponse);
                        }
                    });

        }
        /**
         * 处理请求结果,BaseResponse<T>
         *
         * @param response 请求结果
         * @return 过滤处理, 返回只有data数据的Observable
         */
        private Observable flatResponse2(final BaseResponse1<T> response) {
            if(response.getData() == null) {
                return Observable.create(new ObservableOnSubscribe<Object>() {
                    @Override
                    public void subscribe(ObservableEmitter<Object> emitter) throws Exception {
                        if(response.getCode() == 200) {
                            emitter.onError(new ApiException(response.getCode(), "数据为空"));
                            emitter.onComplete();
                        }else {
                            emitter.onError(new ApiException(response.getCode(), response.getMassage()));
                            emitter.onComplete();
                        }
                    }
                });
            }else{
                return Observable.create(new ObservableOnSubscribe<T>() {
                    @Override
                    public void subscribe(ObservableEmitter emitter) throws Exception {
                        if (response.isSuccess()) {//请求成功
                            if (!emitter.isDisposed()) {
                                T data = response.getData();
                                Gson gson = new Gson();
                                Log.e("code:"+response.getPageIndex()+response.getCount()+"getPageCount:"+response.getPageCount()+response.getRecordCount());
                                BaseListBean bean = new BaseListBean();
                                bean.setCount(response.getCount());
                                bean.setPageCount(response.getPageCount());
                                bean.setPageIndex(response.getPageIndex());
                                bean.setRecordCount(response.getRecordCount());
                                emitter.onNext(bean);
                                if(data != null ) {
                               /* Gson gson1 = new Gson();
                                String paramLoginStr = gson1.toJson(data)
                                        .replace("null","");
                                T t1 = gson1.fromJson(paramLoginStr, (Class<T>) data.getClass());*/
                                    if(data instanceof List) {
                                        List list = (List) data;
                                        if(list.size()>0) {
                                            emitter.onNext(data);
                                        }else {
                                            emitter.onError(new ApiException(250, "无数据"));
                                        }

                                    }else {

                                        emitter.onNext(data);
                                    }

                                }else {
                                    emitter.onNext((T) "1");
                                }
                            }
                        } else {//请求失败

                            if (!emitter.isDisposed()) {
                                //这里抛出自定义的一个异常.可以处理服务器返回的错误.
                                emitter.onError(new ApiException(-1, response.getMassage()));
                            }
                            return;
                        }
                        if (!emitter.isDisposed()) {//请求完成
                            emitter.onComplete();
                        }
                    }
                });
            }


        }
    }

    /**
     * 这个类的意义就是转换Observable.
     */
    private static class SampleTransformer<T> implements ObservableTransformer<BaseResponse<T>, T> {
        //这里对Observable,进行一般的通用设置.不用每次用Observable都去设置线程以及重连设置

        @Override
        public Observable<T> apply(final  Observable<BaseResponse<T>> observable) {
            return observable.subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .unsubscribeOn(Schedulers.io())
                    .timeout(5, TimeUnit.SECONDS)//重连间隔时间
                    .retry(5)//重连次数
                    .doOnNext(tBaseResponse -> {
                        Log.e("tBaseResponse"+tBaseResponse.toString());
                    })
                    .flatMap(new Function<BaseResponse<T>, Observable<T>>() {
                        @Override
                        public Observable<T> apply(BaseResponse<T> tBaseResponse) throws Exception {
                            return flatResponse(tBaseResponse);
                        }
                    });
        }

        /**
         * 处理请求结果,BaseResponse<T>
         *
         * @param response 请求结果
         * @return 过滤处理, 返回只有data数据的Observable
         */
        private Observable flatResponse(final BaseResponse<T> response) {
            final String message = response.getMessage();
            if(response.getData() == null) {
                return Observable.create(new ObservableOnSubscribe<Object>() {
                    @Override
                    public void subscribe(ObservableEmitter<Object> emitter) throws Exception {
                        if(response.getReturnCode() == 200) {
                            emitter.onError(new ApiException(response.getReturnCode(), "数据为空"));
                            emitter.onComplete();
                        }else {
                            emitter.onError(new ApiException(response.getReturnCode(), message));
                            emitter.onComplete();
                        }
                    }
                });
            }else {
                return Observable.create(new ObservableOnSubscribe<T>() {
                    @Override
                    public void subscribe(ObservableEmitter<T> emitter) throws Exception {
                        if (response.isSuccess()) {//请求成功
                            if (!emitter.isDisposed()) {
                                T data = response.getData();
                                if(data != null) {
                               /* Gson gson1 = new Gson();
                                String paramLoginStr = gson1.toJson(data)
                                        .replace("null","");
                                T t1 = gson1.fromJson(paramLoginStr, (Class<T>) data.getClass());*/
                                    emitter.onNext(data);
                                }else {
                                    emitter.onNext((T) "1");
                                }
                            }
                        } else {//请求失败
                            int resultCode = response.getReturnCode();
                            if (!emitter.isDisposed()) {
                                //这里抛出自定义的一个异常.可以处理服务器返回的错误.
                                if(message != null) {

                                    emitter.onError(new ApiException(response.getReturnCode(), message));
                                }else {
                                    emitter.onError(new ApiException(response.getReturnCode(), ""));

                                }

                            }

                            return;
                        }
                        if (!emitter.isDisposed()) {//请求完成
                            emitter.onComplete();
                        }
                    }


                });
            }


        }
    }

    private static class SampleTransformer1<T> implements ObservableTransformer<T, T> {
        //这里对Observable,进行一般的通用设置.不用每次用Observable都去设置线程以及重连设置

        @Override
        public Observable<T> apply(final  Observable<T> observable) {
            return observable.subscribeOn(Schedulers.io())
                    .observeOn(Schedulers.computation())
                    .unsubscribeOn(Schedulers.io())
                    .timeout(5, TimeUnit.SECONDS)//重连间隔时间
                    .retry(5)//重连次数
                    .flatMap(new Function<T, ObservableSource<T>>() {
                        @Override
                        public ObservableSource<T> apply(T t) throws Exception {
                            return convert(t);
                        }
                    }).observeOn(AndroidSchedulers.mainThread())
                    ;

        }

        private ObservableSource<T> convert(T t) {
            return Observable.create(new ObservableOnSubscribe<T>() {
                @Override
                public void subscribe(ObservableEmitter<T> emitter) throws Exception {
                    if (!emitter.isDisposed()) {
                        if (t != null) {//这里最好判断一下是否为null.
                            Gson gson1 = new Gson();
                            String paramLoginStr = gson1.toJson(t)
                                    .replace("null","");
                            T t1 = gson1.fromJson(paramLoginStr, (Class<T>) t.getClass());
                            emitter.onNext(t1);
                            emitter.onComplete();
                        }
                    }
                }
            });
        }


        /**
         * 处理请求结果,BaseResponse<T>
         *
         * @param response 请求结果
         * @return 过滤处理, 返回只有data数据的Observable
         */
        private Observable flatResponse(final BaseResponse<T> response) {
            return Observable.create(new ObservableOnSubscribe<T>() {
                @Override
                public void subscribe(ObservableEmitter<T> emitter) throws Exception {
                    if (!emitter.isDisposed()) {
                        emitter.onNext(response.getData());
                        emitter.onComplete();
                    }
                    /* if (response.isSuccess()) {//请求成功
                        if (!emitter.isDisposed()) {
                            emitter.onNext(response.getData());
                        }
                    } else {//请求失败
                        int resultCode = response.getResultCode();
                        if (!emitter.isDisposed()) {
                            //这里抛出自定义的一个异常.可以处理服务器返回的错误.
                            emitter.onError(new ApiException(response.getResultCode(), response.getMsg()));
                        }
                        return;
                    }
                    if (!emitter.isDisposed()) {//请求完成
                        emitter.onComplete();
                    }*/
                }


            });
        }


    }

}
