package com.yidianling.course

import CoursePlugin
import android.annotation.SuppressLint
import android.os.Handler
import android.text.TextUtils
import com.alibaba.android.arouter.launcher.ARouter
import com.channel.ydl_flutter_base.base.BaseFlutterFragment
import com.google.gson.Gson
import com.ydl.ydl_router.manager.YDLRouterManager
import com.ydl.ydlcommon.data.http.BaseResponse
import com.ydl.ydlcommon.data.http.RxUtils
import com.ydl.ydlcommon.data.http.ThrowableConsumer
import com.ydl.ydlcommon.router.YdlCommonRouterManager
import com.ydl.ydlcommon.utils.YDLCacheUtils
import com.ydl.ydlcommon.utils.actionutil.ActionCountUtils
import com.ydl.ydlcommon.utils.remind.ToastHelper
import com.yidianling.common.tools.ToastUtil
import com.yidianling.course.bean.CourseCouponBean
import com.yidianling.course.constants.CourseBIConstants
import com.yidianling.course.flutterPlugin.CourseSendPlugin
import com.yidianling.course.net.CourseRetrofitUtils
import com.yidianling.course.router.CourseIn
import com.yidianling.course.widget.CourseCouponDialog
import io.flutter.view.FlutterView
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.functions.Consumer
import io.reactivex.schedulers.Schedulers
import java.text.SimpleDateFormat
import java.util.*

/**
 * @author jiucheng
 * @描述:课程频道页（flutter）
 * @Copyright Copyright (c) 2018
 * @Company 壹点灵
 * @date 2019/10/22
 */
class FlutterCourseHomeFragment : BaseFlutterFragment() {

    private var hasRequestCoupon = false
    private var dialog: CourseCouponDialog? = null

    override fun initChannelPlugin(flutterView: FlutterView) {
        CoursePlugin.register(this, flutterView)

        CourseSendPlugin.initContext(this, flutterView)

    }

    override fun initialRoute(): String {
        return "course/home"
    }

    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        super.setUserVisibleHint(isVisibleToUser)
        if (isVisibleToUser) {
            prepareCoupon()

            ActionCountUtils.count(CourseBIConstants.CourseHomeEvent.POSITION_COURSE_HOME_PAGE_VISIT)
        }
    }

    /**
     * 获取优惠券信息
     */
    private fun prepareCoupon() {
        //判断是否登录  以及本次app启动后是否已经请求过
        if (CourseIn.getUserService()?.isLogin() && !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", "CheckResult")
    private fun getCouponData() {
        val (userId) = YdlCommonRouterManager.getYdlCommonRoute().getUserInfo() ?: return
        CourseRetrofitUtils.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.isNotEmpty()) {
                    YDLCacheUtils.saveCouponTime(userId, nowTime)
                    couponDataResponse(it.data)
                }
            }, object : ThrowableConsumer() {
                override fun accept(msg: String) {
                }
            })
    }

    /**
     * 可领取的优惠券列表
     */
    private fun couponDataResponse(data: List<CourseCouponBean>) {
        if (dialog == null) {
            dialog = CourseCouponDialog(
                activity,
                data,
                object : CourseCouponDialog.OnClickEnsureListener {
                    override fun clickUse(toLink: String) {
                        YDLRouterManager.router(toLink)
                        dialog!!.dismiss()
                    }

                    override fun clickEnsure(status: Int) {
                        if (status == CourseCouponDialog.STATUS_RECEIVER) {
                            receiveCoupon(data)
                        } else {
                            dialog!!.dismiss()

                            //查看我的卡券
                            ARouter.getInstance().build("/mine/redpacket")
                                .withString("is_from_main", "1")
                                .navigation()
                        }
                    }
                })
        }
        dialog!!.show()
    }


    /**
     * 领取优惠券
     */
    @SuppressLint("CheckResult")
    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)
        CourseRetrofitUtils.receiveCoupon(couponIdsStr)
            .compose(RxUtils.netCheck())
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(Consumer {
                receiveCouponResponse(it)
            }, object : ThrowableConsumer() {
                override fun accept(msg: String) {
                    ToastUtil.toastShort(msg)
                }
            })
    }

    /**
     * 优惠券领取成功
     */
    private fun receiveCouponResponse(data: BaseResponse<List<String>>) {
        if (data.code == 200) {
            dialog?.updateStatus(CourseCouponDialog.STATUS_GET, data.data)
        } else {
            ToastHelper.show(data.msg)
        }
    }

    /**
     * 对比上次获取优惠券时间，若时间差超过一天，则再次请求，否则不获请求
     */
    @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))
        }
    }

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