package com.base.appzxhy.ui.main

import android.content.Intent
import android.view.Gravity
import android.view.View
import android.widget.FrameLayout
import androidx.fragment.app.Fragment
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import com.base.appzxhy.R
import com.base.appzxhy.base.BaseFragment
import com.base.appzxhy.databinding.FragmentPlaySlideBinding
import com.base.appzxhy.databinding.LayoutOverlayForyouBinding
import com.base.appzxhy.ui.play.CustomCollectView
import com.base.appzxhy.ui.play.CustomLikeView
import com.base.appzxhy.ui.play.CustomOverlayView
import com.base.appzxhy.ui.play.CustomShareView
import com.base.appzxhy.ui.play.PlayFullActivity
import com.base.appzxhy.utils.LogEx
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
import com.google.gson.Gson
import java.util.concurrent.atomic.AtomicBoolean
import kotlin.random.Random


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

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

    //    private val customViewSparseArray = SparseArray<CustomOverlayView>()
    private var currentShortPlay: ShortPlay? = null
    private var currentShortPlayIndex: Int? = 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?) {
                        }
                    })
                }

                if (feedListAdapter?.needLoadMore(position) == true) {
                    loadMore()
                }


            }
        })

        loadMore()
    }

    private var isLoading = AtomicBoolean(false)
    private var loadIndex = 1
    private var hasMore: Boolean = true
    private fun loadMore() {

        if (isLoading.get() || !hasMore) return
        isLoading.set(true)

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

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

                val activity = requireActivity() as MainActivity?

                hasMore = result.hasMore
                val list = result.dataList
                activity?.runOnUiThread { setShortData(list) }
                LogEx.logDebug(TAG, "hasMore=$hasMore")

                loadIndex++
                isLoading.set(false)
            }
        })
    }


    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? {

        var freeEp = 10
        if (freeEp >= shortPlay.total) {
            freeEp = shortPlay.total
        }
        val startFromIndex = Random.nextInt(1, freeEp)

        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)
            .startPlayIndex(startFromIndex)

        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) {
                LogEx.logDebug(TAG, "onShortPlayPlayed shortPlay=$shortPlay index=$index")
                currentShortPlay = shortPlay
                currentShortPlayIndex = index
            }

            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>()

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

                //分享
                val customShareView = CustomShareView(requireContext())
                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 = resources.getDimensionPixelSize(R.dimen.dp_18)
                    }
                customShareView.setLayoutParams(shareParams)
                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 customCollectView = CustomCollectView(requireContext())
                val collectParams =
                    FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT).apply {
                        gravity = Gravity.BOTTOM or Gravity.RIGHT
                        bottomMargin = aLLBottomMargin + itemMargin * 1
                        rightMargin = resources.getDimensionPixelSize(R.dimen.dp_18)
                    }
                customCollectView.setLayoutParams(collectParams)


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


                val customOverlayView = CustomOverlayView(requireContext(), R.layout.layout_overlay_foryou)
                customOverlayView.bindItemDataCallBack = { data, index, view ->
                    val customBinding = LayoutOverlayForyouBinding.bind(view)
                    customBinding.llBtn.setOnClickListener {
                        val activity = requireActivity() as MainActivity?
                        val useData = currentShortPlay ?: data

                        LogEx.logDebug(TAG, "PlayFullActivity currentShortPlayIndex=$currentShortPlayIndex")
                        activity?.startActivity(Intent(activity, PlayFullActivity::class.java).apply {
                            putExtra("data", Gson().toJson(useData))
                            if (currentShortPlayIndex != null) {
                                putExtra("startFromIndex", currentShortPlayIndex)
                            }
                        })
                    }
                }

                views.add(customLikeView)
                views.add(customCollectView)
                views.add(customShareView)
                views.add(customOverlayView)

                return views
            }
        })
        return shortPlayFragment
    }

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

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

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

        fun needLoadMore(position: Int): Boolean {
            return fragments.size - position < 5
        }

        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()
    }

}