package com.base.appzxhy.ui.main

import android.view.View
import androidx.fragment.app.Fragment
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import com.base.appzxhy.base.BaseFragment
import com.base.appzxhy.databinding.FragmentPlaySlideBinding
import com.bytedance.sdk.shortplay.api.PSSDK
import com.bytedance.sdk.shortplay.api.PSSDK.DetailPageConfig
import com.bytedance.sdk.shortplay.api.PSSDK.FeedListLoadResult
import com.bytedance.sdk.shortplay.api.PSSDK.FeedListResultListener
import com.bytedance.sdk.shortplay.api.ShortPlay
import com.bytedance.sdk.shortplay.api.ShortPlayFragment


class PlaySlideFragment : BaseFragment<FragmentPlaySlideBinding>(FragmentPlaySlideBinding::inflate) {

    private var feedListAdapter: FeedListAdapter? = null
    private var currentShortPlayFragment: ShortPlayFragment? = null

    override fun initView() {
        super.initView()
        feedListAdapter = FeedListAdapter(this)
        binding.vpShortFeed.adapter = feedListAdapter
        binding.vpShortFeed.setOrientation(ViewPager2.ORIENTATION_VERTICAL)
        binding.vpShortFeed.offscreenPageLimit = 1
        binding.vpShortFeed.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {

            override fun onPageSelected(position: Int) {

                //当前fragment
                val currentFragment = feedListAdapter?.getItem(position)
                if (currentFragment is ShortPlayFragment) {
                    currentShortPlayFragment = currentFragment
                }

                //预加载下个fragment
                val nextPos = position + 1
                val nextPlayFragment = feedListAdapter?.getItem(nextPos)
                if (nextPlayFragment is ShortPlayFragment) {
                    nextPlayFragment.preLoadVideo(object : PSSDK.ActionResultListener {
                        override fun onSuccess() {

                        }

                        override fun onFail(p0: PSSDK.ErrorInfo?) {
                        }
                    })
                }
            }
        })

        PSSDK.requestPopularDrama(1, 20, object : FeedListResultListener {
            override fun onFail(errorInfo: PSSDK.ErrorInfo?) {
            }

            override fun onSuccess(result: FeedListLoadResult<ShortPlay>?) {

                val activity = requireActivity() as MainActivity?
                result?.dataList?.let {
                    activity?.runOnUiThread {
                        setShortData(it)
                    }
                }
            }
        })
    }

    private fun setShortData(dataList: List<ShortPlay>) {

        val fragments: ArrayList<Fragment> = ArrayList()
        dataList.forEach { shortPlay ->
            val shortPlayFragment = createShortPlayFragment(shortPlay)
            shortPlayFragment?.let { fragments.add(it) }
        }
        feedListAdapter?.appendData(fragments)
    }

    private fun createShortPlayFragment(shortPlay: ShortPlay): ShortPlayFragment? {

        val builder = DetailPageConfig.Builder()
        builder.hideLeftTopCloseAndTitle(true, null)
            .displayBottomExtraView(false)
            .displayProgressBar(false)
            .displayTextVisibility(DetailPageConfig.TEXT_POS_BOTTOM_TITLE, false)
            .displayTextVisibility(DetailPageConfig.TEXT_POS_BOTTOM_DESC, false)
            .playSingleItem(true)
        val config = builder.build()

        val shortPlayFragment = PSSDK.createDetailFragment(shortPlay, config, object : PSSDK.ShortPlayDetailPageListener {

            override fun onProgressChange(shortPlay: ShortPlay, index: Int, currentPlayTime: Int, duration: Int) = Unit
            override fun onPlayFailed(errorInfo: PSSDK.ErrorInfo?): Boolean = false
            override fun onShortPlayPlayed(shortPlay: ShortPlay?, index: Int) = Unit
            override fun onItemSelected(position: Int, type: PSSDK.ShortPlayDetailPageListener.ItemType, index: Int) = Unit
            override fun onVideoPlayStateChanged(shortPlay: ShortPlay?, index: Int, playbackState: Int) = Unit
            override fun onVideoPlayCompleted(shortPlay: ShortPlay?, index: Int) = Unit
            override fun onEnterImmersiveMode() = Unit
            override fun onExitImmersiveMode() = Unit
            override fun isNeedBlock(shortPlay: ShortPlay?, index: Int): Boolean = false
            override fun showAdIfNeed(shortPlay: ShortPlay?, index: Int, listener: PSSDK.ShortPlayBlockResultListener?) = Unit
            override fun onVideoInfoFetched(shortPlay: ShortPlay?, index: Int, videoPlayInfo: PSSDK.VideoPlayInfo?) = Unit

            override fun onObtainPlayerControlViews(): MutableList<View> {
                val views = ArrayList<View>()

                return views
            }
        })
        return shortPlayFragment
    }

    override fun initListener() {
        super.initListener()
    }

    inner class FeedListAdapter(fragment: Fragment) : FragmentStateAdapter(fragment) {

        private val fragments: ArrayList<Fragment> = ArrayList()

        override fun getItemCount(): Int {
            return fragments.size
        }

        override fun createFragment(position: Int): Fragment {
            return fragments[position]
        }

        fun appendData(fragments: List<Fragment>) {
            val size = this.fragments.size
            this.fragments.addAll(fragments)
            notifyItemRangeInserted(size, fragments.size)
        }

        fun getItem(position: Int): Fragment? {
            if (position < 0 || position >= fragments.size) {
                return null
            }
            return fragments[position]
        }
    }

    override fun onResumeOneShoot() {
        super.onResumeOneShoot()
        currentShortPlayFragment?.startPlay()
    }

    override fun onPause() {
        super.onPause()
        currentShortPlayFragment?.onPause()
    }

}