package com.cheng.blzb.ui.fragment.video

import android.annotation.SuppressLint
import android.content.pm.ActivityInfo
import android.os.Bundle
import android.view.OrientationEventListener
import android.view.View
import android.widget.FrameLayout
import android.widget.ImageButton
import androidx.media3.common.MediaItem
import androidx.media3.common.PlaybackException
import androidx.media3.common.Player
import androidx.media3.exoplayer.ExoPlayer
import com.cheng.blzb.R
import com.cheng.blzb.databinding.FragmentVideoPlayerBinding
import com.example.base.extensions.getColor
import com.example.base.extensions.gone
import com.example.base.extensions.onClick
import com.example.base.extensions.toast
import com.example.base.extensions.visible
import com.example.base.ui.BaseFragment
import com.example.base.utils.L
import com.example.base.utils.ScreenUtils
import org.jetbrains.anko.find


class VideoPlayerFragment : BaseFragment<FragmentVideoPlayerBinding, VideoPlayerViewModel>() {
    private val title by lazy { arguments?.getString("title") ?: "" }
    private val url by lazy { arguments?.getString("url") ?: "" }

    private var orientationEventListener: OrientationEventListener? = null
    private var currentOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
    private var isFullScreen: Boolean = false

    private var listener: ((Int) -> Unit)? = null

    companion object {
        fun newInstance(url: String, title: String): VideoPlayerFragment {
            val args = Bundle()
            args.putString("url", url)
            args.putString("title", title)
            val fragment = VideoPlayerFragment()
            fragment.arguments = args
            return fragment
        }
    }

    override fun initView() {
        super.initView()
        mTitleBar?.background = null
        mTitleBar?.titleView?.text = title
        mTitleBar?.titleView?.setTextColor(getColor(R.color.white))
        setBackColor(R.color.white)

        binding.playerView.player = ExoPlayer.Builder(requireContext()).build()
        binding.playerView.player?.playWhenReady = true
        binding.playerView.player?.repeatMode = Player.REPEAT_MODE_OFF

        orientationEventListener = object : OrientationEventListener(requireContext()) {
            override fun onOrientationChanged(orientation: Int) {
                if (!ScreenUtils.isScreenAutoRotate()) return
                val activityOrientation = if (orientation >= 315 || orientation < 45) { // 0度，纵向向上
                    ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
                } else if (orientation in 45..134) { // 90度，横向向右
                    ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE
                } else if (orientation in 135..224) { // 180度，纵向向下
                    ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT
                } else { // 270度，横向向左
                    ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
                }
                if (currentOrientation != activityOrientation) {
                    currentOrientation = activityOrientation
                    isFullScreen =
                        !(currentOrientation == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT || currentOrientation == ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT)
//                    updateFullScreenButton()
                    listener?.invoke(currentOrientation)
                }
            }
        }
    }

    override fun initData() {
        super.initData()
        binding.playerView.player?.setMediaItem(MediaItem.fromUri(url))
        binding.playerView.player?.prepare()
    }

    override fun initListener() {
        super.initListener()
        binding.ivPlay.onClick {
            binding.playerView.player?.prepare()
            binding.playerView.player?.play()
        }
        binding.playerView.player?.addListener(object : Player.Listener {
            override fun onIsPlayingChanged(isPlaying: Boolean) {
                super.onIsPlayingChanged(isPlaying)
                L.d("视频播放状态：$isPlaying")
                binding.ivPlay.visibility = if (isPlaying) View.GONE else View.VISIBLE
            }

            override fun onPlaybackStateChanged(playbackState: Int) {
                super.onPlaybackStateChanged(playbackState)
                when (playbackState) {
                    Player.STATE_IDLE -> {
                        L.d("视频已暂停")
                    }

                    Player.STATE_BUFFERING -> {
                        L.d("视频正在缓冲")
                        binding.progressbar.visible()
                    }

                    Player.STATE_READY -> {
                        L.d("视频已准备好")
                        binding.progressbar.gone()
                    }

                    Player.STATE_ENDED -> {
                        L.d("视频已结束")
                        binding.playerView.player?.seekTo(0)
                        binding.playerView.player?.pause()
                    }
                }
            }

            override fun onPlayerError(error: PlaybackException) {
                super.onPlayerError(error)
                binding.progressbar.gone()
                toast("视频加载失败，错误：${error.errorCodeName}")
            }
        })
//        binding.playerView.setFullscreenButtonClickListener {
//            isFullScreen = !isFullScreen
//            updateFullScreenButton()
//            listener?.invoke(if (isFullScreen) ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE else ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
//        }
//        binding.playerView.setControllerVisibilityListener(PlayerView.ControllerVisibilityListener {
//            mTitleBar?.visibility = it
//        })
    }

    @SuppressLint("PrivateResource")
    private fun updateFullScreenButton() {
        val exoController = binding.playerView.find<FrameLayout>(androidx.media3.ui.R.id.exo_controller)
        val exoFullscreen = exoController.find<ImageButton>(androidx.media3.ui.R.id.exo_fullscreen)
        if (isFullScreen) {
            exoFullscreen.setImageResource(androidx.media3.ui.R.drawable.exo_styled_controls_fullscreen_exit)
            exoFullscreen.setContentDescription(getString(androidx.media3.ui.R.string.exo_controls_fullscreen_exit_description))
        } else {
            exoFullscreen.setImageResource(androidx.media3.ui.R.drawable.exo_styled_controls_fullscreen_enter)
            exoFullscreen.setContentDescription(getString(androidx.media3.ui.R.string.exo_controls_fullscreen_enter_description))
        }
    }

    fun setFullScreenChangedListener(listener: (Int) -> Unit) {
        this.listener = listener
    }

    override fun onResume() {
        orientationEventListener?.enable()
        // 恢复播放
        binding.playerView.onResume()
        super.onResume()
    }

    override fun onPause() {
        orientationEventListener?.disable()
        // 暂停播放
        binding.playerView.player?.pause()
        binding.playerView.onPause()
        super.onPause()
    }

    override fun onDestroyView() {
        // 释放播放器资源
        binding.playerView.player?.release()
        binding.playerView.player = null
        super.onDestroyView()
    }
}