package com.gh.gamecenter.gamedetail.video

import android.app.Activity
import android.content.Context
import android.media.AudioManager
import android.util.AttributeSet
import android.view.*
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.SeekBar
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import com.gh.common.util.LogUtils
import com.gh.download.cache.ExoCacheManager
import com.gh.gamecenter.R
import com.gh.gamecenter.common.base.GlobalActivityManager
import com.gh.gamecenter.common.observer.MuteCallback
import com.gh.gamecenter.common.observer.VolumeObserver
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.core.runOnIoThread
import com.gh.gamecenter.core.runOnUiThread
import com.gh.gamecenter.core.utils.MD5Utils
import com.gh.gamecenter.gamedetail.GameDetailViewModel
import com.gh.gamecenter.gamedetail.entity.CoverTabEntity
import com.gh.gamecenter.home.video.ScrollCalculatorHelper
import com.gh.gamecenter.video.detail.CustomManager
import com.lightgame.utils.Utils
import com.shuyu.gsyvideoplayer.utils.CommonUtil
import com.shuyu.gsyvideoplayer.utils.Debuger
import com.shuyu.gsyvideoplayer.utils.GSYVideoType
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer
import com.shuyu.gsyvideoplayer.video.base.GSYVideoView
import com.shuyu.gsyvideoplayer.video.base.GSYVideoViewBridge
import io.reactivex.disposables.Disposable
import java.util.*

class TopVideoView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) :
    StandardGSYVideoPlayer(context, attrs) {

    private var mMuteCallback: MuteCallback
    private var mVolumeObserver: VolumeObserver? = null

    var video: CoverTabEntity.Video? = null
    var viewModel: GameDetailViewModel? = null
    var uuid = UUID.randomUUID().toString()
    private var mMuteDisposable: Disposable? = null
    private var mContentLength = 0.0
    private var mIsAutoPlay = false
    private var mLastGetContentLengthTime = 0L

    var showOrHideCoverFilter: ((Boolean) -> Unit)? = null
    var scrollCalculatorHelper: GameDetailScrollCalculatorHelper? = null

    init {
        post {
            gestureDetector =
                GestureDetector(getContext().applicationContext, object : GestureDetector.SimpleOnGestureListener() {
                    override fun onSingleTapConfirmed(e: MotionEvent): Boolean {
                        if (!mChangePosition && !mChangeVolume && !mBrightness) {
                            onClickUiToggle(e)
                        }
                        return super.onSingleTapConfirmed(e)
                    }
                })

            if (mIfCurrentIsFullscreen) {
                showBackBtn()
            } else {
                hideBackBtn()
            }

            findViewById<View>(R.id.volume).setOnClickListener { toggleMute() }
        }

        mMuteCallback = object : MuteCallback {
            override fun onMute(isMute: Boolean) {
                if (isMute) {
                    mute()
                } else {
                    unMute()
                }
            }
        }

        if (!isInEditMode) {
            mVolumeObserver = VolumeObserver(mMuteCallback)
        }

        setBackFromFullScreenListener {
            if (it.id == R.id.fullscreen || it.id == R.id.back) {
                SensorsBridge.trackGameDetailVideoClick(
                    gameName = viewModel?.game?.name ?: "",
                    gameId = viewModel?.game?.id ?: "",
                    gameType = viewModel?.game?.categoryChinese ?: "",
                    lastPageName = GlobalActivityManager.getLastPageEntity().pageName,
                    lastPageId = GlobalActivityManager.getLastPageEntity().pageId,
                    action = if (it.id == R.id.fullscreen) "退出全屏" else "点击返回",
                    playType = if (mIsAutoPlay) "自动播放" else "主动播放",
                    isFullScreen = mIfCurrentIsFullscreen,
                    sequence = viewModel?.coverTabSequence ?: 1,
                    tabName = viewModel?.coverTabName ?: "",
                    playLength = (currentPositionWhenPlaying / 1000).toString()
                )
            }
            clearFullscreenLayout()
        }

        findViewById<View>(R.id.errorBtn)?.setOnClickListener {
            debounceActionWithInterval(it.id, 1000) {
                if (!com.shuyu.gsyvideoplayer.utils.NetworkUtils.isAvailable(mContext)) {
                    Utils.toast(context, "网络异常，请检查手机网络状态")
                    setViewShowState(mStartButton, INVISIBLE)
                    findViewById<View>(R.id.errorContainer)?.visibility = VISIBLE
                    return@debounceActionWithInterval
                }
                startPlayLogic(false)
            }
        }
    }

    //这个必须配置最上面的构造才能生效
    override fun getLayoutId(): Int {
        return R.layout.layout_new_game_detail_video_portrait
    }

    fun observeVolume(fragment: Fragment?) {
        fragment?.context?.applicationContext?.contentResolver?.registerContentObserver(
            android.provider.Settings.System.CONTENT_URI, true, mVolumeObserver!!
        )
    }

    fun unObserveVolume(activity: AppCompatActivity) {
        activity.contentResolver?.unregisterContentObserver(mVolumeObserver!!)
    }

    fun startPlayLogic(isAutoPlay: Boolean) {
        mIsAutoPlay = isAutoPlay
        violenceUpdateMuteStatus()

        if (isAutoPlay) {
            SensorsBridge.trackGameDetailVideoClick(
                gameName = viewModel?.game?.name ?: "",
                gameId = viewModel?.game?.id ?: "",
                gameType = viewModel?.game?.categoryChinese ?: "",
                lastPageName = GlobalActivityManager.getLastPageEntity().pageName,
                lastPageId = GlobalActivityManager.getLastPageEntity().pageId,
                action = "自动播放",
                playType = if (mIsAutoPlay) "自动播放" else "主动播放",
                isFullScreen = mIfCurrentIsFullscreen,
                sequence = viewModel?.coverTabSequence ?: 1,
                tabName = viewModel?.coverTabName ?: "",
                playLength = (currentPositionWhenPlaying / 1000).toString()
            )

            val seekTime = ScrollCalculatorHelper.getPlaySchedule(MD5Utils.getContentMD5(video?.url))
            seekOnStart = seekTime
            mTouchingProgressBar = false
        }
        GSYVideoType.setShowType(GSYVideoType.SCREEN_TYPE_DEFAULT)
        startPlayLogic()
    }

    fun violenceUpdateMuteStatus() {
        if (mMuteDisposable != null) {
            mMuteDisposable?.dispose()
            mMuteDisposable = null
        }
        mMuteDisposable = rxTimer(25) {
            if (it >= 400) {
                mMuteDisposable?.dispose()
                mMuteDisposable = null
            }
            updateMuteStatus()
        }
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        disposableTimer()
        unObserveVolume(context as AppCompatActivity)
    }

    fun disposableTimer() {
        if (mMuteDisposable != null && !mMuteDisposable!!.isDisposed) {
            mMuteDisposable?.dispose()
            mMuteDisposable = null
        }
    }

    private fun toggleMute() {
        if (viewModel?.videoIsMuted == true) {
            unMute(true)
        } else {
            mute(true)
        }
    }

    fun updateMuteStatus() {
        if (viewModel?.videoIsMuted == true) {
            mute()
        } else {
            unMute()
        }
    }

    private fun mute(isManual: Boolean = false) {
        viewModel?.videoIsMuted = true
        findViewById<ImageView>(R.id.volume)?.setImageResource(R.drawable.ic_game_detail_volume_off)
        CustomManager.getCustomManager(getKey()).isNeedMute = true
        if (isManual) {
            Utils.toast(context, "当前处于静音状态")
            uploadVideoStreamingPlaying("点击静音")
//            MtaHelper.onEvent("游戏详情_顶部视频", "${getMtaKeyPrefix()}-点击静音", combinedTitleAndId)
        }
    }

    private fun unMute(isManual: Boolean = false) {
        viewModel?.videoIsMuted = false
        findViewById<ImageView>(R.id.volume)?.setImageResource(R.drawable.ic_game_detail_volume_on)
        CustomManager.getCustomManager(getKey()).isNeedMute = false
        mAudioManager.requestAudioFocus(
            onAudioFocusChangeListener,
            AudioManager.STREAM_MUSIC,
            AudioManager.AUDIOFOCUS_GAIN_TRANSIENT
        )
        if (isManual) {
            uploadVideoStreamingPlaying("取消静音")
//            MtaHelper.onEvent("游戏详情_顶部视频", "${getMtaKeyPrefix()}-解除静音", combinedTitleAndId)
        }
    }

    override fun onSeekComplete() {
        super.onSeekComplete()
//        MtaHelper.onEvent("游戏详情_顶部视频", "${getMtaKeyPrefix()}-拖动进度条", combinedTitleAndId)
    }

    // 重载以减少横竖屏切换的时间
    override fun checkoutState() {
        removeCallbacks(mCheckoutTask)
        postDelayed(mCheckoutTask, 300)
    }

    override fun clearFullscreenLayout() {
        super.clearFullscreenLayout()
        updateMuteStatus()
        hideBackBtn()
    }

    fun updateThumb(url: String) {
        ImageUtils.picasso.load(url).into(findViewById<ImageView>(R.id.thumbImage))
    }

    override fun touchDoubleUp(e: MotionEvent?) {
        // we do not need double click to play or pause
    }

    // 不需要弹弹窗，直接播放
    override fun showWifiDialog() {
        scrollCalculatorHelper?.currentPlayer = this
        startPlayLogic(false)
        //val trafficVideo = PreferenceManager.getDefaultSharedPreferences(context).getBoolean(SettingsFragment.TRAFFIC_VIDEO_SP_KEY, false)
        //if (trafficVideo) {
        // 不延迟的话 isCacheFile 可能直接返回 false
        postDelayed({
            // 这个库的 NetworkUtils.isWifiConnected 可能会触发空指针，这里换为我们自己的
            if (!com.shuyu.gsyvideoplayer.utils.NetworkUtils.isAvailable(mContext) && !gsyVideoManager.isCacheFile) {
                Utils.toast(context, "网络异常，请检查手机网络状态")
            } else if (!NetworkUtils.isWifiConnected(mContext) && !gsyVideoManager.isCacheFile) {
                Utils.toast(context, "当前为非Wi-Fi环境，请注意流量消耗")
            }
        }, 100)
        // }
    }

    override fun getGSYVideoManager(): GSYVideoViewBridge {
        CustomManager.getCustomManager(getKey()).initContext(context.applicationContext)
        return CustomManager.getCustomManager(getKey())
    }

    fun getKey(): String {
        return uuid
    }

    fun getUrl(): String {
        return mUrl
    }

    override fun onAutoCompletion() {
        // 这个方法在内核被释放时也会被回调，所以可以用来统计播放量和播放时长
        val playedTime = (gsyVideoManager.currentPosition / 1000).toInt()

//        MtaHelper.onEventWithTime("视频播放量_按位置", playedTime, "游戏详情-顶部视频", combinedTitleAndId)
//        MtaHelper.onEventWithTime("视频播放量_游戏加位置", playedTime, gameName, "游戏详情-顶部视频")

        //播放完成后判断是否已缓冲完毕,没有完成显示播放错误状态
        if (mBufferPoint != 0 && mBufferPoint != 100 && isShown) {
            gsyVideoManager.releaseMediaPlayer()
            changeUiToPreparingShow()
            postDelayed({
                if (!com.shuyu.gsyvideoplayer.utils.NetworkUtils.isAvailable(mContext)) {
                    Utils.toast(context, "网络错误，视频播放失败")
                    changeUiToError()
                }
            }, 10 * 1000)
        }
        uploadVideoStreamingPlaying("播放完毕")
        super.onAutoCompletion()
    }

    override fun onStopTrackingTouch(seekBar: SeekBar?) {
        super.onStopTrackingTouch(seekBar)
        uploadVideoStreamingPlaying("拖动进度条", seekBar)
    }

    override fun isShowNetConfirm(): Boolean {
        return (!mOriginUrl.startsWith("file") && !mOriginUrl.startsWith("android.resource") && !CommonUtil.isWifiConnected(
            context
        )
                && mNeedShowWifiTip)
    }

    override fun updateStartImage() {
        if (mStartButton is ImageView) {
            val imageView = mStartButton as ImageView
            when (mCurrentState) {
                GSYVideoView.CURRENT_STATE_PLAYING -> imageView.setImageResource(R.drawable.ic_game_detail_pause)
                GSYVideoView.CURRENT_STATE_ERROR -> imageView.setImageResource(R.drawable.ic_game_detail_play)
                else -> imageView.setImageResource(R.drawable.ic_game_detail_play)
            }
        }
    }

    override fun startPrepare() {
        if (gsyVideoManager.listener() != null) {
            gsyVideoManager.listener().onCompletion()
        }
        if (mVideoAllCallBack != null) {
            Debuger.printfLog("onStartPrepared")
            mVideoAllCallBack.onStartPrepared(mOriginUrl, mTitle, this)
        }
        gsyVideoManager.setListener(this)
        gsyVideoManager.playTag = mPlayTag
        gsyVideoManager.playPosition = mPlayPosition
        if (viewModel?.videoIsMuted == false) {
            mAudioManager.requestAudioFocus(
                onAudioFocusChangeListener,
                AudioManager.STREAM_MUSIC,
                AudioManager.AUDIOFOCUS_GAIN_TRANSIENT
            )
        }
        try {
            if (mContext is Activity) {
                (mContext as Activity).window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        mBackUpPlayingBufferState = -1
        gsyVideoManager.prepare(
            mUrl,
            if (mMapHeadData == null) HashMap() else mMapHeadData,
            mLooping,
            mSpeed,
            mCache,
            mCachePath,
            mOverrideExtension
        )
        setStateAndUi(CURRENT_STATE_PREPAREING)
    }

    override fun setStateAndUi(state: Int) {
        super.setStateAndUi(state)

        if (state == CURRENT_STATE_AUTO_COMPLETE) {
            hideAllWidget()
            showOrHideCoverFilter?.invoke(true)
            findViewById<LinearLayout>(R.id.replayContainer)?.visibility = View.VISIBLE
            mTopContainer.visibility = View.VISIBLE
            findViewById<ImageView>(R.id.replayIv).setOnClickListener {
//                MtaHelper.onEvent("游戏详情_顶部视频", "${getMtaKeyPrefix()}-点击重新播放", combinedTitleAndId)
                startButton.performClick()
                violenceUpdateMuteStatus()
                uploadVideoStreamingPlaying("重新播放")
            }
            updateThumb(video!!.poster)
        } else if (state == CURRENT_STATE_PLAYING) {
            if (!CustomManager.getCustomManager(getKey()).isNeedMute) {
                mAudioManager.requestAudioFocus(
                    onAudioFocusChangeListener,
                    AudioManager.STREAM_MUSIC,
                    AudioManager.AUDIOFOCUS_GAIN_TRANSIENT
                )
            }
        } else {
            findViewById<LinearLayout>(R.id.replayContainer)?.visibility = View.GONE
        }
    }

    private fun showBackBtn() {
        mTopContainer.background = ContextCompat.getDrawable(context, com.shuyu.gsyvideoplayer.R.drawable.video_title_bg)
        findViewById<View>(R.id.back)?.visibility = View.VISIBLE
    }

    private fun hideBackBtn() {
        mTopContainer?.setBackgroundResource(0)
        findViewById<View>(R.id.back)?.visibility = View.GONE
    }

    override fun getEnlargeImageRes(): Int {
        return R.drawable.ic_game_detail_enter_full_screen
    }

    override fun getShrinkImageRes(): Int {
        return R.drawable.ic_game_detail_exit_full_screen
    }

    /******************* 下方两个重载方法，在播放开始前不屏蔽封面，不需要可屏蔽 ********************/

    override fun onSurfaceUpdated(surface: Surface) {
        super.onSurfaceUpdated(surface)
        if (mThumbImageViewLayout != null && mThumbImageViewLayout.visibility == View.VISIBLE) {
            mThumbImageViewLayout.visibility = View.INVISIBLE
            uploadVideoStreamingPlaying("开始播放")
        }
    }

    override fun setViewShowState(view: View?, visibility: Int) {
        if (view === mThumbImageViewLayout && visibility != View.VISIBLE) {
            return
        }
        super.setViewShowState(view, visibility)
    }

    /********************************各类UI的状态显示*********************************************/

    override fun hideAllWidget() {
        super.hideAllWidget()
        Utils.log(TAG, "hideAllWidget")
        findViewById<LinearLayout>(R.id.errorContainer)?.visibility = View.GONE
        findViewById<LinearLayout>(R.id.loadingContainer)?.visibility = View.GONE
        showOrHideCoverFilter?.invoke(false)
    }

    override fun changeUiToNormal() {
        super.changeUiToNormal()
        Utils.log(TAG, "changeUiToNormal")
        findViewById<LinearLayout>(R.id.errorContainer)?.visibility = View.GONE
        findViewById<LinearLayout>(R.id.loadingContainer)?.visibility = View.GONE
        showOrHideCoverFilter?.invoke(true)
    }

    override fun changeUiToPreparingShow() {
        super.changeUiToPreparingShow()
        Utils.log(TAG, "changeUiToPreparingShow")
        findViewById<LinearLayout>(R.id.errorContainer)?.visibility = View.GONE
        findViewById<LinearLayout>(R.id.loadingContainer)?.visibility = View.VISIBLE
        showOrHideCoverFilter?.invoke(true)
    }

    override fun changeUiToPlayingShow() {
        super.changeUiToPlayingShow()
        findViewById<LinearLayout>(R.id.errorContainer)?.visibility = View.GONE
        findViewById<LinearLayout>(R.id.loadingContainer)?.visibility = View.GONE
        showOrHideCoverFilter?.invoke(true)
        Utils.log(TAG, "changeUiToPlayingShow")

    }

    override fun changeUiToPauseShow() {
        super.changeUiToPauseShow()
        Utils.log(TAG, "changeUiToPauseShow")
        findViewById<LinearLayout>(R.id.errorContainer)?.visibility = View.GONE
        findViewById<LinearLayout>(R.id.loadingContainer)?.visibility = View.GONE
        showOrHideCoverFilter?.invoke(true)
    }

    fun showFullPauseBitmap() {
        mThumbImageViewLayout.visibility = View.VISIBLE
        tryWithDefaultCatch {
            // 可能宽高为 0
            mTextureView?.initCover()?.let {
                if (it.width == 0 || it.height == 0) return@let
                findViewById<ImageView>(R.id.thumbImage).setImageBitmap(it)
            }
        }
    }

    override fun changeUiToCompleteShow() {
        super.changeUiToCompleteShow()
        Utils.log(TAG, "changeUiToCompleteShow")
        findViewById<LinearLayout>(R.id.errorContainer)?.visibility = View.GONE
        findViewById<LinearLayout>(R.id.loadingContainer)?.visibility = View.GONE
        showOrHideCoverFilter?.invoke(true)
    }

    override fun changeUiToError() {
        super.changeUiToError()
        Utils.log(TAG, "changeUiToError")
        setViewShowState(mStartButton, View.INVISIBLE)
        findViewById<LinearLayout>(R.id.errorContainer)?.visibility = View.VISIBLE
        findViewById<LinearLayout>(R.id.loadingContainer)?.visibility = View.GONE
        showOrHideCoverFilter?.invoke(true)
    }

    override fun changeUiToPrepareingClear() {
        super.changeUiToPrepareingClear()
        Utils.log(TAG, "changeUiToPrepareingClear")
        findViewById<LinearLayout>(R.id.loadingContainer)?.visibility = View.GONE
        showOrHideCoverFilter?.invoke(false)
    }

    override fun changeUiToPlayingBufferingShow() {
        super.changeUiToPlayingBufferingShow()
        Utils.log(TAG, "changeUiToPlayingBufferingShow")
        findViewById<LinearLayout>(R.id.loadingContainer)?.visibility = View.VISIBLE
        showOrHideCoverFilter?.invoke(true)
    }

    override fun changeUiToPlayingBufferingClear() {
        super.changeUiToPlayingBufferingClear()
        Utils.log(TAG, "changeUiToPlayingBufferingClear")
        findViewById<LinearLayout>(R.id.loadingContainer)?.visibility = View.VISIBLE
        showOrHideCoverFilter?.invoke(false)
    }

    override fun changeUiToClear() {
        super.changeUiToClear()
        Utils.log(TAG, "changeUiToClear")
        findViewById<LinearLayout>(R.id.loadingContainer)?.visibility = View.GONE
        showOrHideCoverFilter?.invoke(false)
    }

    override fun changeUiToCompleteClear() {
        super.changeUiToCompleteClear()
        Utils.log(TAG, "changeUiToCompleteClear")
        findViewById<LinearLayout>(R.id.loadingContainer)?.visibility = View.GONE
        showOrHideCoverFilter?.invoke(true)
    }

    override fun netWorkErrorLogic() {
        super.netWorkErrorLogic()
        Utils.toast(context, "网络错误，视频播放失败")
        setViewShowState(mStartButton, View.INVISIBLE)
        findViewById<LinearLayout>(R.id.errorContainer)?.visibility = View.VISIBLE
    }

    //监控播放错误
    override fun onError(what: Int, extra: Int) {
        super.onError(what, extra)
        Utils.toast(context, "网络错误，视频播放失败")
        setViewShowState(mStartButton, View.INVISIBLE)
        findViewById<LinearLayout>(R.id.errorContainer)?.visibility = View.VISIBLE
    }

    override fun releaseVideos() {
        uploadVideoStreamingPlaying("播放完毕")
        CustomManager.releaseAllVideos(getKey())
    }

    override fun onVideoPause() {
        super.onVideoPause()
        uploadVideoStreamingPlaying("暂停播放")
    }

    override fun onLossAudio() {
        if (!CustomManager.getCustomManager(getKey()).isNeedMute) {
            super.onLossAudio()
        }
    }

    override fun onLossTransientAudio() {
        // transient audio lost 代表的是短暂的 audio focus lost，不暂停播放。不然视频很容易就处于暂停状态
        // onLossAudio 回调的时候再决定是否需要暂停
    }

    override fun onClick(v: View) {
        when (v.id) {
            R.id.start -> {
                SensorsBridge.trackGameDetailVideoClick(
                    gameName = viewModel?.game?.name ?: "",
                    gameId = viewModel?.game?.id ?: "",
                    gameType = viewModel?.game?.categoryChinese ?: "",
                    lastPageName = GlobalActivityManager.getLastPageEntity().pageName,
                    lastPageId = GlobalActivityManager.getLastPageEntity().pageId,
                    action = if (currentState == GSYVideoView.CURRENT_STATE_PLAYING) "点击暂停" else "点击播放",
                    playType = if (mIsAutoPlay) "自动播放" else "主动播放",
                    isFullScreen = mIfCurrentIsFullscreen,
                    sequence = viewModel?.coverTabSequence ?: 1,
                    tabName = viewModel?.coverTabName ?: "",
                    playLength = (currentPositionWhenPlaying / 1000).toString()
                )
                // 手动触发暂停/播放，后续行为都算主动播放
                mIsAutoPlay = false
                super.onClick(v)
            }

            else -> super.onClick(v)
        }
    }

    fun getCurrentPosition(): Long {
        return mCurrentPosition
    }

    fun uploadVideoStreamingPlaying(action: String, seekBar: SeekBar? = null) {
        if (video == null || video?.url.isNullOrEmpty()) return
        runOnIoThread(isHeavyWightTask = true) {
            val isLandscape = mOrientationUtils != null
            val videoPlayModel = if (!isLandscape) {
                if (mIsAutoPlay) "自动播放" else "点击播放"
            } else "全屏播放"
            val videoPlayTs = currentPositionWhenPlaying / 1000
            val videoTotalTime = duration / 1000
            val progress = if (videoTotalTime != 0) videoPlayTs.toFloat() / videoTotalTime.toFloat() * 100 else 0f
            if (mContentLength == 0.0) {
                val newGetContentLengthTime = System.currentTimeMillis()
                if (newGetContentLengthTime - mLastGetContentLengthTime > 5000) {
                    mLastGetContentLengthTime = newGetContentLengthTime
                    mContentLength = ExoCacheManager.getContentLength(video!!.url) / 1024.0 / 1024.0
                }
            }

            //https://exoplayer.dev/hello-world.html#a-note-on-threading
            runOnUiThread {
                LogUtils.uploadTopVideoStreamingPlaying(
                    action, video?.videoId, video?.title, viewModel?.game?.id, viewModel?.game?.name,
                    videoPlayModel, videoPlayStatus(), mContentLength, videoTotalTime, videoPlayTs, progress.toInt()
                )
                if (action != "开始播放" && action != "暂停播放" && action != "退出全屏") {
                    val playLength = when (action) {
                        "播放完毕" -> (duration / 1000).toString()
                        "拖动进度条" -> ((seekBar?.progress ?: 0) * duration / 100000).toString()
                        else -> (currentPositionWhenPlaying / 1000).toString()
                    }
                    SensorsBridge.trackGameDetailVideoClick(
                        gameName = viewModel?.game?.name ?: "",
                        gameId = viewModel?.game?.id ?: "",
                        gameType = viewModel?.game?.categoryChinese ?: "",
                        lastPageName = GlobalActivityManager.getLastPageEntity().pageName,
                        lastPageId = GlobalActivityManager.getLastPageEntity().pageId,
                        action = action,
                        playType = if (mIsAutoPlay) "自动播放" else "主动播放",
                        isFullScreen = mIfCurrentIsFullscreen,
                        sequence = viewModel?.coverTabSequence ?: 1,
                        tabName = viewModel?.coverTabName ?: "",
                        playLength = playLength
                    )
                }
            }
        }
    }

    private fun videoPlayStatus(): String {
        return when (mCurrentState) {
            CURRENT_STATE_PLAYING, CURRENT_STATE_PREPAREING, CURRENT_STATE_PLAYING_BUFFERING_START -> "play"
            GSYVideoView.CURRENT_STATE_PAUSE -> "pause"
            else -> ""
        }
    }
    
    companion object {
        const val TAG = "TopVideoView"
    }
}