package com.yidianling.course.courseNew.home

import android.annotation.SuppressLint
import android.content.Context
import android.os.Handler
import android.text.TextUtils
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.yidianling.common.tools.LogUtil
import com.yidianling.common.tools.ToastUtil
import com.yidianling.course.bean.CourseCouponBean
import com.yidianling.course.coursePlay.common.net.RetrofitUtils
import com.yidianling.router.RouterManager
import com.yidianling.ydlcommon.http.RxUtils
import com.yidianling.ydlcommon.http.ThrowableConsumer
import com.yidianling.ydlcommon.router.YdlCommonRouterManager
import com.yidianling.ydlcommon.utils.AssetsUtils
import com.yidianling.ydlcommon.utils.YDLAsyncUtils
import com.yidianling.ydlcommon.utils.YDLCacheUtils
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.functions.Consumer
import io.reactivex.schedulers.Schedulers
import java.text.SimpleDateFormat
import java.util.*

/**
 * Created by Jim on 2018/7/11 0011.
 */
class CourseHomePresenter(var view: ICourseHomeView) {

    private var hasRequestCoupon = false

    private val compositeSubscription = CompositeDisposable()
    /**
     * 加载本地缓存
     */
    fun localData(context: Context) {
        YDLAsyncUtils.asyncAsResult(object : YDLAsyncUtils.AsyncObjecyerResult {
            override fun doAsyncAction(): Any {

                var cacheData = YDLCacheUtils.getCourseHomeData()

                if (cacheData?.isEmpty()!!) {
                    cacheData = String(AssetsUtils.getAssertsFile(context, "course_home.json")!!)
                }

                return cacheData
            }

            override fun asyncResult(`object`: Any?) {

                if (`object` is String) {
                    val gson = Gson()
                    if (!TextUtils.isEmpty(`object`)) {
                        val list = gson.fromJson<List<ResultBean>>(`object`, object : TypeToken<List<ResultBean>>() {}.type)
                        view.showBody(list)
                    }
                }
            }
        })
    }

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

    fun fetchData() {
        compositeSubscription.add(RetrofitUtils.getCoursesHomePage()
                .subscribeOn(Schedulers.io())
                .compose(RxUtils.resultJavaData())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({ response ->
                    view.hideRefreshView()
                    view.showBody(response)
                    //更新本地缓存数据
                    updateCache(response)
                }, { t: Throwable? ->
                    view.hideRefreshView()
                    view.showLoadErrorView(t)
                    LogUtil.e("CoursesHomePage data fetch error: " + t.toString())
                }))
    }


    /**
     * 获取优惠券信息
     */
    fun prepareCoupon() {
        //判断是否登录  以及本次app启动后是否已经请求过
        if (RouterManager.getUserRouter()?.isLogin() == true && !hasRequestCoupon) {
            Handler().postDelayed({
                //优惠券逻辑
                if (compareCouponTime()) {
                    getCouponData()
                }
            }, 2000)
        }
    }

    /**
     * 获取可以领取的课程优惠券
     *
     * @param uid         uid
     * @param services    适用服务 1预约咨询 2电话倾诉 3课程（用户课程 专家课程） 5测评
     * @param receiveType 领取条件方式 1前台领取 2链接领取
     * @param applyEnds   适用终端 1PC官网 2wap站点 3用户app 4好杮app 5专家app
     * @return
     */
    @SuppressLint("SimpleDateFormat")
    private fun getCouponData() {
        val (userId) = YdlCommonRouterManager.getYdlCommonRoute().getUserInfo() ?: return
        val disposable = RetrofitUtils.getCourseCoupons(userId, "3", "1", "3")
                .compose(RxUtils.netCheck())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .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)

                    if (it?.data != null && !it.data.isEmpty()) {
                        YDLCacheUtils.saveCouponTime(userId, nowTime)
                        view.couponDataResponse(it.data)
                    }
                }, object : ThrowableConsumer() {
                    override fun accept(msg: String) {
                    }
                })
        compositeSubscription.add(disposable)
    }


    /**
     * 领取优惠券
     */
    fun receiveCoupon(list: List<CourseCouponBean>) {
        val (userId) = YdlCommonRouterManager.getYdlCommonRoute().getUserInfo() ?: return
        val couponIds = ArrayList<String>()
        for (bean in list) {
            couponIds.add(bean.id)
        }
        val bean = CouponReceiveBean()
        bean.couponIds = couponIds
        bean.uid = userId
        val couponIdsStr = Gson().toJson(bean)
        view.showRefreshView()
        val disposable = RetrofitUtils.receiveCoupon(couponIdsStr)
                .compose(RxUtils.netCheck())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(Consumer {
                    view.hideRefreshView()
                    view.receiveCouponResponse(it)
                }, object : ThrowableConsumer() {
                    override fun accept(msg: String) {
                        ToastUtil.toastShort(msg)
                        view.hideRefreshView()
                    }
                })
        compositeSubscription.add(disposable)
    }

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

    fun onDestroy() {
        compositeSubscription.dispose()
    }

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

}