package com.gh.gamecenter.qa.editor

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.pm.ActivityInfo
import android.os.Build
import android.os.Bundle
import com.therouter.router.Route
import com.gh.common.util.NewFlatLogUtils
import com.gh.gamecenter.R
import com.gh.gamecenter.common.base.activity.BaseActivity
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.common.constant.RouteConsts
import com.gh.gamecenter.common.utils.NetworkUtils
import com.gh.gamecenter.common.utils.roundTo
import com.gh.gamecenter.core.utils.DisplayUtils
import com.gh.gamecenter.core.utils.MD5Utils
import com.gh.gamecenter.databinding.ActivityFullScreenVideoBinding
import com.gh.gamecenter.forum.home.ForumScrollCalculatorHelper
import com.gh.gamecenter.video.detail.CustomManager
import com.shuyu.gsyvideoplayer.builder.GSYVideoOptionBuilder

@Route(path = RouteConsts.activity.fullScreenVideoActivity)
class FullScreenVideoActivity : BaseActivity() {

    private var mVideoUrl = ""
    private var mIsQAVideo = false
    private var mQAContentId = ""
    private var mQAContentTitle = ""
    private var mQAVideoId = ""
    private var mQASequence = -1
    private var mQAVideoLength = 0
    private lateinit var mBinding: ActivityFullScreenVideoBinding
    private var mCurrentPosition = -1

    override fun getLayoutId(): Int = R.layout.activity_full_screen_video

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if (Build.VERSION.SDK_INT != Build.VERSION_CODES.O) {
            requestedOrientation = if (intent.getBooleanExtra(EntranceConsts.KEY_IS_LANDSCAPE, true)) {
                ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
            } else {
                ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
            }
        }
        DisplayUtils.transparentStatusBar(this)
        DisplayUtils.hideNavigationBar(this)
        mBinding = ActivityFullScreenVideoBinding.bind(mContentView)

        mVideoUrl = intent.getStringExtra(EntranceConsts.KEY_URL) ?: ""
        mIsQAVideo = intent.getBooleanExtra(EntranceConsts.KEY_IS_QA_FEEDBACK, false)
        mQAContentId = intent.getStringExtra(EntranceConsts.KEY_ID) ?: ""
        mQAContentTitle = intent.getStringExtra(EntranceConsts.KEY_QA_TITLE) ?: ""
        mQASequence = intent.getIntExtra(EntranceConsts.KEY_SEQUENCE, -1)
        mQAVideoId = intent.getStringExtra(EntranceConsts.KEY_VIDEO_ID) ?: ""
        mQAVideoLength = intent.getIntExtra(EntranceConsts.KEY_VIDEO_LENGTH, 0)
        val poster = intent.getStringExtra(EntranceConsts.KEY_POSTER_PATH) ?: ""
        val title = intent.getStringExtra(EntranceConsts.KEY_NAVIGATION_TITLE) ?: ""
        val position = intent.getLongExtra(EntranceConsts.KEY_POSITION, -1L)
        mBinding.videoView.backBtn.setOnClickListener { finish() }
        if (!intent.getBooleanExtra(EntranceConsts.KEY_VIDEO_MUTE, true)) {
            mBinding.videoView.videoIsMuted = false
        }
        setUpTopVideo(title, mVideoUrl, poster, position)

        mBinding.videoView.logCallback = {
            val eventName = when (it) {
                "开始播放" -> "qa_video_play"
                "暂停播放" -> "qa_video_pause"
                "播放完毕" -> "qa_video_finish"
                "重新播放" -> "qa_video_replay"
                "点击静音" -> "qa_video_click_mute"
                "取消静音" -> "qa_video_cancel_mute"
                "拖动" -> "qa_video_drag_progress"
                else -> ""
            }
            if (mIsQAVideo && eventName.isNotEmpty() && mQAVideoLength != 0) {
                var currentTimeSeconds = mCurrentPosition / 1000F
                if (currentTimeSeconds < 0) {
                    currentTimeSeconds = 0F
                }
                val progress = (currentTimeSeconds / mQAVideoLength).roundTo(4)
                NewFlatLogUtils.logQAVideo(
                    eventName,
                    mQAContentId,
                    mQAContentTitle,
                    "帮助视频",
                    mQASequence + 1,
                    mQAVideoId,
                    "点击播放",
                    progress,
                    currentTimeSeconds.toInt()
                )
            }
        }
    }

    private fun setUpTopVideo(title: String, url: String, poster: String, position: Long) {
        GSYVideoOptionBuilder()
            .setIsTouchWigetFull(false)
            .setIsTouchWiget(false)
            .setRotateViewAuto(false)
            .setShowFullAnimation(false)
            .setSeekRatio(1f)
            .setUrl(url)
            .setVideoTitle(title)
            .setCacheWithPlay(true)
            .setGSYVideoProgressListener { _, _, currentPosition, _ ->
                mCurrentPosition = currentPosition
            }
            .also {
                if (position != -1L) {
                    it.setSeekOnStart(position)
                }
            }
            .build(mBinding.videoView)

        mBinding.videoView.updateThumb(poster)

        if (NetworkUtils.isWifiConnected(this) || position != -1L) {
            mBinding.videoView.startPlayLogic(position == -1L)
        }
        mBinding.videoView.observeVolume(this)
    }

    override fun onResume() {
        super.onResume()
        CustomManager.onResume(mBinding.videoView.getKey())
    }

    override fun onPause() {
        super.onPause()
        CustomManager.onPause(mBinding.videoView.getKey())
        val currentPosition = mBinding.videoView.getCurrentPosition()
        ForumScrollCalculatorHelper.savePlaySchedule(MD5Utils.getContentMD5(mVideoUrl), currentPosition)
    }

    override fun finish() {
        if (mIsQAVideo && mQAVideoLength != 0) {
            val currentTimeSeconds = mCurrentPosition / 1000F
            val progress = (currentTimeSeconds / mQAVideoLength).roundTo(4)
            NewFlatLogUtils.logQAVideo(
                "qa_video_shut",
                mQAContentId,
                mQAContentTitle,
                "帮助视频",
                mQASequence + 1,
                mQAVideoId,
                "点击播放",
                progress,
                currentTimeSeconds.toInt()
            )
        }
        if (!isFinishing) {
            val newIntent = Intent().apply {
                putExtra(EntranceConsts.KEY_URL, mVideoUrl)
                putExtra(EntranceConsts.KEY_POSITION, mCurrentPosition)
            }
            setResult(RESULT_OK, newIntent)
        }
        super.finish()
    }

    override fun onDestroy() {
        super.onDestroy()
        CustomManager.releaseAllVideos(mBinding.videoView.getKey())
        mBinding.videoView.disposableTimer()
    }

    companion object {
        const val REQUEST_CODE = 10013

        fun start(
            context: Context,
            title: String,
            url: String,
            poster: String,
            progress: Long = -1L,
            isLandscape: Boolean = true
        ) {
            val intent = Intent(context, FullScreenVideoActivity::class.java)
            intent.putExtra(EntranceConsts.KEY_URL, url)
            intent.putExtra(EntranceConsts.KEY_POSITION, progress)
            intent.putExtra(EntranceConsts.KEY_NAVIGATION_TITLE, title)
            intent.putExtra(EntranceConsts.KEY_POSTER_PATH, poster)
            intent.putExtra(EntranceConsts.KEY_IS_LANDSCAPE, isLandscape)
            if (context is Activity) {
                context.startActivityForResult(intent, REQUEST_CODE)
            } else {
                context.startActivity(intent)
            }
        }
    }

}