package com.yidianling.home.presenter

import android.annotation.SuppressLint
import com.google.gson.Gson
import com.ydl.ydlcommon.base.BaseApp
import com.ydl.ydlcommon.data.http.RxUtils
import com.ydl.ydlcommon.data.http.ThrowableConsumer
import com.ydl.ydlcommon.modular.ModularServiceManager
import com.ydl.ydlcommon.utils.SharedPreferencesEditor
import com.yidianling.common.tools.LogUtil
import com.yidianling.common.tools.RxAppTool
import com.yidianling.consultant.api.IConsultantService
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.HomeLogPrinter
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.functions.Action
import io.reactivex.functions.Consumer
import io.reactivex.schedulers.Schedulers
import java.util.*
import java.util.concurrent.TimeUnit


/**
 * @author <a href="https://www.jianshu.com/u/c1e5310dd724">xujian</a>
 * @描述:
 * @Copyright Copyright (c) 2019
 * @Company 壹点灵
 * @date 2019/02/13
 */
class HomePresenterImpl: BaseHomePresenterImpl<IHomeContract.View, IHomeContract.Model>(), IHomeContract.Presenter {
    override fun createModel(): IHomeContract.Model {
        return HomeModelImpl()
    }

    /**
     * 获取首页数据请求
     */
    @SuppressLint("CheckResult")
    override fun loadHomeData() {
        disposeHome()
        val homeList: MutableList<HomePagerDataBean> = mutableListOf()
        LogUtil.d("mConsultType-loadHomeData:$mConsultType")
        mHomeDisposable = Observable.mergeArray(
            mModel.headerRequest()
                .compose(RxUtils.applySchedulers(mView)).map { it ->
                //首页头部数据 分类 & Banner
                homeList.add(
                    getHomeItemFromTempData(
                        it,
                        YdlHomeViewHolderConstract.PAGER_BANNER_VIEW
                    )
                )
                mView.homeHeadResponse(it)
                //获取咨询分类后，再次请求咨询模块数据，防止出现默认分类为空，数据不对
                if (it.consultCategoryData != null && it.consultCategoryData!!.isNotEmpty()) {
                    //咨询分类和缓存分类不一致，重新加载咨询列表数据
                    if (it.consultCategoryData!![0].id.toString() != mConsultType) {
                        getConsultData("${it.consultCategoryData!![0].id}", 0, false)
                    }
                }
                homeList.add(HomePagerDataBean(YdlHomeViewHolderConstract.BUTTON_BANNER_VIEW))
                //保存热门搜索列表
                it.keywordData?.let {
                    ModularServiceManager.provide(IConsultantService::class.java).setHotSearch(it)
                }
            },
            mModel.consultRequest(mConsultType)
                .compose(RxUtils.applySchedulers(mView)).map {
                //首页咨询数据
                homeList.add(getHomeItemFromTempData(it, YdlHomeViewHolderConstract.CONSULT_VIEW))
            },
            //GoodType为空 获取默认类型
            mModel.confideRequest(mConfideType)
                .compose(RxUtils.applySchedulers(mView)).map {
                //首页倾述数据
                homeList.add(getHomeItemFromTempData(it, YdlHomeViewHolderConstract.CONFIDE_VIEW))
            },
            mModel.courseRequest()
                .compose(RxUtils.applySchedulers(mView)).map {
                //首页课程数据
                homeList.add(getHomeItemFromTempData(it, YdlHomeViewHolderConstract.COURSE_VIEW))
            },
            mModel.testRequest()
                .compose(RxUtils.applySchedulers(mView)).map {
                //首页测试数据
                val homeTestBean = HomeTestBean()
                homeTestBean.testItemList = it.data
                homeList.add(
                    getHomeItemFromTempData(
                        homeTestBean,
                        YdlHomeViewHolderConstract.TEST_VIEW
                    )
                )
            },
            mModel.askRequest()
                .compose(RxUtils.applySchedulers(mView)).map {
                //首页问答数据
                homeList.add(
                    getHomeItemFromTempData(
                        it,
                        YdlHomeViewHolderConstract.ASSUAGE_GRIEF_VIEW
                    )
                )
            },
            mModel.museRequest()
                .compose(RxUtils.applySchedulers(mView)).map {
                //首页冥想数据
                homeList.add(getHomeItemFromTempData(it, YdlHomeViewHolderConstract.MUSE_VIEW))
            },
            mModel.fmRequest()
                .compose(RxUtils.applySchedulers(mView)).map {
                //首页电台数据
                homeList.add(
                    getHomeItemFromTempData(
                        it,
                        YdlHomeViewHolderConstract.INTELLIGENT_VIEW
                    )
                )
            },
            mModel.articleRequest()
                .compose(RxUtils.applySchedulers(mView)).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)
                    mHomeDisposable?.dispose()
                }
            }, Action {
                homeList.sortWith(compareBy { it.type })

                //更新本地缓存数据
                Observable.interval(5000, TimeUnit.SECONDS)
                    .compose(RxUtils.applySchedulers(mView))
                    .subscribe {
                        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()
                        )
                    }

                mView.homeDataResponse(homeList)
                //更新本地缓存数据

                HomeLogPrinter.printLongLog(
                    HomePresenterImpl::class.java.simpleName,
                    Gson().toJson(homeList)
                )
            })
    }

    override 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()
    }

    override 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 {
                        ModularServiceManager.provide(IConsultantService::class.java)
                            .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
    }

    override 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
    }
}