package com.yidianling.home.presenter

import android.annotation.SuppressLint
import android.content.Context
import android.text.TextUtils
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.ydl.ydlcommon.base.BaseApp
import com.ydl.ydlcommon.data.http.RxUtils
import com.ydl.ydlcommon.data.http.ThrowableConsumer
import com.ydl.ydlcommon.mvp.base.BasePresenter
import com.ydl.ydlcommon.mvp.base.IModel
import com.ydl.ydlcommon.mvp.base.IView
import com.ydl.ydlcommon.utils.SharedPreferencesEditor
import com.ydl.ydlcommon.utils.YDLAsyncUtils
import com.yidianling.common.tools.RxAppTool
import com.yidianling.home.constants.IHomeBaseContract
import com.yidianling.home.model.bean.HomeAskBean
import com.yidianling.home.model.bean.HomeItemBaseBean
import com.yidianling.home.model.bean.HomePagerDataBean
import com.yidianling.home.utils.HomeFileUtils
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.functions.Consumer
import io.reactivex.schedulers.Schedulers

abstract class  BaseHomePresenterImpl< V : IHomeBaseContract.View,M : IHomeBaseContract.Model>:
    BasePresenter< V, M>(), IHomeBaseContract.Presenter<V> {
    abstract override fun createModel(): M

    /**
     * 获取首页数据请求
     */
    abstract override fun loadHomeData()

    /**
     * 保存临时数据
     */
    abstract override fun saveTempData(list: MutableList<HomePagerDataBean>)

    /**
     * 获取临时数据
     */
    abstract override fun getHomeItemFromTempData(dataBean: HomeItemBaseBean, type: Int): Any

    /**
     * 刷新首页数据请求
     */
    abstract override fun refreshHomeData()



    var CACHE_HOME_PAGER_DATA = "cache_home_pager_data"

    //首页json文件和缓存数据结构不一致时临时使用
    var IS_NEW_CACHE_HOME_PAGER_DATA = "IS_NEW_CACHE_HOME_PAGER_DATA"

    //首页缓存版本号
    var HOME_PAGER_DATA_CACHE_VERISON = "HOME_PAGER_DATA_CACHE_VERISON"

    var mConsultDisposable: Disposable? = null
    var mConfideDisposable: Disposable? = null
    var mHomeDisposable: Disposable? = null
    var mConfideType: String = ""
    var mConsultType: String = ""

    @Volatile
    var mHomeAskBean: HomeAskBean? = null
    //首页数据缓存
    var homeTempData: HomePagerDataBean = HomePagerDataBean()

    /**
     * 加载本地缓存
     */
    override fun localHomeData(context: Context, fileName: String) {
        YDLAsyncUtils.asyncAsResult(object : YDLAsyncUtils.AsyncObjecyerResult {
            override fun doAsyncAction(): Any {

                //首页缓存数据
                var cacheHomeData: String

                //是否为新的数据结构
                val isNewPageData = SharedPreferencesEditor.getString(IS_NEW_CACHE_HOME_PAGER_DATA)
                val homeCacheVersion =
                    SharedPreferencesEditor.getString(HOME_PAGER_DATA_CACHE_VERISON)
                val appVersionCode = RxAppTool.getAppVersionCode(BaseApp.getApp())

                //版本更新后不使用上个版本的首页缓存
                cacheHomeData = if (isNewPageData.isEmpty() || (!TextUtils.isEmpty(homeCacheVersion) && appVersionCode > homeCacheVersion.toInt())) {
                    ""
                } else {
                    //上次首页缓存数据
                    SharedPreferencesEditor.getString(CACHE_HOME_PAGER_DATA)
                }

                if (cacheHomeData.isEmpty()) {
                    //第一次安装使用本地临时数据
                    cacheHomeData =
                        String(HomeFileUtils.getAssertsFile(context, fileName)!!)
                }

                return cacheHomeData
            }

            override fun asyncResult(`object`: Any?) {
                //如果没 有缓存数据，显示加载框
                if (`object` !is String || TextUtils.isEmpty(`object`)) {
                    mView.showRefreshLayout()
                }

                if (`object` is String) {
                    val list = Gson().fromJson<MutableList<HomePagerDataBean>>(
                        `object`,
                        object : TypeToken<MutableList<HomePagerDataBean>>() {
                        }.type
                    )
                    if (null != list && list.isNotEmpty()) {
                        mView.homeDataResponse(list)
                        saveTempData(list)
                    }
                }
            }
        })
    }

    /**
     *获取倾述列表
     */
    @SuppressLint("CheckResult")
    override fun getConfideData(type: String, selectPosition: Int) {

        disposeConfide()
        disposeHome()

        mConfideType = type

        mConfideDisposable = mModel.confideRequest(type)
            .compose(RxUtils.applySchedulers(mView))
            .map { it }
            .filter { true }
            .subscribe(Consumer {
                mView.confideDataResponse(it, selectPosition)
            }, object : ThrowableConsumer() {
                override fun accept(msg: String) {
                    mView.homeDataFail(msg)
                }
            })
    }


    /**
     *获取咨询列表
     */
    override fun getConsultData(type: String, selectPosition: Int, isCancelHome: Boolean) {

        disposeConsult()

        if (isCancelHome) {
            disposeHome()
        }

        mConsultType = type

        mConsultDisposable = mModel.consultRequest(type)
            .compose(RxUtils.applySchedulers(mView))
            .map { it }
            .filter { true }
            .subscribe(Consumer {
                mView.consultDataResponse(it, selectPosition)
            }, object : ThrowableConsumer() {
                override fun accept(msg: String) {
                    mView.homeDataFail(msg)
                }
            })
    }

    fun disposeConfide() {
        if (mConfideDisposable != null && !mConfideDisposable!!.isDisposed) {
            mConfideDisposable?.dispose()
        }
    }

    fun disposeConsult() {
        if (mConsultDisposable != null && !mConsultDisposable!!.isDisposed) {
            mConsultDisposable?.dispose()
        }
    }

    fun disposeHome() {
        if (mHomeDisposable != null && !mHomeDisposable!!.isDisposed) {
            mHomeDisposable?.dispose()
        }
    }

    /**
     * 首页问答 - 点赞
     */
    @SuppressLint("CheckResult")
    override fun askZan(position: Int, index: Int, id: String) {
        mModel.askZan(id)
            .compose(RxUtils.applySchedulers(mView))
            .compose(RxUtils.netCheck())
            .map {}
            .subscribe(Consumer {
            }, object : ThrowableConsumer() {
                override fun accept(msg: String) {
                    mView.homeDataFail(msg)
                }
            })

    }

    /**
     * 首页问答 - 关注
     */
    @SuppressLint("CheckResult")
    override fun askFocus(position: Int, id: String) {
        mModel.askFocus(id)
            .compose(RxUtils.applySchedulers(mView))
            .compose(RxUtils.netCheck())
            .map {}
            .subscribe(Consumer {
                //                    view.askDataResponse(it!!, position)
            }, object : ThrowableConsumer() {
                override fun accept(msg: String) {
                    mView.homeDataFail(msg)
                }
            })
    }
}