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.ad.video.VedioAdingManager
import com.mints.goodmoney.common.AppConfig
import com.mints.goodmoney.common.Constant
import com.mints.goodmoney.manager.TTPreLoadExpressManager
import com.mints.goodmoney.manager.UserManager
import com.mints.goodmoney.mvp.model.MainVedioMsgBean
import com.mints.goodmoney.mvp.model.UserTaskMsgBean
import com.mints.goodmoney.mvp.presenters.HomePresenter
import com.mints.goodmoney.mvp.views.HomeView
import com.mints.goodmoney.ui.activitys.AwardActivity
import com.mints.goodmoney.ui.activitys.WebActivity
import com.mints.goodmoney.ui.fragment.base.BaseFragment
import com.mints.goodmoney.ui.widgets.DialogListener
import com.mints.goodmoney.ui.widgets.PowerDialog
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.little.YLLittleVideoFragment
import kotlinx.android.synthetic.main.fragment_main_first.*
import net.grandcentrix.tray.AppPreferences

/**
 * 描述：首页
 * 作者：孟崔广
 * 时间：2020/10/10 17:30
 */
class MainFragment : BaseFragment(), HomeView, View.OnClickListener {

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

    private val homePresenter by lazy { HomePresenter() }
    private val userManager by lazy { UserManager.getInstance() }
    private val ps by lazy { AppPreferences(context) }
    private var powerDialog: PowerDialog? = null

    // 视频相关
    private var rewardDoubleCoin = 0 // 大金币
    private var rewardCoin = 0 // 小金币
    private var littleVideoFragment: YLLittleVideoFragment? = null
    private val videoMaxCount = 12 // 当前缓存视频id最大数
    private val vedioIdList by lazy { ArrayList<String>() }//记录播放的视频id

    private var isToCreateReward = true // 是否还有剩余红包 服务器返回
    private var isFirstLoadVedio = true // 首次加载视频初始化 本地判断
    private var isAward = false // 是否可以领金币 本地判断

    // 广告权重相关
    private var vedioAdingManager: VedioAdingManager? = null

    // 是否是第一次观看完视频
    private var isFirstWatchVideo = true

    override fun getContentViewLayoutID() = R.layout.fragment_main_first

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

        vedioAdingManager = VedioAdingManager.getInstance(activity)
        // 奖励页预加载 信息流广告
        TTPreLoadExpressManager.getInstance().loadTtFrameLayout()

        // 首次显示权限弹窗
        showPowerDialog()
        // 初始化视频
        showLittle()

        initListener()
    }

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

    override fun onHiddenChanged(hidden: Boolean) {
        littleVideoFragment?.onHiddenChanged(hidden)

        if (hidden) {
            onPause()
        } else {
            onResume()
        }
        super.onHiddenChanged(hidden)
    }

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

            // 打开激活
            uploadDeviceInfo()

            if (!TextUtils.isEmpty(userManager?.userID)) {
                homePresenter.getHallBaseMsg()
            } else {
                homePresenter.userLogin()
            }

            registerPlayerCallBack()
            littleVideoFragment?.onResume()
        }
    }

    private fun uploadDeviceInfo() {
        if (!ps.getBoolean(Constant.FIRST_DEVICE_FLAG, false)) {
            homePresenter.comSaveTerminalInfo(ps)
        }
    }

    override fun onPause() {
        super.onPause()
        if (AppConfig.fragmentClickFlag == Constant.FRAGMENT_CLICK_MAIN) {
            YLPlayerConfig.config().unRegisterPlayerCallback()
        }
        littleVideoFragment?.onPause()
    }

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

    override fun onDestroy() {
        super.onDestroy()

        cdvvYilanTime?.setCountDownVedioListener(null)

        homePresenter.detachView()
    }

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

        // 新人福利
        if (data.userMsg.firstGiveCoin > 0) {
            val bundle = Bundle()
            bundle.putInt(Constant.MAIN_CUR_COIN, data.userMsg.firstGiveCoin)
            bundle.putString(Constant.MAIN_CARRIER_TYPE, Constant.CARRIER_NEW_USER)
            readyGo(AwardActivity::class.java, bundle)
        } else {
            // 离线收益
            if (data.offlineBean.offlineIncome > 0) {
                val bundle = Bundle()
                bundle.putInt(Constant.MAIN_CUR_COIN, data.offlineBean.offlineIncome)
                bundle.putString(Constant.MAIN_CARRIER_TYPE, Constant.CARRIER_OFFLINE_DOUBLE)
                readyGo(AwardActivity::class.java, bundle)
            }
        }

        // 设置视频权限
        vedioAdingManager?.initAdWeight(data.vedioRules.csJ_VEDIO.rate, data.vedioRules.ylH_VEDIO.rate)
        LogUtil.d(TAG, "首页权重值：csjWeight:${data.vedioRules.csJ_VEDIO.rate}    ylhWeight:${data.vedioRules.ylH_VEDIO.rate}")
        // 广告视频数
        AppConfig.csjVedioAdCount = data.vedioRules.csJ_VEDIO.surplus
        AppConfig.ylhAdCount = data.vedioRules.ylH_VEDIO.surplus
        LogUtil.d(TAG, "首页视频数：csjCount:${AppConfig.csjVedioAdCount}    ylhCount:${AppConfig.ylhAdCount}")


        // 调用金币视频信息接口
        homePresenter.getHomeVedioMsg()
    }

    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) {
            // 防止界面切换 重置倒计时
            // 好兔视频已加载 且 红包已转满 且 奖励已领过
            if (!isFirstLoadVedio && !cdvvYilanTime.isPlaying && !isAward) {
                cdvvYilanTime?.reset()
                cdvvYilanTime?.start()
            }
        } else {
            stopDownloadTime()
        }
    }

    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_HOMEVEDIO)
                    bundle.putString(Constant.MAIN_EXTRA_ID, rewardDoubleCoin.toString())
                    readyGo(AwardActivity::class.java, bundle)
                }
            }
        }
    }

    private fun showPowerDialog() {
        if (ps.getBoolean(Constant.LOAN_PERMISSION_FLAG, true)) {
            powerDialog()
        }
    }

    /**
     * 一览视频初始化
     */
    private fun showLittle() {
        val transaction: FragmentTransaction = supportFragmentManager.beginTransaction()
        if (littleVideoFragment == null) {
            littleVideoFragment = YLLittleVideoFragment.newInstance()
            transaction.add(R.id.yilan_fragment_frame_container, littleVideoFragment!!, YLLittleVideoFragment::class.java.simpleName)
        } else {
            transaction.show(littleVideoFragment!!)
        }
        transaction.commitAllowingStateLoss()

    }

    private fun registerPlayerCallBack() {
        YLPlayerConfig.config().registerPlayerCallBack(object : OnPlayerCallBack {
            override fun onStart(pager: String, videoid: String, p2: String?) {
                if (TextUtils.equals(YLPlayerConfig.PAGE_LITTLE, "PAGE_LITTLE")) {
                    // 防止网络异常时， 第一次加载倒计时红包
                    if (isFirstLoadVedio) {
                        isFirstLoadVedio = false
                        initTimeview()
                    } else {
                        resumeDownloadTime(videoid)
                    }
                    LogUtil.d(TAG, "onStart  videoid:${videoid}")
                }
            }

            override fun onPause(pager: String, p1: String?, p2: String?) {
                LogUtil.d(TAG, "onPause  pager:${pager}")
                if (TextUtils.equals(YLPlayerConfig.PAGE_LITTLE, "PAGE_LITTLE")) {
                    pauseDownloadTime()
                }
            }

            override fun onResume(pager: String, videoid: String, p2: String?) {
                if (TextUtils.equals(YLPlayerConfig.PAGE_LITTLE, "PAGE_LITTLE")) {

                    resumeDownloadTime(videoid)
                }
            }

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

            }

            override fun onLoopComplete(pager: String?, videoID: String, taskID: String?, num: Int) {
                if (TextUtils.equals(YLPlayerConfig.PAGE_LITTLE, "PAGE_LITTLE")) {


                    addVedioIdList(videoID)
                    pauseDownloadTime()
                    LogUtil.d(TAG, "onLoopComplete  pager:${pager}   videoID:${videoID}  taskID:${taskID}  num:${num}")
                }
            }

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

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

            override fun onError(pager: String, p1: String?, p2: String?) {
                if (TextUtils.equals(YLPlayerConfig.PAGE_LITTLE, "PAGE_LITTLE")) {

                    pauseDownloadTime()
                }
            }

            override fun onStop(pager: String, p1: String?, p2: String?) {
                if (TextUtils.equals(YLPlayerConfig.PAGE_LITTLE, "PAGE_LITTLE")) {

                    pauseDownloadTime()
                }
            }
        })
    }

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

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

    /**
     *用户主动暂时或网络异常结束后 重新加载倒计时红包
     */
    private fun resumeDownloadTime(id: String) {
        if (!TextUtils.isEmpty(id)) {
            if (vedioIdList.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 vedioTime = ps.getInt(Constant.MAIN_VEDIO_TIME, 30)
        cdvvYilanTime.setTime(vedioTime)
        cdvvYilanTime.start()
    }

    /**
     * 权限弹窗
     */
    private fun powerDialog() {
        powerDialog = PowerDialog(requireActivity(), object : DialogListener() {
            override fun onClick(v: View) {
                when (v.id) {
                    R.id.tv_dialogper_agreement -> {
                        val bundle = Bundle()
                        bundle.putString(WebActivity.WEB_TITLE, getString(R.string.register_name))
                        bundle.putString(WebActivity.WEB_URL, Constant.REGISTER_URL)
                        readyGo(WebActivity::class.java, bundle)
                    }
                    R.id.tv_dialogper_policy -> {
                        val bundle = Bundle()
                        bundle.putString(WebActivity.WEB_TITLE, getString(R.string.privacy_name))
                        bundle.putString(WebActivity.WEB_URL, Constant.PRIVACY_URL)
                        readyGo(WebActivity::class.java, bundle)
                    }
                    R.id.btn_dialogper_back -> {
                        if (activity != null && !activity!!.isFinishing &&
                                powerDialog != null && powerDialog!!.isShowing
                        ) {
                            showToast("请您同意授权,否则将无法使用APP功能")
                        }
                    }
                    R.id.btn_dialogper_next -> {
                        if (activity != null && !activity!!.isFinishing &&
                                powerDialog != null && powerDialog!!.isShowing
                        ) {
                            powerDialog!!.dismiss()
                            ps.put(Constant.LOAN_PERMISSION_FLAG, false)
                        }
                    }
                }
            }
        })
        powerDialog!!.show()
    }
}