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.SimplePresenter
import com.ydl.ydlcommon.utils.SharedPreferencesEditor
import com.ydl.ydlcommon.utils.YDLAsyncUtils
import com.yidianling.home.constract.IHomeContract
import com.yidianling.home.constract.YdlHomeViewHolderConstract
import com.yidianling.home.model.HomeModelImpl
import com.yidianling.home.model.bean.*
import com.yidianling.home.utils.HomeFileUtils
import com.yidianling.home.utils.HomeLogPrinter
import com.yidianling.common.tools.LogUtil
import com.yidianling.common.tools.RxAppTool
import com.yidianling.router.RouterManager
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.functions.Action
import io.reactivex.functions.Consumer
import io.reactivex.schedulers.Schedulers


/**
 * @author <a href="https://www.jianshu.com/u/c1e5310dd724">xujian</a>
 * @描述:
 * @Copyright Copyright (c) 2019
 * @Company 壹点灵
 * @date 2019/02/13
 */
class HomePresenterImpl : SimplePresenter<IHomeContract.View>() {

    private var CACHE_HOME_PAGER_DATA = "cache_home_pager_data"

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

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

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

    /**
     * 本次启动时候已经获取过优惠券的标记
     * 因为优惠券调用逻辑在onResum方法中执行，避免不必要的判断逻辑，增加标记
     * 每次请求优惠券成功之后，将值置为true
     */
    private var hasRequestCoupon = false
    @Volatile
    private var mHomeAskBean: HomeAskBean? = null
    /**
     * 防止重复请求
     */
//    private var zanRequestList: MutableList<String>? = mutableListOf()
    //首页数据缓存
    private var homeTempData: HomePagerDataBean = HomePagerDataBean()

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

                //首页缓存数据
                var cacheHomeData = ""

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

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

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

                return cacheHomeData
            }

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

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

    /**
     * 刷新首页数据请求
     */
    fun refreshHomeData() {
        val homeItemFromTempData = getHomeItemFromTempData(
            HomeHeaderBean(true),
            YdlHomeViewHolderConstract.PAGER_BANNER_VIEW
        )

        mConsultType =
            if (homeItemFromTempData.headerBean?.listenCategoryDate == null || homeItemFromTempData.headerBean?.listenCategoryDate!!.isEmpty()) {
                "1"
            } else {
                homeItemFromTempData.headerBean?.consultCategoryData!![0].id.toString()
            }

        mConfideType = ""

        mView?.resetModuleTabPosition()
        loadHomeData()
    }

    /**
     * 获取首页数据请求
     */
    @SuppressLint("CheckResult")
    fun loadHomeData() {
        disposeHome()
        val homeList: MutableList<HomePagerDataBean> = mutableListOf()
        LogUtil.d("mConsultType-loadHomeData:" + mConsultType)
        Observable.mergeArray(
            HomeModelImpl.headerRequest().map { it ->
                //首页头部数据 分类 & Banner
                homeList.add(
                    getHomeItemFromTempData(
                        it,
                        YdlHomeViewHolderConstract.PAGER_BANNER_VIEW
                    )
                )
                mView?.let { i -> i.homeHeadResponse(it) }
                //获取咨询分类后，再次请求咨询模块数据，防止出现默认分类为空，数据不对
                if (it.consultCategoryData != null && it.consultCategoryData!!.size > 0) {
                    //咨询分类和缓存分类不一致，重新加载咨询列表数据
                    if (!it.consultCategoryData!![0].id.toString().equals(mConsultType)) {
                        getConsultData("${it.consultCategoryData!![0].id}", 0)
                    }
                }
                homeList.add(HomePagerDataBean(YdlHomeViewHolderConstract.BUTTON_BANNER_VIEW))
                //保存热门搜索列表
                it.keywordData?.let { RouterManager.getConsultantRouter()?.setHotSearch(it) }
            },
            HomeModelImpl.consultRequest(mConsultType).map {
                //首页咨询数据
                homeList.add(getHomeItemFromTempData(it, YdlHomeViewHolderConstract.CONSULT_VIEW))
            },
            //GoodType为空 获取默认类型
            HomeModelImpl.confideRequest(mConfideType).map {
                //首页倾述数据
                homeList.add(getHomeItemFromTempData(it, YdlHomeViewHolderConstract.CONFIDE_VIEW))
            },
            HomeModelImpl.courseRequest().map {
                //首页课程数据
                homeList.add(getHomeItemFromTempData(it, YdlHomeViewHolderConstract.COURSE_VIEW))
            },
            HomeModelImpl.testRequest().map {
                //首页测试数据
                val homeTestBean = HomeTestBean()
                homeTestBean.testItemList = it.data
                homeList.add(
                    getHomeItemFromTempData(
                        homeTestBean,
                        YdlHomeViewHolderConstract.TEST_VIEW
                    )
                )
            },
            HomeModelImpl.askRequest().map {
                //首页问答数据
                homeList.add(
                    getHomeItemFromTempData(
                        it,
                        YdlHomeViewHolderConstract.ASSUAGE_GRIEF_VIEW
                    )
                )
            },
            HomeModelImpl.museRequest().map {
                //首页冥想数据
                homeList.add(getHomeItemFromTempData(it, YdlHomeViewHolderConstract.MUSE_VIEW))
            },
            HomeModelImpl.fmRequest().map {
                //首页电台数据
                homeList.add(
                    getHomeItemFromTempData(
                        it,
                        YdlHomeViewHolderConstract.INTELLIGENT_VIEW
                    )
                )
            },
            HomeModelImpl.articleRequest().map {
                //首页文章数据
                homeList.add(getHomeItemFromTempData(it, YdlHomeViewHolderConstract.ARTICLE_VIEW))
                homeList.add(HomePagerDataBean(YdlHomeViewHolderConstract.FOOTER_VIEW))
            })
            .subscribeOn(Schedulers.newThread())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(Consumer {}, object : ThrowableConsumer() {
                override fun accept(msg: String) {
                    mView?.homeDataFail(msg)
                }
            }, Action {
                homeList.sortWith(compareBy { it.type })
                mView?.let { it.homeDataResponse(homeList) }
                //更新本地缓存数据
                SharedPreferencesEditor.putString(CACHE_HOME_PAGER_DATA, Gson().toJson(homeList))
                SharedPreferencesEditor.putString(IS_NEW_CACHE_HOME_PAGER_DATA, true.toString())
                SharedPreferencesEditor.putString(
                    HOME_PAGER_DATA_CACHE_VERISON,
                    RxAppTool.getAppVersionCode(BaseApp.getApp()).toString()
                )
                HomeLogPrinter.printLongLog(
                    HomePresenterImpl::class.java.simpleName,
                    Gson().toJson(homeList)
                );
            })
    }

    fun saveTempData(list: MutableList<HomePagerDataBean>) {
        val homeBean = HomePagerDataBean()
        for (dataBean in list) {
            when (dataBean.type) {
                YdlHomeViewHolderConstract.PAGER_BANNER_VIEW -> {
                    homeBean.headerBean = dataBean.headerBean
                    dataBean.headerBean?.keywordData?.let {
                        RouterManager.getConsultantRouter()?.setHotSearch(it)
                    }
                }
                YdlHomeViewHolderConstract.CONSULT_VIEW -> {
                    homeBean.consultBean = dataBean.consultBean
                }
                YdlHomeViewHolderConstract.CONFIDE_VIEW -> {
                    homeBean.confideBean = dataBean.confideBean
                }
                YdlHomeViewHolderConstract.COURSE_VIEW -> {
                    homeBean.courseBean = dataBean.courseBean
                }
                YdlHomeViewHolderConstract.TEST_VIEW -> {
                    homeBean.testListBean = dataBean.testListBean
                }
                YdlHomeViewHolderConstract.ASSUAGE_GRIEF_VIEW -> {
                    mHomeAskBean = dataBean.askBean;
                    homeBean.askBean = dataBean.askBean
                }
                YdlHomeViewHolderConstract.MUSE_VIEW -> {
                    homeBean.museBean = dataBean.museBean
                }
                YdlHomeViewHolderConstract.INTELLIGENT_VIEW -> {
                    homeBean.fmBean = dataBean.fmBean
                }
                YdlHomeViewHolderConstract.ARTICLE_VIEW -> {
                    homeBean.articleBean = dataBean.articleBean
                }
            }
        }
        homeTempData = homeBean
    }

    private fun getHomeItemFromTempData(
        dataBean: HomeItemBaseBean,
        type: Int
    ): HomePagerDataBean {

        val item = HomePagerDataBean(type)

        when (type) {
            YdlHomeViewHolderConstract.PAGER_BANNER_VIEW -> {
                item.headerBean =
                    if (dataBean.isRealEmpty || dataBean !is HomeHeaderBean) homeTempData.headerBean else dataBean
            }
            YdlHomeViewHolderConstract.CONSULT_VIEW -> {
                item.consultBean =
                    if (dataBean.isRealEmpty || dataBean !is HomeConsultBean) homeTempData.consultBean else dataBean
            }
            YdlHomeViewHolderConstract.CONFIDE_VIEW -> {
                item.confideBean =
                    if (dataBean.isRealEmpty || dataBean !is HomeConfideBean) homeTempData.confideBean else dataBean
            }
            YdlHomeViewHolderConstract.COURSE_VIEW -> {
                item.courseBean =
                    if (dataBean.isRealEmpty || dataBean !is HomeCourseBean) homeTempData.courseBean else dataBean
            }
            YdlHomeViewHolderConstract.TEST_VIEW -> {
                item.testListBean =
                    if (dataBean.isRealEmpty || dataBean !is HomeTestBean) homeTempData.testListBean else dataBean.testItemList
            }
            YdlHomeViewHolderConstract.ASSUAGE_GRIEF_VIEW -> {
                item.askBean =
                    if (dataBean.isRealEmpty || dataBean !is HomeAskBean) homeTempData.askBean else dataBean
                mHomeAskBean = item.askBean
            }
            YdlHomeViewHolderConstract.MUSE_VIEW -> {
                item.museBean =
                    if (dataBean.isRealEmpty || dataBean !is MuseModuleBean) homeTempData.museBean else dataBean
            }
            YdlHomeViewHolderConstract.INTELLIGENT_VIEW -> {
                item.fmBean =
                    if (dataBean.isRealEmpty || dataBean !is HomeFMBean) homeTempData.fmBean else dataBean
            }
            YdlHomeViewHolderConstract.ARTICLE_VIEW -> {
                item.articleBean =
                    if (dataBean.isRealEmpty || dataBean !is HomeArticleBean) homeTempData.articleBean else dataBean
            }
        }
        return item
    }

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

        disposeConfide()
        disposeHome()

        mConfideType = type

        HomeModelImpl.confideRequest(type)
            .map { it }
            .filter { true }
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(Consumer {
                mView?.confideDataResponse(it, selectPosition)
            }, object : ThrowableConsumer() {
                override fun accept(msg: String) {
                    mView?.homeDataFail(msg)
                }
            })
    }


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

        disposeConsult()
        disposeHome()

        mConsultType = type

        mConsultDisposable = HomeModelImpl.consultRequest(type)
            .map { it }
            .filter { true }
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .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")
    fun askZan(position: Int, index: Int, id: String) {
//        if (zanRequestList?.contains(id)!!) {
//            return
//        }
//        zanRequestList?.add(id)
        HomeModelImpl.askZan(id)
            .compose(RxUtils.netCheck())
            .subscribeOn(Schedulers.io())
            .map { result ->
                //                    mHomeAskBean!!.data!![index].isZan = result.status
//                    if (result.status == 1) mHomeAskBean!!.data!![index].zanCount++ else mHomeAskBean!!.data!![index].zanCount--
//                    mHomeAskBean
            }
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(Consumer {
                //                    zanRequestList?.remove(id)
//                    view.askDataResponse(it!!, position)
            }, object : ThrowableConsumer() {
                override fun accept(msg: String) {
                    //zanRequestList?.remove(id)
                    mView?.homeDataFail(msg)
                }
            })

    }

    /**
     * 首页问答 - 关注
     */
    fun askFocus(position: Int, id: String) {
        HomeModelImpl.askFocus(id)
            .compose(RxUtils.netCheck())
            .subscribeOn(Schedulers.io())
            .map { result ->
                //                    //遍历更改集合中已关注用户状态
//                    var tempList = mutableListOf<HomeAskBean.DataBean>();
//                    for ((index, value) in mHomeAskBean!!.data?.withIndex()!!) {
//                        if (value.uid.toString() == id) {
//                            value.isFocused = result.status
//                        }
//                        tempList.add(value)
//                    }
//                    mHomeAskBean!!.data = tempList
//                    mHomeAskBean
            }
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(Consumer {
                //                    view.askDataResponse(it!!, position)
            }, object : ThrowableConsumer() {
                override fun accept(msg: String) {
                    mView.homeDataFail(msg)
                }
            })
    }

    inner class CouponReceiveBean {
        var couponIds: List<String>? = null
    }
}