package com.base.appzxhy.ui.play

import android.annotation.SuppressLint
import android.content.Intent
import android.util.SparseArray
import android.view.Gravity
import android.view.View
import android.widget.FrameLayout
import android.widget.TextView
import androidx.activity.addCallback
import androidx.core.content.ContextCompat
import androidx.lifecycle.lifecycleScope
import com.base.appzxhy.R
import com.base.appzxhy.base.BaseActivity
import com.base.appzxhy.bean.ShortPlayHistory
import com.base.appzxhy.databinding.ActivityPlayFullBinding
import com.base.appzxhy.databinding.LayoutOverlayPlayerBinding
import com.base.appzxhy.databinding.PupupMoreBinding
import com.base.appzxhy.ui.views.DialogSelectEP
import com.base.appzxhy.ui.views.MyPopupMore
import com.base.appzxhy.ui.views.ReportProblemDialog.showReportProblemDialog
import com.base.appzxhy.ui.views.ShortPlayEPDialog.showShortPlayEPDialog
import com.base.appzxhy.ui.views.ShortPlayQualityDialog.showShortPlayQualityDialog
import com.base.appzxhy.ui.views.ShortPlaySpeedDialog.showShortPlaySpeedDialog
import com.base.appzxhy.utils.KotlinExt.formatSeconds
import com.base.appzxhy.utils.LogEx
import com.base.appzxhy.utils.SpJsonUtils
import com.base.appzxhy.utils.SpJsonUtils.KEY_SHORTPLAY_HISTORY
import com.base.appzxhy.utils.ToastUtils.toast
import com.bytedance.sdk.shortplay.api.PSSDK
import com.bytedance.sdk.shortplay.api.PSSDK.AdCustomProvider
import com.bytedance.sdk.shortplay.api.PSSDK.DetailPageConfig
import com.bytedance.sdk.shortplay.api.PSSDK.DrawAdProvider
import com.bytedance.sdk.shortplay.api.ShortPlay
import com.bytedance.sdk.shortplay.api.ShortPlayFragment
import com.google.gson.Gson
import com.gyf.immersionbar.ImmersionBar
import com.ss.ttvideoengine.Resolution
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

class PlayFullActivity : BaseActivity<ActivityPlayFullBinding>(ActivityPlayFullBinding::inflate) {

    private var shortPlay: ShortPlay? = null
    private var startFromIndex = 1//剧集下标
    private val startFromSeconds = 0//开始秒数

    private var shortPlayFragment: ShortPlayFragment? = null
    private var playSpeed = 1.0f//0.5 0.75 1.0 1.25 1.5 2.0
    private var resolutions: Array<Resolution>? = null
    private var currentResolution = Resolution.Auto

    private val playControlViewSparseArray = SparseArray<CustomOverlayView>()

    override fun initView() {
        super.initView()
        val data = intent.extras?.getString("data")
        LogEx.logDebug(TAG, "data=$data")
        data?.let {
            shortPlay = Gson().fromJson(it, ShortPlay::class.java)
        }

        startFromIndex = intent.extras?.getInt("startFromIndex", 1) ?: 1
        LogEx.logDebug(TAG, "startFromIndex=$startFromIndex")

        shortPlay?.let { showShortPlayerFragment(it) }
    }

    override fun initListener() {
        super.initListener()
        onBackPressedDispatcher.addCallback {
            finish()
        }
    }

    private fun showShortPlayerFragment(shortPlay: ShortPlay) {

        val builder = DetailPageConfig.Builder()
        builder.displayTextVisibility(DetailPageConfig.TEXT_POS_BOTTOM_DESC, false)
        builder.displayTextVisibility(DetailPageConfig.TEXT_POS_BOTTOM_TITLE, false)
        builder.displayProgressBar(false)
        builder.startPlayIndex(startFromIndex)
        builder.startPlayAtTimeSeconds(startFromSeconds)


        // 配置广告策略
        builder.adCustomProvider(object : AdCustomProvider {
            override fun getDetailDrawAdPositions(): List<Int> {
                val integers = ArrayList<Int>()
                // 在第1集、第3集、第50集后面插入广告
//                integers.add(1)
//                integers.add(3)
//                integers.add(50)
                return integers
            }

            override fun getDrawAdProvider(): DrawAdProvider {
                return object : DrawAdProvider {
                    override fun onPrepareAd() {
                        // 快划到广告插入位置时调用，可以在这里请求广告
//                        loadPangleFeedAd()
                    }

                    override fun onObtainAdView(position: Int, index: Int): View? {
                        // 返回广告View，如没有可用广告则返回null
                        return null
                    }

                    override fun onDestroy() {
                        // 播放页退出时调用，可在这里释放广告资源
                    }
                }
            }
        })

        builder.enableImmersiveMode(5000)
        builder.enableAutoPlayNext(false)
        builder.displayProgressBar(false)

        shortPlayFragment = PSSDK.createDetailFragment(shortPlay, builder.build(), object : PSSDK.ShortPlayDetailPageListener {

            @SuppressLint("SetTextI18n")
            override fun onProgressChange(shortPlay: ShortPlay?, index: Int, currentPlayTimeInSeconds: Int, durationInSeconds: Int) {
                LogEx.logDebug(
                    TAG,
                    "index=$index startFromIndex=$startFromIndex " +
                            "currentPlayTimeInSeconds=$currentPlayTimeInSeconds " +
                            "durationInSeconds=$durationInSeconds"
                )

                val playControlView: CustomOverlayView? = playControlViewSparseArray.get(index)
                playControlView?.onProgressChange(currentPlayTimeInSeconds, durationInSeconds)
            }

            override fun onPlayFailed(errorInfo: PSSDK.ErrorInfo?): Boolean {
                LogEx.logDebug(TAG, "msg=${errorInfo?.msg} code=${errorInfo?.code}")
                if (errorInfo?.code == PSSDK.ErrorInfo.ERROR_CODE_CURRENT_COUNTRY_NOT_SUPPORT) {
                    // 当前地区不支持播放，SDK会Toast提示，开发者也可以在此时显示弹窗等更友好的提示
                    // return true表示替换掉SDK内的Toast提示
                    toast("code current country not support")
                    return true

                }
                return false
            }

            @SuppressLint("SetTextI18n")
            override fun onShortPlayPlayed(shortPlay: ShortPlay?, index: Int) {
                shortPlay ?: return
                this@PlayFullActivity.shortPlay = shortPlay
                startFromIndex = index
                LogEx.logDebug(TAG, "onShortPlayPlayed index=$index")

                playControlViewSparseArray.get(index)?.findViewById<TextView>(R.id.tvTitle)?.text =
                    "${shortPlay.title} $index/${shortPlay.total}"

                //保存播放历史
                saveShortPlayHistory(shortPlay, index)
            }

            override fun onItemSelected(position: Int, type: PSSDK.ShortPlayDetailPageListener.ItemType, index: Int) {

                playControlViewSparseArray.get(index)?.findViewById<TextView>(R.id.tvTitle)?.text =
                    "${shortPlay.title} $index/${shortPlay.total}"
            }

            override fun onVideoPlayStateChanged(shortPlay: ShortPlay?, index: Int, playbackState: Int) {
//                LogEx.logDebug(TAG)
            }

            override fun onVideoPlayCompleted(shortPlay: ShortPlay?, index: Int) {
            }

            override fun onEnterImmersiveMode() {
                // 进入沉浸式模式
            }

            override fun onExitImmersiveMode() {
                // 退出沉浸式模式
            }

            override fun isNeedBlock(shortPlay: ShortPlay?, index: Int): Boolean {
                // 询问index集是否锁定，true锁定后则该集无法自动播放，需要通过showAdIfNeed里完成解锁
                // 默认对每一集均会询问，一旦返回false则此播放页不会再询问该集
                return false
            }

            override fun showAdIfNeed(shortPlay: ShortPlay?, index: Int, listener: PSSDK.ShortPlayBlockResultListener?) {
                // 当isNeedBlock指定index集锁定后，在用户切换到该集时，SDK不会播放视频，同时会调用此回调，可在此时展示激励广告或购买等交互，用户达成后调用listener.onShortPlayUnlocked告知SDK可播放该集
            }

            override fun onVideoInfoFetched(shortPlay: ShortPlay?, index: Int, videoPlayInfo: PSSDK.VideoPlayInfo?) {
                // 每一集视频准备好时调用此方法告知本集的视频信息
                resolutions = videoPlayInfo?.supportResolutions
            }

            @SuppressLint("RtlHardcoded", "SetTextI18n")
            override fun onObtainPlayerControlViews(): MutableList<View> {
                val views = java.util.ArrayList<View>()

                val aLLBottomMargin = this@PlayFullActivity.resources.getDimensionPixelSize(R.dimen.dp_120)
                val itemMargin = this@PlayFullActivity.resources.getDimensionPixelSize(R.dimen.dp_70)

                // 点赞按钮
                val customLikeView = CustomLikeView(this@PlayFullActivity)
                val likeParams =
                    FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT).apply {
                        gravity = Gravity.BOTTOM or Gravity.RIGHT
                        bottomMargin = aLLBottomMargin + itemMargin * 3
                        rightMargin = this@PlayFullActivity.resources.getDimensionPixelSize(R.dimen.dp_18)
                    }
                customLikeView.setLayoutParams(likeParams)
                views.add(customLikeView)

                //收藏按钮
                val customCollectView = CustomCollectView(this@PlayFullActivity)
                val collectParams =
                    FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT).apply {
                        gravity = Gravity.BOTTOM or Gravity.RIGHT
                        bottomMargin = aLLBottomMargin + itemMargin * 2
                        rightMargin = this@PlayFullActivity.resources.getDimensionPixelSize(R.dimen.dp_18)
                    }
                customCollectView.setLayoutParams(collectParams)
                views.add(customCollectView)

                //选集,测试过无法触发点击事件
                val customPEView = CustomView(this@PlayFullActivity, R.mipmap.fy_list)
                customPEView.text = resources.getString(R.string.list)
                val peParams =
                    FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT).apply {
                        gravity = Gravity.BOTTOM or Gravity.RIGHT
                        bottomMargin = aLLBottomMargin + itemMargin * 1
                        rightMargin = this@PlayFullActivity.resources.getDimensionPixelSize(R.dimen.dp_18)
                    }
                customPEView.setLayoutParams(peParams)
                views.add(customPEView)
                customPEView.setOnClickListener {
                    shortPlayFragment?.pausePlay()
                    showShortPlayEPDialog(shortPlay.total, startFromIndex, 0, object : DialogSelectEP {
                        override fun dismissAction() {
                            shortPlayFragment?.startPlay()
                        }

                        override fun selectEPAction(ep: Int) {
                            super.selectEPAction(ep)
                            startFromIndex = ep
                            shortPlayFragment?.startPlayIndex(startFromIndex)
                        }
                    })
                }

                //分享
                val customShareView = CustomShareView(this@PlayFullActivity)
                customShareView.text = resources.getString(R.string.share)
                val shareParams =
                    FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT).apply {
                        gravity = Gravity.BOTTOM or Gravity.RIGHT
                        bottomMargin = aLLBottomMargin
                        rightMargin = this@PlayFullActivity.resources.getDimensionPixelSize(R.dimen.dp_18)
                    }
                customShareView.setLayoutParams(shareParams)
                views.add(customShareView)
                customShareView.setOnClickListener {
                    val intent = Intent(Intent.ACTION_SEND)
                    intent.setType("text/plain")
                    intent.putExtra(Intent.EXTRA_SUBJECT, shortPlay.title)
                    intent.putExtra(Intent.EXTRA_TEXT, shortPlay.desc)
                    startActivity(Intent.createChooser(intent, "分享短剧"))
                }

                //控制按钮
                val playControlView = CustomOverlayView(this@PlayFullActivity, R.layout.layout_overlay_player)
                playControlView.layoutParams =
                    FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT)
                playControlView.let { views.add(it) }
                //全局持有控制view
                playControlView.bindItemDataCallBack = { data, index, view ->
                    playControlViewSparseArray[index] = view
                }
                val playerBinding = LayoutOverlayPlayerBinding.bind(playControlView)
                bindPlayControlView(playerBinding)
                return views
            }
        })
        if (shortPlayFragment == null) {
            LogEx.logDebug(TAG, "create detailFragment failed")
            return
        }

        shortPlayFragment?.let {
            // 将播放页展示出来
            supportFragmentManager.beginTransaction()
                .add(R.id.fragment_container, it)
                .show(it).commit()
        }

    }

    private fun saveShortPlayHistory(shortPlay: ShortPlay, epIndex: Int) = lifecycleScope.launch(Dispatchers.IO) {

        val list = SpJsonUtils.getSpJsonList<ShortPlayHistory>(KEY_SHORTPLAY_HISTORY).toMutableList()
        val findBean = list.find { it.shortPlay.id == shortPlay.id }
        if (findBean == null) {
            val newHistory = ShortPlayHistory(shortPlay, epIndex)
            list.add(newHistory)
            SpJsonUtils.saveJsonBeanList(KEY_SHORTPLAY_HISTORY, list)
        } else {
            findBean.epIndex = epIndex
            SpJsonUtils.saveJsonBeanList(KEY_SHORTPLAY_HISTORY, list)
        }

    }

    private fun bindPlayControlView(playerBinding: LayoutOverlayPlayerBinding) {
        playerBinding.niftySlider.addOnValueChangeListener { slider, value, fromUser ->
            if (fromUser) {
                LogEx.logDebug(TAG, "value=$value")
                shortPlayFragment?.setCurrentPlayTimeSeconds(value.toInt())
                playerBinding.tvPlayNow.text = value.toLong().formatSeconds() + " / "
            }
        }
        playerBinding.tvSpeed.setOnClickListener {
            showShortPlaySpeedDialog(playSpeed) { newSpeed ->
                if (playSpeed != newSpeed) {
                    playSpeed = newSpeed
                    shortPlayFragment?.setVideoSpeed(newSpeed)
                    playerBinding.tvSpeed.text = "${newSpeed}x"
                }
            }
        }
        playerBinding.tvQuality.setOnClickListener {
            if (resolutions == null) {
                toast("the video not support change resolution", true)
                return@setOnClickListener
            } else {
                resolutions?.let {
                    showShortPlayQualityDialog(this@PlayFullActivity.currentResolution, it) { resolution, resolutionString ->
                        if (currentResolution != resolution) {
                            currentResolution = resolution
                            shortPlayFragment?.setResolution(resolution)
                            playerBinding.tvQuality.text = resolutionString
                        }
                    }
                }
            }
        }
        playerBinding.tvTitle.text = "${shortPlay?.title}"
        playerBinding.flBack.setOnClickListener {
            onBackPressedDispatcher.onBackPressed()
        }
        playerBinding.flMore.setOnClickListener {

            val popup = MyPopupMore(this, R.layout.pupup_more)
            popup.setBlurBackgroundEnable(false)
            popup.setBackground(ContextCompat.getDrawable(this, R.drawable.trans))
            popup.setPopupGravity(Gravity.BOTTOM or Gravity.CENTER_HORIZONTAL)
            popup.showPopupWindow(playerBinding.flMore)
            val popupBinding = PupupMoreBinding.bind(popup.contentView)
            popupBinding.root.setOnClickListener {
                popup.dismiss()
                showReportProblemDialog()
            }

        }

    }

    override fun configSystemBar() {
        ImmersionBar.with(this)
            .statusBarColor(R.color.black)
            .init()
    }

}