package com.ydl.confide.home.presenter

import android.content.Context
import android.text.TextUtils
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.ydl.confide.home.bean.ConfideHomeDataBean
import com.ydl.confide.home.contract.IConfideHomeContract
import com.ydl.confide.home.http.ConfideRecommendParam
import com.ydl.confide.home.model.ConfideHomeModelImpl
import com.ydl.confide.home.util.ConfideHomeUtils
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.IView
import com.ydl.ydlcommon.utils.YDLAsyncUtils
import com.ydl.ydlcommon.utils.YDLCacheUtils
import com.yidianling.common.tools.RxNetTool
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.functions.Consumer

/**
 * @author yuanwai
 * @描述:倾诉首页逻辑实现类
 * @Copyright Copyright (c) 2018
 * @Company 壹点灵
 * @date 2018/8/10
 */
class ConfideHomePresenterImpl : BasePresenter<IConfideHomeContract.View,IConfideHomeContract.Model>(), IConfideHomeContract.Presenter{

    override fun createModel(): IConfideHomeContract.Model {
        return ConfideHomeModelImpl()
    }

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

                //读取缓存数据
                var cacheData = YDLCacheUtils.getConfideHomeData()

                if (cacheData.isEmpty()) {
                    cacheData = String(ConfideHomeUtils.getAssertsFile(context, "confide_home.json")!!)
                }

                return cacheData
        }

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

                if (`object` is String){
                    val gson = Gson()
                    val list = gson.fromJson<MutableList<ConfideHomeDataBean>>(`object`, object : TypeToken<MutableList<ConfideHomeDataBean>>() {

                    }.type)
                    if(null != list && !list.isEmpty()){
                        mView.confideHomeResponse(list)
                    }
                }
                confideHomeRequest(false)
            }
        })
    }

    /**
     * 请求首页数据
     */
    override fun confideHomeRequest(isRefresh:Boolean) {
        if (!RxNetTool.isConnected(mView.getContext())){
            mView.confideHomeRequestFail()
            return
        }
        val disposable = mModel.confideHomeRequest()
                .map { it }
                .filter { it != null }
                .compose(RxUtils.applySchedulers(mView as IView))
                .doFinally { mView.hideLoading() }
                .subscribe(Consumer {
                    mView.confideHomeResponse(it)
                    updateCache(it)
                }, object : ThrowableConsumer() {
                    override fun accept(msg: String) {
                        mView.confideHomeRequestFail()
                    }
                })
    }

    private fun testHome(){
        var json = "[{\"type\":1,\"body\":[{\"bannerId\":\"23434\",\"bannerImageUrl\":\"https://img.ydlcdn.com/file/2018/09/18/335fb32fd39131f9159578bcc5a62863.jpg\",\"bannerTitle\":\"banner标题\",\"bannerLinkUrl\":\"app:qingsu/home?id=123\"},{\"bannerId\":\"23434\",\"bannerImageUrl\":\"https://img.ydlcdn.com/file/2018/09/18/335fb32fd39131f9159578bcc5a62863.jpg\",\"bannerLinkUrl\":\"app:qingsu/home?id=123\"}],\"diviLine\":0},{\"type\":2,\"body\":[{\"confidedId\":\"123\",\"confidedName\":\"黄蓉\",\"confideSex\":0,\"confideContent\":\"对你留言：没有人一出生就是完美的，只有不断地相信自己才能成就自己的梦\",\"confidedIcon\":\"https://img.ydlcdn.com/file/2018/03/15/p5hmpru0n0dt5331.png\",\"confideLine\":0,\"confideHearNum\":\"已聆听2882次\",\"confideHistory\":\"7月13日 你向TA倾诉过\",\"confideVoice\":\"http://ssssssssssssssssss\"}],\"head\":{\"title\":\"最近倾诉\"},\"diviLine\":1},{\"type\":3,\"body\":[{\"categoryId\":\"123\",\"categoryType\":1,\"categoryName\":\"倾诉指南\",\"categoryContent\":\"排忧疏导，隐私安全\",\"categoryIcon\":\"https://img.ydlcdn.com/file/2018/08/15/2d04ef1c734b3bed59b33bb73fed81db.png\",\"linkUrl\":\"ydl-user://h5/h5?url=http://www.yidianling.com\"},{\"categoryId\":\"123\",\"categoryType\":2,\"categoryName\":\"专业师资\",\"categoryContent\":\"1182人倾诉心事\",\"categoryIcon\":\"https://img.ydlcdn.com/file/2018/08/15/2d04ef1c734b3bed59b33bb73fed81db.png\"}],\"diviLine\":1},{\"type\":7,\"body\":[{\"confidedId\":\"123\",\"confidedTitle\":\"情感恋爱\",\"confideNum\":\"8513人\",\"confideBgUrl\":\"https://img.ydlcdn.com/file/2018/08/11/m8ueotgn50hgxaa2.png\",\"confidedName\":\"黄蓉\",\"confideSex\":0,\"confideContent\":\"没有人出生就是完美的，只有不断地相信自己才能成就自己的梦想\",\"confidedIcon\":\"https://img.ydlcdn.com/file/2018/03/15/p5hmpru0n0dt5331.png\",\"confideLine\":1,\"confideConnection\":\"98%\",\"confideHearNum\":\"已聆听2882次\",\"confidedTag\":[\"80后\",\"婚姻家庭\",\"情感导师\",\"职场发展\"]},{\"confidedId\":\"123\",\"confidedTitle\":\"情感恋爱\",\"confideNum\":\"8513人\",\"confideBgUrl\":\"https://img.ydlcdn.com/file/2018/08/11/m8ueotgn50hgxaa2.png\",\"confidedName\":\"黄蓉\",\"confideSex\":0,\"confideContent\":\"没有人出生就是完美的，只有不断地相信自己才能成就自己的梦想\",\"confidedIcon\":\"https://img.ydlcdn.com/file/2018/03/15/p5hmpru0n0dt5331.png\",\"confideLine\":2,\"confideConnection\":\"100%\",\"confideHearNum\":\"已聆听2882次\",\"confidedTag\":[\"80后\",\"婚姻家庭\",\"情感导师\",\"职场发展\"]},{\"confidedId\":\"123\",\"confidedTitle\":\"情感恋爱\",\"confideNum\":\"8513人\",\"confideBgUrl\":\"https://img.ydlcdn.com/file/2018/08/11/m8ueotgn50hgxaa2.png\",\"confidedName\":\"黄蓉\",\"confideSex\":0,\"confideContent\":\"没有人出生就是完美的，只有不断地相信自己才能成就自己的梦想\",\"confidedIcon\":\"https://img.ydlcdn.com/file/2018/03/15/p5hmpru0n0dt5331.png\",\"confideLine\":3,\"confideConnection\":\"88%\",\"confideHearNum\":\"已聆听2882次\",\"confidedTag\":[\"80后\",\"婚姻家庭\",\"情感导师\",\"职场发展\"]}],\"head\":{\"title\":\"最佳倾诉榜单\"},\"diviLine\":1},{\"type\":4,\"body\":[{\"filterId\":\"123\",\"filterName\":\"综合排序\",\"filterType\":1,\"sortData\":[{\"id\":1,\"name\":\"综合排序\"},{\"id\":2,\"name\":\"人气从高到低\"},{\"id\":3,\"name\":\"时间从新到旧\"}]},{\"filterId\":\"456\",\"filterName\":\"性别年龄\",\"filterType\":2,\"sexTitle\":\"性别筛选\",\"sexData\":[{\"id\":1,\"name\":\"只看男生\"},{\"id\":2,\"name\":\"只看女生\"}],\"ageTitle\":\"年龄筛选\",\"ageData\":[{\"id\":1,\"name\":\"60后\"},{\"id\":2,\"name\":\"70后\"},{\"id\":3,\"name\":\"80后\"},{\"id\":4,\"name\":\"90后\"}]},{\"filterId\":\"789\",\"filterName\":\"擅长方向\",\"filterType\":3,\"goodTitle\":\"擅长方向\",\"goodData\":[{\"id\":1,\"name\":\"情感问题\"},{\"id\":2,\"name\":\"婚姻家庭\"},{\"id\":3,\"name\":\"情绪压力\"},{\"id\":4,\"name\":\"亲子教育\"}]}],\"diviLine\":1},{\"type\":5,\"body\":[{\"confidedId\":\"123\",\"confidedName\":\"黄蓉\",\"confideSex\":0,\"confideNum\":\"8513人\",\"confideContent\":\"没有人出生就是完美的，只有不断地相信自己才能成就自己的梦想\",\"confidedTag\":[\"80后\",\"婚姻家庭\",\"情感导师\",\"职场发展\"],\"confidedIcon\":\"https://img.ydlcdn.com/file/2018/03/15/p5hmpru0n0dt5331.png\",\"confideLine\":1,\"confideVoice\":\"http://ssssssssssssssssss\",\"confideConnection\":\"100%\"},{\"confidedId\":\"123\",\"confidedName\":\"黄蓉\",\"confideSex\":0,\"confideNum\":\"8513人\",\"confideContent\":\"没有人出生就是完美的，只有不断地相信自己才能成就自己的梦想\",\"confidedTag\":[\"80后\",\"婚姻家庭\",\"情感导师\",\"职场发展\"],\"confidedIcon\":\"https://img.ydlcdn.com/file/2018/03/15/p5hmpru0n0dt5331.png\",\"confideLine\":2,\"confideVoice\":\"http://ssssssssssssssssss\",\"confideConnection\":\"100%\"},{\"confidedId\":\"123\",\"confidedName\":\"黄蓉\",\"confideSex\":0,\"confideNum\":\"8513人\",\"confideContent\":\"没有人出生就是完美的，只有不断地相信自己才能成就自己的梦想\",\"confidedTag\":[\"80后\",\"婚姻家庭\",\"情感导师\",\"职场发展\"],\"confidedIcon\":\"https://img.ydlcdn.com/file/2018/03/15/p5hmpru0n0dt5331.png\",\"confideLine\":3,\"confideVoice\":\"http://ssssssssssssssssss\",\"confideConnection\":\"100%\"}],\"head\":{\"title\":\"为你推荐\"},\"diviLine\":1},{\"type\":6,\"body\":[{\"confidedId\":\"123\",\"confidedName\":\"黄蓉\",\"confideSex\":0,\"confideNum\":\"8513人\",\"confideVoice\":\"http://ssssssssssssssssss\",\"confideConnection\":\"100%\",\"confideContent\":\"没有人出生就是完美的，只有不断地相信自己才能成就自己的梦想\",\"confidedIcon\":\"https://img.ydlcdn.com/file/2018/03/15/p5hmpru0n0dt5331.png\",\"confideLine\":1,\"confideHearNum\":\"已聆听2882次\"},{\"confidedId\":\"123\",\"confidedName\":\"海伦\",\"confideSex\":0,\"confideNum\":\"8513人\",\"confideVoice\":\"http://ssssssssssssssssss\",\"confideConnection\":\"100%\",\"confideContent\":\"没有人出生就是完美的，只有不断地相信自己才能成就自己的梦想\",\"confidedIcon\":\"https://img.ydlcdn.com/file/2018/03/15/p5hmpru0n0dt5331.png\",\"confideLine\":2,\"confideHearNum\":\"已聆听2882次\"},{\"confidedId\":\"123\",\"confidedName\":\"海伦\",\"confideSex\":0,\"confideNum\":\"8513人\",\"confideVoice\":\"http://ssssssssssssssssss\",\"confideConnection\":\"100%\",\"confideContent\":\"没有人出生就是完美的，只有不断地相信自己才能成就自己的梦想\",\"confidedIcon\":\"https://img.ydlcdn.com/file/2018/03/15/p5hmpru0n0dt5331.png\",\"confideLine\":3,\"confideHearNum\":\"已聆听2882次\"}],\"head\":{\"title\":\"听声寻人\",\"subTitle\":\"更多\"},\"diviLine\":1}]"
        val gson = Gson()
        val list = gson.fromJson<MutableList<ConfideHomeDataBean>>(json, object : TypeToken<MutableList<ConfideHomeDataBean>>() {

        }.type)
        updateCache(list)
        mView.confideHomeResponse(list)
    }

    /**
     * 更新本地缓存
     */
    private fun updateCache(list : MutableList<ConfideHomeDataBean>){
        YDLAsyncUtils.async(object : YDLAsyncUtils.AsyncObjecyer{
            override fun doAsyncAction() {
                var gson = Gson()
                var json = gson.toJson(list)
                YDLCacheUtils.saveConfideHomeData(json)
            }
        })
    }

    /**
     * 为你推荐列表(筛选调用)
     */
    override fun recommendList(param : ConfideRecommendParam) {
        if (!RxNetTool.isConnected(mView.getContext())){
            mView.showError1("网络不给力")
            return
        }
        val disposable = mModel.recommendList(param)
                .map { it }
                .filter { it != null }
                .compose(RxUtils.applySchedulers(mView as IView))
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(Consumer {
                    mView.recommendListResponse(it)
                }, object : ThrowableConsumer() {
                    override fun accept(msg: String) {
                        mView.showError1(msg)
                    }
                })
    }

    /**
     * 为你推荐列表（翻页时调用）
     */
    override fun recommendListMore(param: ConfideRecommendParam) {
        if (!RxNetTool.isConnected(mView.getContext())){
            mView.showError1("网络不给力")
            return
        }
        val disposable = mModel.recommendList(param)
                .map { it }
                .filter { it != null }
                .compose(RxUtils.applySchedulers(mView as IView))
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(Consumer {
                    mView.recommendListMoreResponse(it)
                }, object : ThrowableConsumer() {
                    override fun accept(msg: String) {
                        mView.showError(msg)
                        mView.showError1(msg)
                    }
                })
    }
}