package com.mints.goodmoney.ui.fragment

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.text.TextUtils
import android.view.View
import androidx.fragment.app.FragmentTransaction
import com.mints.goodmoney.R
import com.mints.goodmoney.common.AppConfig
import com.mints.goodmoney.common.Constant
import com.mints.goodmoney.mvp.model.MainVedioMsgBean
import com.mints.goodmoney.mvp.presenters.HorizChannelPresenter
import com.mints.goodmoney.mvp.views.HorizChannelView
import com.mints.goodmoney.ui.activitys.AwardActivity
import com.mints.goodmoney.ui.fragment.base.BaseFragment
import com.mints.goodmoney.utils.LogUtil
import com.yilan.sdk.player.ylplayer.YLPlayerConfig
import com.yilan.sdk.player.ylplayer.callback.OnPlayerCallBack
import com.yilan.sdk.ui.category.ChannelFragment
import kotlinx.android.synthetic.main.fragment_horiz_channel.cdvvYilanTime
import kotlinx.android.synthetic.main.fragment_horiz_channel.vs_tips
import net.grandcentrix.tray.AppPreferences

class HorizChannelFragment : BaseFragment(), HorizChannelView, View.OnClickListener {

    private val TAG = HorizChannelFragment::class.java.simpleName

    private val horizChannelPresenter by lazy { HorizChannelPresenter() }

    private val ps by lazy { AppPreferences(context) }

    private var channelFragment: ChannelFragment? = null

    private val videoMaxCount = 12 // 当前缓存视频id最大数
    private val videoIdList by lazy { ArrayList<String>() }//记录播放的视频id

    // 是否是第一次观看完视频
    private var isFirstWatchVideo = true
    private var isFirstLoadVideo = true // 首次加载视频初始化
    private var rewardDoubleCoin = 0 // 大金币
    private var rewardCoin = 0 // 小金币
    private var isToCreateReward = true // 是否还有剩余红包 服务器返回
    private var isAward = false // 是否可以领金币 本地判断

    override fun initViewsAndEvents() {
        horizChannelPresenter.attachView(this)

        initChannelFragment()
        initListener()

    }

    private fun initListener() {
        cdvvYilanTime.setOnClickListener(this)
    }

    override fun getHomeVedioMsgSuc(data: MainVedioMsgBean) {
        if (activity == null || requireActivity().isFinishing) {
            return
        }

        ps.put(Constant.MAIN_VEDIO_TIME, data.createRewardNeedTime)

        rewardCoin = data.rewardCoin
        rewardDoubleCoin = data.rewardDoubleCoin
        isToCreateReward = data.isToCreateReward

        if (isToCreateReward) {
            // 防止界面切换 重置倒计时
            // 第一次能过 isFirstLoadVedio 判断好兔先加载视频
            if (!isFirstLoadVideo && !cdvvYilanTime.isPlaying && !isAward) {
                cdvvYilanTime?.reset()
                cdvvYilanTime?.start()
            }
        } else {
            stopDownloadTime()
        }
    }

    private fun initChannelFragment() {
        val transaction: FragmentTransaction = childFragmentManager.beginTransaction()
        if (channelFragment == null) {

            channelFragment = ChannelFragment()
            transaction.add(R.id.yilan_fragment_frame_container, channelFragment!!, ChannelFragment::class.java.simpleName)
        } else {
            transaction.show(channelFragment!!)
        }
        transaction.commitAllowingStateLoss()

    }

    private fun registerPlayerCallBack() {
        // 设置点击的item播放状态,callback返回true标识用户已经处理了event，返回false，标识使用播放器内部逻辑处理event。
        YLPlayerConfig.config().registerPlayerCallBack(object : OnPlayerCallBack {

            override fun onStart(p0: String?, videoid: String, p2: String?) {
                // 防止网络异常时， 第一次加载倒计时红包
                if (isFirstLoadVideo) {
                    isFirstLoadVideo = false
                    initTimeView()
                } else {
                    resumeDownloadTime(videoid)
                }
            }

            override fun onPause(p0: String?, p1: String?, p2: String?) {
                LogUtil.d(TAG, "onPause  pager:${p0}")
                pauseDownloadTime()
            }

            override fun onResume(p0: String?, videoid: String, p2: String?) {
                resumeDownloadTime(videoid)
            }

            override fun onComplete(p0: String?, videoid: String, p2: String?) {

            }

            override fun onLoopComplete(pager: String?, videoID: String, taskID: String?, num: Int) {
                addVedioIdList(videoID)
                pauseDownloadTime()
            }

            override fun onStuckStart(p0: String?, p1: String?, p2: String?) {
            }

            override fun onStuckEnd(p0: String?, p1: String?, p2: String?) {
            }

            override fun onError(p0: String?, p1: String?, p2: String?) {
                pauseDownloadTime()
            }

            override fun onStop(p0: String?, p1: String?, p2: String?) {
                pauseDownloadTime()
            }
        })
    }

    override fun getContentViewLayoutID() = R.layout.fragment_horiz_channel

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.cdvvYilanTime -> {
                if (isAward && isToCreateReward) {
                    isAward = false

                    val bundle = Bundle()
                    bundle.putInt(Constant.MAIN_CUR_COIN, rewardCoin)
                    bundle.putString(Constant.MAIN_CARRIER_TYPE, Constant.CARRIER_SMALLHOMEVEDIO)
                    bundle.putString(Constant.MAIN_EXTRA_ID, rewardDoubleCoin.toString())
                    readyGo(AwardActivity::class.java, bundle)
                }
            }
        }
    }

    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        super.setUserVisibleHint(isVisibleToUser)
        channelFragment?.userVisibleHint = isVisibleToUser
    }

    override fun onHiddenChanged(hidden: Boolean) {
        if (hidden) {
            onPause()
        } else {
            onResume()
        }
        super.onHiddenChanged(hidden)

        channelFragment?.onHiddenChanged(hidden)
    }

    override fun onResume() {
        super.onResume()
        if (AppConfig.fragmentClickFlag == Constant.FRAGMENT_CLICK_CHANNEL) {

            // 调用金币视频信息接口
            horizChannelPresenter.getSmallHomeVedioBaseMsg()

            registerPlayerCallBack()
            channelFragment?.onResume()
        }
    }

    override fun onPause() {
        super.onPause()
        if (AppConfig.fragmentClickFlag == Constant.FRAGMENT_CLICK_CHANNEL) {
            YLPlayerConfig.config().unRegisterPlayerCallback()
        }
        channelFragment?.onPause()
//        pauseDownloadTime()
    }

    /**
     * 倒计时红包暂停
     */
    private fun pauseDownloadTime() {
        cdvvYilanTime?.pause()
    }

    /**
     * 将播放的id记录到list中
     */
    private fun addVedioIdList(id: String) {
        // 达到12个视频时 删除前10个记录
        if (videoIdList.size >= videoMaxCount) {
            videoIdList.subList(0, 10).clear()
        }
        if (!videoIdList.contains(id)) videoIdList.add(id)
    }

    /**
     *用户主动暂时或网络异常结束后 重新加载倒计时红包
     */
    private fun resumeDownloadTime(id: String) {
        if (!TextUtils.isEmpty(id)) {
            if (videoIdList.contains(id)) {
                cdvvYilanTime?.pause()
                return
            }

            if (!isAward) {
                cdvvYilanTime?.resume()
            }
        }
    }

    /**
     * 停止转动
     */
    private fun stopDownloadTime() {
        cdvvYilanTime?.stop()
    }

    /**
     * 红包倒计时初始化
     */
    private fun initTimeView() {
        cdvvYilanTime.setCountDownVedioListener {
            if (isFirstWatchVideo) {
                // 第一次观看完视频提醒用户
                val vs = vs_tips.inflate()
                Handler(Looper.getMainLooper()).postDelayed({
                    vs.visibility = View.GONE
                }, 3000)
                isFirstWatchVideo = false
            }

            // 转满一圈，可领金币标记
            isAward = true
            cdvvYilanTime?.showRedbox()
            stopDownloadTime()
        }
        val videoTime = ps.getInt(Constant.MAIN_VEDIO_TIME, 30)
        cdvvYilanTime.setTime(videoTime)
        cdvvYilanTime.start()
    }


    override fun onDestroy() {
        super.onDestroy()

        cdvvYilanTime?.setCountDownVedioListener(null)

        horizChannelPresenter.detachView()
    }

}