package com.gh.gamecenter.forum.home

import android.app.Activity
import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.Surface
import android.view.View
import android.widget.ImageView
import android.widget.SeekBar
import android.widget.TextView
import androidx.core.content.ContextCompat
import com.facebook.drawee.view.SimpleDraweeView
import com.gh.gamecenter.R
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.core.utils.MD5Utils
import com.gh.gamecenter.entity.ForumVideoEntity
import com.gh.gamecenter.video.detail.CustomManager
import com.lightgame.utils.Utils
import com.shuyu.gsyvideoplayer.utils.CommonUtil
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 ArticleItemVideoView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) :
    StandardGSYVideoPlayer(context, attrs) {

    private var mVideoEntity: ForumVideoEntity? = null
    private var mMuteDisposable: Disposable? = null
    private var mIsAutoPlay = false
    var uuid = UUID.randomUUID().toString()

    var thumbImage: SimpleDraweeView = findViewById(R.id.thumbImage)
    var durationTv: TextView = findViewById(R.id.durationTv)
    var completeContainer: View = findViewById(R.id.completeContainer)
    var replayTv: TextView = findViewById(R.id.replayTv)
    var shareTv: TextView = findViewById(R.id.shareTv)
    var volume: ImageView = findViewById(R.id.volume)
    var remainingTv: TextView = findViewById(R.id.remainingTv)
    var back: ImageView = findViewById(R.id.back)
    var pendingView: TextView = findViewById(R.id.pendingView)
    var titleTv: TextView = findViewById(R.id.title)

    override fun getLayoutId(): Int {
        return R.layout.layout_article_item_video
    }

    init {
        post {
            volume.setOnClickListener { toggleMute() }
        }

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

        setBackFromFullScreenListener {
            clearFullscreenLayout()
        }
    }

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

    fun startPlayLogic(isAutoPlay: Boolean) {
        mIsAutoPlay = isAutoPlay
        if (mIsAutoPlay) {
            val seekTime = ForumScrollCalculatorHelper.getPlaySchedule(MD5Utils.getContentMD5(mVideoEntity?.url))
            seekOnStart = seekTime
        }
        startPlayLogic()
    }

    override fun prepareVideo() {
        super.prepareVideo()
        violenceUpdateMuteStatus()
    }

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

    // 不需要弹弹窗，直接播放
    override fun showWifiDialog() {
        startPlayLogic(false)
        //val trafficVideo = PreferenceManager.getDefaultSharedPreferences(context).getBoolean(SettingsFragment.TRAFFIC_VIDEO_SP_KEY, false)
        //if (trafficVideo) {
        // 不延迟的话 isCacheFile 可能直接返回 false
        postDelayed({
            tryCatchInRelease {
                // 这个库的 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 updateStartImage() {
        if (mStartButton is ImageView) {
            val imageView = mStartButton as ImageView
            when (mCurrentState) {
                GSYVideoView.CURRENT_STATE_PLAYING -> imageView.setImageResource(R.drawable.icon_preview_video_pause)
                GSYVideoView.CURRENT_STATE_ERROR -> imageView.setImageResource(R.drawable.icon_preview_video_play)
                else -> imageView.setImageResource(R.drawable.icon_preview_video_play)
            }
        }
    }

    override fun onClickUiToggle(e: MotionEvent?) {
        if (mVideoEntity?.status != "pending" && mVideoEntity?.status != "fail") {
            if (mCurrentState == CURRENT_STATE_PLAYING) {
                if (mStartButton.visibility == View.VISIBLE) {
                    changeUiToPlayingClear()
                } else {
                    changeUiToPlayingShow()
                }
            } else {
                super.onClickUiToggle(e)
            }
        }
    }

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

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

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

    override fun releaseVideos() {
        uploadVideoStreamingPlaying("结束播放")
        CustomManager.releaseAllVideos(getKey())
    }

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

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

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

    override fun setProgressAndTime(
        progress: Int,
        secProgress: Int,
        currentTime: Int,
        totalTime: Int,
        forceChange: Boolean
    ) {
        super.setProgressAndTime(progress, secProgress, currentTime, totalTime, forceChange)
        if (remainingTv.visibility == View.VISIBLE) {
            remainingTv.text = CommonUtil.stringForTime(totalTime - currentTime)
        }
    }

    private fun showBackBtn() {
        mTopContainer.background = ContextCompat.getDrawable(context, R.drawable.video_title_bg)
        back.visibility = View.VISIBLE
        mVideoEntity?.run {
            titleTv.text = title
        }
    }

    private fun hideBackBtn() {
        mTopContainer?.setBackgroundResource(0)
        back.visibility = View.GONE
        titleTv.text = ""
    }

    fun updateThumb(url: String) {
        ImageUtils.display(thumbImage, url)
    }

    fun updateDurationTv(duration: String) {
        durationTv.text = duration
    }

    fun updateVideoData(video: ForumVideoEntity) {
        mVideoEntity = video
        titleTv.text = if (mIfCurrentIsFullscreen) video.title else ""
    }

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

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

    override fun touchSurfaceMoveFullLogic(absDeltaX: Float, absDeltaY: Float) {
        super.touchSurfaceMoveFullLogic(absDeltaX, absDeltaY)
        //不给触摸快进，如果需要，屏蔽下方代码即可
        mChangePosition = false
        //不给触摸音量，如果需要，屏蔽下方代码即可
        mChangeVolume = false
        //不给触摸亮度，如果需要，屏蔽下方代码即可
        mBrightness = false
    }

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

    override fun setStateAndUi(state: Int) {
        super.setStateAndUi(state)
        if (currentState == GSYVideoView.CURRENT_STATE_PREPAREING) {
            setViewShowState(durationTv, View.GONE)
        }

//        if (currentState == GSYVideoView.CURRENT_STATE_PLAYING) {
//            setViewShowState(mBottomProgressBar, View.VISIBLE)
//        }

        if (currentState == GSYVideoView.CURRENT_STATE_AUTO_COMPLETE) {
            hideAllWidget()
            setViewShowState(completeContainer, View.VISIBLE)
            mTopContainer.visibility = View.VISIBLE
            replayTv.setOnClickListener {
                startButton.performClick()
                violenceUpdateMuteStatus()
                uploadVideoStreamingPlaying("重新播放")
            }
            shareTv.setOnClickListener {
                share()
            }
        } else {
            setViewShowState(completeContainer, View.GONE)
        }
    }

    override fun changeUiToPlayingShow() {
        super.changeUiToPlayingShow()
        if (!mIfCurrentIsFullscreen) setViewShowState(mBottomProgressBar, View.VISIBLE)
    }

    override fun changeUiToPlayingClear() {
        super.changeUiToPlayingClear()
        if (mIfCurrentIsFullscreen) setViewShowState(mBottomProgressBar, View.GONE)
    }

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

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

    fun mute(isManual: Boolean = false) {
        mVideoEntity?.videoIsMuted = true
        volume.setImageResource(R.drawable.ic_article_video_volume_off)
        CustomManager.getCustomManager(getKey()).isNeedMute = true
        if (isManual) {
//            Utils.toast(context, "当前处于静音状态")
            uploadVideoStreamingPlaying("点击静音")
        }
    }

    fun unMute(isManual: Boolean = false) {
        mVideoEntity?.videoIsMuted = false
        volume.setImageResource(R.drawable.ic_article_video_volume_on)
        CustomManager.getCustomManager(getKey()).isNeedMute = false
        if (isManual) {
            uploadVideoStreamingPlaying("取消静音")
        }
    }

    override fun onAutoCompletion() {
        super.onAutoCompletion()
        uploadVideoStreamingPlaying("播放完毕")
    }

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

    private fun share() {
        mVideoEntity?.let {
            val shareIcon = it.poster
            val shareUrl = if (isPublishEnv()) {
                "https://m.ghzs666.com/video/${it.id}"
            } else {
                "https://resource.ghzs.com/page/video_play/video/video.html?video=${it.id}"
            }
            ShareUtils.getInstance(context).showShareWindowsCallback(context as Activity,
                this,
                shareUrl,
                shareIcon,
                it.title,
                it.des,
                ShareUtils.ShareEntrance.video, it.id, object : ShareUtils.ShareCallBack {
                    override fun onSuccess(label: String) {
//                    if ("短信" == label || "复制链接" == label) viewModel?.shareVideoStatistics(it)
                    }

                    override fun onCancel() {
                        uploadVideoStreamingPlaying("取消分享")
                    }
                })
        }
    }

    fun uploadVideoStreamingPlaying(action: String) {

    }

    fun setFullViewStatus() {
        mProgressBar.visibility = View.VISIBLE
        mCurrentTimeTextView.visibility = View.VISIBLE
        mTotalTimeTextView.visibility = View.VISIBLE
        mBottomProgressBar.visibility = View.GONE
        remainingTv.visibility = View.GONE
        durationTv.visibility = View.GONE
    }

    fun setVideoStatus(status: String) {
        if (status == "pending" || status == "fail") {
            pendingView.text = if (status == "pending") "审核中...请耐心等待" else "审核不通过"
            pendingView.visibility = View.VISIBLE
            mBottomContainer?.visibility = View.GONE
            mStartButton?.visibility = View.GONE
            mBottomProgressBar?.visibility = View.GONE
        } else {
            pendingView.visibility = View.GONE
//            mBottomContainer.visibility = View.VISIBLE
            mStartButton?.visibility = View.VISIBLE
            mBottomProgressBar?.visibility = View.VISIBLE
        }
    }

    fun getKey(): String {
        return uuid
    }

    fun getCurrentPosition(): Long {
        return mCurrentPosition
    }
}