package com.gh.gamecenter.video.detail

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import androidx.core.os.bundleOf
import androidx.fragment.app.Fragment
import com.gh.common.constant.Config
import com.gh.common.util.DirectUtils
import com.gh.common.util.LogUtils
import com.gh.common.view.AdBannerView
import com.gh.gamecenter.R
import com.gh.gamecenter.WebActivity
import com.gh.gamecenter.common.base.adapter.FragmentAdapter
import com.gh.gamecenter.common.base.fragment.BaseLazyFragment
import com.gh.gamecenter.common.constant.Constants
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.common.entity.LinkEntity
import com.gh.gamecenter.common.utils.ImageUtils
import com.gh.gamecenter.common.utils.countDownTimer
import com.gh.gamecenter.common.utils.doOnPageSelected
import com.gh.gamecenter.common.utils.visibleIf
import com.gh.gamecenter.core.utils.MtaHelper
import com.gh.gamecenter.core.utils.SPUtils
import com.gh.gamecenter.databinding.FragmentHomeVideoBinding
import com.gh.gamecenter.entity.SettingsEntity
import com.gh.gamecenter.eventbus.EBRecommed
import io.reactivex.disposables.Disposable
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.util.*

/**
 * 首页视频页面
 */
class HomeVideoFragment : BaseLazyFragment() {

    private var mNewHint: View? = null
    private var newestVideoDetailFragment: VideoDetailContainerFragment? = null
    private var recommendVideoDetailFragment: VideoDetailContainerFragment? = null
    private val fragments = ArrayList<Fragment>()
    private var titles = arrayListOf("关注", "推荐")
    private var mAdCountDownTimer: Disposable? = null
    private var mAdLeftCountDownTimer: Disposable? = null
    private var mAdRightCountDownTimer: Disposable? = null
    private lateinit var mBinding: FragmentHomeVideoBinding

    override fun getLayoutId(): Int = 0

    override fun getInflatedLayout(): View {
        return FragmentHomeVideoBinding.inflate(LayoutInflater.from(requireContext()), null, false).apply {
            mBinding = this
        }.root
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //预加载广告图片
        val videoAdvertisement = Config.getSettings()?.videoAdvertisement
        videoAdvertisement?.left?.let { ads ->
            ads.forEach { ImageUtils.prefetchToDiskCache(it.image) }
        }
        videoAdvertisement?.right?.let { ads ->
            ads.forEach { ImageUtils.prefetchToDiskCache(it.image) }
        }
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val mLocation = arguments?.getString(EntranceConsts.KEY_LOCATION) ?: ""
        if (mLocation != VideoDetailContainerViewModel.Location.USER_UPLOADED_VIDEO.value) {
            mBinding.moreIv.visibility = View.VISIBLE
            mBinding.moreIv.setOnClickListener {
                getCurrentFragment()?.showMoreMenuDialog()
            }
        }
    }

    override fun onFragmentFirstVisible() {
        super.onFragmentFirstVisible()
        val mIsHomeVideo = arguments?.getBoolean(EntranceConsts.KEY_IS_HOME_VIDEO, false) ?: false
        titles = if (mIsHomeVideo) {
            arrayListOf("关注", "推荐")
        } else {
            arrayListOf("推荐")
        }
        if (mIsHomeVideo) {
            val newestBundle = bundleOf(EntranceConsts.KEY_UUID to UUID.randomUUID().toString())
            newestBundle.putAll(arguments)
            newestBundle.putString(EntranceConsts.KEY_PATH, "视频流-关注Tab")
            newestBundle.putString(
                EntranceConsts.KEY_LOCATION,
                VideoDetailContainerViewModel.Location.VIDEO_ATTENTION.value
            )
            newestVideoDetailFragment = VideoDetailContainerFragment()
            newestVideoDetailFragment?.with(newestBundle)
            fragments.add(newestVideoDetailFragment!!)
        }


        recommendVideoDetailFragment = VideoDetailContainerFragment()
        if (mIsHomeVideo) {
            val recommendBundle = bundleOf(EntranceConsts.KEY_UUID to UUID.randomUUID().toString())
            recommendBundle.putAll(arguments)
            recommendBundle.putString(EntranceConsts.KEY_PATH, "视频流-推荐Tab")
            recommendBundle.putString(
                EntranceConsts.KEY_LOCATION,
                VideoDetailContainerViewModel.Location.VIDEO_CHOICENESS.value
            )
            recommendVideoDetailFragment?.with(recommendBundle)
        } else {
            recommendVideoDetailFragment?.with(arguments)
        }

        fragments.add(recommendVideoDetailFragment!!)

        mBinding.mViewPager.apply {
            offscreenPageLimit = fragments.size
            adapter = FragmentAdapter(childFragmentManager, fragments, titles)
            if (mIsHomeVideo) {
                currentItem = 1
            }
            doOnPageSelected {
                if (it == 0) {
                    SPUtils.setBoolean(Constants.SP_HOME_NEW_VIDEO_TIPS, true)
                    mNewHint?.visibility = View.GONE
                    MtaHelper.onEvent("视频流_最新", "顶部Tab", "最新Tab")
                    LogUtils.uploadVideoStreamingPlaying(
                        "点击最新Tab",
                        "",
                        "视频流-最新Tab",
                        arguments?.getString(EntranceConsts.KEY_REFERER),
                        "",
                        newestVideoDetailFragment?.arguments?.getString(
                            EntranceConsts.KEY_UUID
                        )
                            ?: "",
                        0.0,
                        0,
                        0,
                        "play"
                    )
                } else {
                    MtaHelper.onEvent("视频流_推荐", "顶部Tab", "推荐Tab")
                    LogUtils.uploadVideoStreamingPlaying(
                        "点击推荐Tab",
                        "",
                        "视频流-推荐Tab",
                        arguments?.getString(EntranceConsts.KEY_REFERER),
                        "",
                        recommendVideoDetailFragment?.arguments?.getString(EntranceConsts.KEY_UUID)
                            ?: "",
                        0.0,
                        0,
                        0,
                        "play"
                    )
                }
            }
        }
        mBinding.mTabLayout.setupWithViewPager(mBinding.mViewPager)
        if (mIsHomeVideo) {
            mBinding.mTabIndicator.visibility = View.VISIBLE
            mBinding.mTabIndicator.setupWithTabLayout(mBinding.mTabLayout)
            mBinding.mTabIndicator.setupWithViewPager(mBinding.mViewPager)
            mBaseHandler.postDelayed({
                if (mBinding.mViewPager != null) {
                    mBinding.mTabIndicator.generatePath(mBinding.mViewPager.currentItem, 0F)
                }
            }, 10)
        }

        if (mIsHomeVideo) {
            for (i in 0 until mBinding.mTabLayout.childCount) {
                val tab = mBinding.mTabLayout.getTabAt(i) ?: continue
                val tabView = provideTabView(i, if (tab.text != null) tab.text!!.toString() else "")
                    ?: continue
                tab.customView = tabView
            }
            val homeNewVideoTips = SPUtils.getBoolean(Constants.SP_HOME_NEW_VIDEO_TIPS, false)
            mNewHint?.visibleIf(!homeNewVideoTips)
        }
        setAdvertisement(0)
    }

    fun getCurrentFragment(): VideoDetailContainerFragment? {
        val mIsHomeVideo = arguments?.getBoolean(EntranceConsts.KEY_IS_HOME_VIDEO, false) ?: false
        return if (mIsHomeVideo) {
            if (mBinding.mViewPager.currentItem == 0) {
                newestVideoDetailFragment
            } else {
                recommendVideoDetailFragment
            }
        } else {
            recommendVideoDetailFragment
        }
    }

    override fun onResume() {
        super.onResume()
        mBinding.adBannerLeft.resumePage()
        mBinding.adBannerRight.resumePage()
    }

    override fun onPause() {
        super.onPause()
        mBinding.adBannerLeft.pausePage()
        mBinding.adBannerRight.pausePage()
    }

    fun changePosition(position: Int) {
        setAdvertisement(position)
    }

    fun changeAdAlpha(alpha: Float) {
        mBinding.marqueeAd.alpha = alpha
        mBinding.adBannerLeft.alpha = alpha
        mBinding.adBannerRight.alpha = alpha
    }

    private fun provideTabView(position: Int, tabTitle: String): View? {
        if (position == 0) {
            val container = LayoutInflater.from(context).inflate(R.layout.home_video_tab_item, null)
            container.findViewById<TextView>(R.id.content).text = tabTitle
            mNewHint = container.findViewById<View>(R.id.hint)
            return container
        }
        return null
    }

    private fun setAdvertisement(position: Int) {
        val videoAdvertisement = Config.getSettings()?.videoAdvertisement
        videoAdvertisement?.run {
            if (!center.isNullOrEmpty()) {
                if (position == (center!![0].frequency)) {
                    mBinding.marqueeAd.visibility = View.VISIBLE
                    mBinding.marqueeAdTitle.text = center!![0].title
                    mBinding.marqueeAdTitle.isSelected = true

                    mBinding.marqueeAd.setOnClickListener {
                        val pos = getCurrentFragment()?.viewPagerLayoutManager?.findFirstCompletelyVisibleItemPosition()
                            ?: -1
                        if (pos < 0) return@setOnClickListener
                        MtaHelper.onEvent("视频详情", "视频广告", center!![0].title)
                        getCurrentFragment()?.findVisibleVideoViewByPosition()?.let {
                            it.recordMta("视频广告", center!![0].title)
                            it.uploadVideoStreamingPlaying("点击广告")
                        }

                        DirectUtils.directToLinkPage(
                            requireContext(),
                            LinkEntity(
                                link = center!![0].link,
                                type = center!![0].linkType,
                                text = center!![0].text,
                                display = center!![0].display,
                                community = center!![0].linkCommunity
                            ),
                            "", "视频详情"
                        )
                    }
                    if (center!![0].duration > 0 && mAdCountDownTimer == null) {
                        mAdCountDownTimer = startTimer(center!![0].duration.toLong(), mBinding.marqueeAd)
                    }
                }
            }
            if (!left.isNullOrEmpty()) {
                setAdBanner(mBinding.adBannerLeft, left!!, position)
            }
            if (!right.isNullOrEmpty()) {
                setAdBanner(mBinding.adBannerRight, right!!, position)
            }
        }
    }

    private fun setAdBanner(banner: AdBannerView, ads: ArrayList<SettingsEntity.Advertisement>, position: Int) {
        val adDatas = banner.getAdDatas()
        if (adDatas.isEmpty() && position == ads[0].frequency) {
            banner.visibility = View.VISIBLE
            banner.start(ads)
            banner.onItemClick = { pos ->
                val videoPos = getCurrentFragment()?.viewPagerLayoutManager?.findFirstCompletelyVisibleItemPosition()
                    ?: -1
                if (videoPos >= 0) {
                    MtaHelper.onEvent("视频详情", "视频广告", ads[pos].title)
                    getCurrentFragment()?.findVisibleVideoViewByPosition()?.let {
                        it.recordMta("视频广告", ads[pos].title)
                        it.uploadVideoStreamingPlaying("点击广告")
                    }

                    if (ads[pos].linkType == "web") {
                        // 当前入口打开Web页面要显示分享按钮
                        val webIntentByShare = WebActivity.getWebIntentByShare(context, ads[pos].link, true, "视频流广告位")
                        startActivity(webIntentByShare)
                    } else {
                        DirectUtils.directToLinkPage(
                            requireContext(),
                            LinkEntity(
                                link = ads[pos].link,
                                type = ads[pos].linkType,
                                text = ads[pos].text,
                                display = ads[pos].display,
                                community = ads[pos].linkCommunity
                            ),
                            "", "视频详情"
                        )
                    }
                }
            }
            if (ads[0].duration > 0 && banner == mBinding.adBannerLeft && mAdLeftCountDownTimer == null) {
                mAdLeftCountDownTimer = startTimer(ads[0].duration.toLong(), banner)
            }
            if (ads[0].duration > 0 && banner == mBinding.adBannerRight && mAdRightCountDownTimer == null) {
                mAdRightCountDownTimer = startTimer(ads[0].duration.toLong(), banner)
            }
        }
    }

    //广告定时器
    private fun startTimer(countDownTime: Long, view: View): Disposable {
        return countDownTimer(countDownTime) { finish, _ ->
            if (finish) {
                view.visibility = View.GONE
                getCurrentFragment()?.findVisibleVideoViewByPosition()?.uploadVideoStreamingPlaying("关闭广告")
            }
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        if (mAdCountDownTimer != null && !mAdCountDownTimer!!.isDisposed) {
            mAdCountDownTimer?.dispose()
            mAdCountDownTimer = null
        }
        if (mAdLeftCountDownTimer != null && !mAdLeftCountDownTimer!!.isDisposed) {
            mAdLeftCountDownTimer?.dispose()
            mAdLeftCountDownTimer = null
        }
        if (mAdRightCountDownTimer != null && !mAdRightCountDownTimer!!.isDisposed) {
            mAdRightCountDownTimer?.dispose()
            mAdRightCountDownTimer = null
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        getCurrentFragment()?.onActivityResult(requestCode, resultCode, data)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEventMainThread(event: EBRecommed?) {
        if (fragments.size > 1) {
            mBinding.mViewPager.currentItem = 1
        }
    }
}