package com.yidianling.home.presenter

import android.annotation.SuppressLint
import android.app.Activity
import android.os.Handler
import android.text.TextUtils
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.LogUtil
import com.ydl.ydlcommon.utils.SharedPreferencesEditor
import com.ydl.ydlcommon.utils.YDLCacheUtils
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 com.yidianling.user.api.service.IUserService
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.text.SimpleDateFormat
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()
    }

    private var hasRequestCoupon = false

    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.BUTTON_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.ARTICLE_VIEW -> {
                    homeBean.articleBean = dataBean.articleBean
                }
            }
        }
        homeTempData = homeBean
    }

    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 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.BUTTON_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
                item.headerBean = homeTempData.headerBean
            }
            YdlHomeViewHolderConstract.CONFIDE_VIEW -> {
                item.confideBean =
                    if (dataBean.isRealEmpty || dataBean !is HomeConfideBean) homeTempData.confideBean else dataBean
                item.headerBean = homeTempData.headerBean
            }
            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.meditationBean =
                    if (dataBean.isRealEmpty || dataBean !is MeditationModuleBean) homeTempData.meditationBean else dataBean
            }
            YdlHomeViewHolderConstract.ARTICLE_VIEW -> {
                item.articleBean =
                    if (dataBean.isRealEmpty || dataBean !is HomeArticleBean) homeTempData.articleBean else dataBean
            }

        }
        return item
    }

    /**
     * 获取首页数据请求
     */
    @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
                    )
                )
                homeList.add(
                    getHomeItemFromTempData(
                        it,
                        YdlHomeViewHolderConstract.BUTTON_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.getMeditation()
                .compose(RxUtils.applySchedulers(mView)).map {
                    //首页问答数据
                    homeList.add(getHomeItemFromTempData(it, YdlHomeViewHolderConstract.MUSE_VIEW))
                },
            mModel.askRequest()
                .compose(RxUtils.applySchedulers(mView)).map {
                //首页问答数据
                homeList.add(
                    getHomeItemFromTempData(
                        it,
                        YdlHomeViewHolderConstract.ASSUAGE_GRIEF_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)
                }
            }, Action {
                if (homeList.size != 10){
                    mView.homeDataFail("")
                    return@Action
                }

                homeList.sortWith(compareBy { it.type })
                //更新本地缓存数据,这边顶部数据保存了两份，一个10001,一个10002，防止第二次进来读取的时候homeDataResponse回调中的remove(0)把10002删除


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

    /**
     * 领取优惠券
     */
    @SuppressLint("CheckResult")
    override fun receiveCoupon(list: List<CouponBean>) {
        val uid = ModularServiceManager.provide(IUserService::class.java).getUserInfo()?.uid ?: ""
        val couponIds = ArrayList<String>()
        for (bean in list) {
            couponIds.add(bean.couponId ?: "")
        }
        val bean = CouponReceiveBean()
        bean.couponIds = couponIds
        val couponIdsStr = Gson().toJson(bean)

        mModel.receiveCoupon(uid, couponIdsStr)
            .compose(RxUtils.applySchedulers(mView))
            .compose(RxUtils.netCheck())
            .doOnSubscribe { mView.showHomeProgress() }
            .doAfterTerminate { mView.dismissHomeProgress() }
            .subscribe(Consumer {
                mView.receiveCouponResponse(it)
            }, object : ThrowableConsumer() {
                override fun accept(msg: String) {
                    mView.homeDataFail(msg)
                }
            })
    }


    override fun prepareCoupon(activity: Activity) {
        //判断是否登录  以及本次app启动后是否已经请求过
        if (ModularServiceManager.provide(IUserService::class.java).isLogin() && !hasRequestCoupon) {
            Handler().postDelayed({
                //优惠券逻辑
                if (compareCouponTime()) {
                    getCouponData()
                }
            }, 2000)
        }
    }

    @SuppressLint("CheckResult")
    private fun getCouponData() {
        val uid = ModularServiceManager.provide(IUserService::class.java).getUserInfo()?.uid ?: ""
        mModel.getCoupons(uid)
            .compose(RxUtils.applySchedulers(mView))
            .compose(RxUtils.netCheck())
            .subscribe(Consumer {
                hasRequestCoupon = true

                val simpleFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")//如2016-08-10
                val time = System.currentTimeMillis()
                val date = Date()
                date.time = time
                val nowTime = simpleFormat.format(date)
                YDLCacheUtils.saveCouponTime(uid, nowTime);
                if (it?.data != null && !it.data.isEmpty()) {
                    mView.couponDataResponse(it.data)
                }
            }, object : ThrowableConsumer() {
                override fun accept(msg: String) {
                    mView.homeDataFail(msg)
                }
            })
    }

    /**
     * 对比上次获取优惠券时间，若时间差超过一天，则再次请求，否则不获请求
     */
    @SuppressLint("SimpleDateFormat")
    private fun compareCouponTime(): Boolean {
        val simpleFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")//如2016-08-10
        val uid = ModularServiceManager.provide(IUserService::class.java).getUserInfo()?.uid
        val last = YDLCacheUtils.getCouponTime(uid)
        if (TextUtils.isEmpty(last)) {
            //还没有获取过优惠券，直接请求数据
            return true
        } else {
            val time = System.currentTimeMillis()
            val date = Date()
            date.time = time
            val nowTime = simpleFormat.format(date)
            return !TextUtils.equals(last.substring(0, 10), nowTime.substring(0, 10))
        }
    }

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