package com.ysnows.base.base

import android.annotation.SuppressLint
import com.ysnows.base.emptyview.callback.EmptyCallback
import com.ysnows.base.model.IResultList
import com.ysnows.base.net.IResponse
import com.ysnows.base.utils.MMKVManager
import com.ysnows.base.view.BRView
import io.reactivex.Observable
import io.reactivex.ObservableEmitter
import io.reactivex.ObservableOnSubscribe

open class BRRepository : BRepository() {

    override fun view(): BRView<*>? {
        return bView as BRView<*>?
    }

    var page = 0

    /**
     * 请求时, 缓存第一个数据
     *
     * @param <T>
     * @param key
     * @param clazz
     *
     * @return
    </T> */
    fun <D, T : IResultList<D>?> cacheReq(key: String?, clazz: Class<T>?): Observable<T> {
        return Observable.create(ObservableOnSubscribe { emitter ->
            val t = MMKVManager.instance().decodeParcelable(key, clazz)
            var pagable = false
            if (t != null) {
                view()?.adapter()?.setList(t.list() as ArrayList<Nothing>)
                emitter.onNext(t)
            } else {
                pagable = true
            }
//            reqFirstPage(pagable)
//                    .doOnNext(Consumer { res: IResponse<*> ->
////                            if (res.ok()) {
//                        val result = res.data() as T?
//                        emitter.onNext(result)
//                        val encode = MMKVManager.instance().encode(key, result)
//                    } as Consumer<in IResponse<*>>)
//                    .subscribe()
        })
    }

    fun <D, T : IResponse<D?>> reqFirstPage(pagable: Boolean): Observable<T> {
        page = 0
        val api = view()?.api() as Observable<T>
        return reqList(api, pagable)
    }

    fun <D, T : IResponse<D?>> reqList(observable: Observable<T>): Observable<T> {
        return reqList(observable, false)
    }

    @SuppressLint("CheckResult")
    fun <D, T : IResponse<D?>> reqList(observable: Observable<T>, pageLoading: Boolean): Observable<T> {
        return Observable.create { emitter: ObservableEmitter<T> ->
            req(observable, pageLoading, false)
                    .doOnError { throwable: Throwable ->
                        throwable.printStackTrace()
                        if (page >= 1) {
                            view()?.adapter()?.loadMoreModule?.loadMoreFail()
                            page -= 1
                        }
                        emitter.onError(throwable)
                    }
                    .subscribe({ res: T ->
                        view()?.onListReceive(res)
                        if (page <= 1) {
                            if (res.empty()) { //如果没有数据
                                view()?.refreshing(false)
                                view()?.loadService!!.showCallback(EmptyCallback::class.java)
                            } else {
                                view()?.refreshing(false)
                                //Object data = res.data();
//                                if (data instanceof IResultList) {
//                                    adapter.setList(((IResultList) data).list());
//                                }
                                view()?.adapter()?.setList(res.data() as ArrayList<Nothing>)
                                view()?.loadService!!.showSuccess()
                            }
                            view()?.getTotal(res.total())
                        } else {
//                            Object data = res.data();
//                            if (data instanceof IResultList) {
//                                view().getAdapter().addData((((IResultList) data).list()));
//                            }
                            view()?.adapter()?.addData(res.data() as ArrayList<Nothing>)
                        }
                        if (res.more(page)) {
                            view()?.adapter()?.loadMoreModule?.loadMoreComplete()
                        } else {
                            //数据全部加载完毕
                            view()?.adapter()?.loadMoreModule?.loadMoreEnd()
                        }
                        emitter.onNext(res)
                    }, { throwable: Throwable? -> }) { emitter.onComplete() }
        }
    }

    fun autoPage(): Int {
        page += 1
        return page
    }
}