package com.base.appzxhy.ui.views

import android.annotation.SuppressLint
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import androidx.core.content.ContextCompat
import com.base.appzxhy.R
import com.base.appzxhy.bean.ShortPlayEPBean
import com.base.appzxhy.databinding.DialogEpListBinding
import com.base.appzxhy.ui.adapter.EPAdapter
import com.base.appzxhy.utils.XmlEx.inflate
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.bottomsheet.BottomSheetDialog

interface DialogSelectEP {

    open fun dismissAction() {}
    open fun selectEPAction(ep: Int) {}
}

object ShortPlayEPDialog {

    @SuppressLint("SetTextI18n")
    fun Context.showShortPlayEPDialog(
        totalEp: Int,
        playEp: Int,
        lockEp: Int = 9,
        callBack: DialogSelectEP
    ) {
        val dialog = BottomSheetDialog(this, R.style.BottomSheetDialog)
        val binding = DialogEpListBinding.inflate(LayoutInflater.from(this))
        dialog.setContentView(binding.root)
        dialog.setCanceledOnTouchOutside(true)

        dialog.show()

        val parentView = binding.root.parent as View
        val behavior = BottomSheetBehavior.from(parentView)
        //展开
        behavior.state = BottomSheetBehavior.STATE_EXPANDED

        val list = ArrayList<ShortPlayEPBean>()
        repeat(totalEp) { i ->
            val ep = i + 1
            val lock = ep >= lockEp
            val isPlay = ep == playEp
            val bean = ShortPlayEPBean(ep, lock, isPlay)
            list.add(bean)
        }
        val splitLists = list.chunked(50)
        splitLists.forEach {
            val view = R.layout.item_ep_tab.inflate(this)
            view.findViewById<TextView>(R.id.tv).text = "${it.first().ep} - ${it.last().ep}"
            binding.dslTabLayout.addView(view)
        }
        binding.dslTabLayout.tabIndicator.indicatorDrawable =
            ContextCompat.getDrawable(this, R.drawable.indicator_bottom_line_ff3d71)
        binding.dslTabLayout.tabIndicator.indicatorEnableFlow = true
        binding.dslTabLayout.tabIndicator.ignoreChildPadding = true
        binding.dslTabLayout.tabIndicator.indicatorWidth = resources.getDimensionPixelSize(R.dimen.dp_28)
        binding.dslTabLayout.tabIndicator.indicatorHeight = resources.getDimensionPixelSize(R.dimen.dp_2)

        val adapter = EPAdapter()
        binding.rv.adapter = adapter
        adapter.selectEp = { ep, lock ->
            dialog.dismiss()
            callBack.selectEPAction(ep)
        }

        binding.dslTabLayout.configTabLayoutConfig {
            onSelectIndexChange = { fromIndex, selectIndexList, reselect, fromUser ->
                val toIndex = selectIndexList.first()
                val epList = splitLists[toIndex]
                adapter.submitList(epList)
            }
        }

        dialog.setOnDismissListener {
            callBack.dismissAction()
        }
    }
}