package com.base.appzxhy.ui.main.mylist

import androidx.core.content.ContextCompat
import androidx.core.view.updatePadding
import androidx.fragment.app.Fragment
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import com.angcyo.tablayout.delegate2.ViewPager2Delegate
import com.base.appzxhy.R
import com.base.appzxhy.base.BaseFragment
import com.base.appzxhy.databinding.FragmentMyListBinding
import com.base.appzxhy.utils.BarUtils


class MyListFragment : BaseFragment<FragmentMyListBinding>(FragmentMyListBinding::inflate) {

    private val myListPage by lazy(LazyThreadSafetyMode.NONE) {
        MyListPageFragment()
    }
    private val historyPage by lazy(LazyThreadSafetyMode.NONE) {
        MyListPageFragment()
    }
    private val fragments = arrayOf(myListPage, historyPage)
    private var pageAdapter: FragmentStateAdapter? = null

    override fun initView() {
        super.initView()
        binding.root.updatePadding(top = BarUtils.getStatusBarHeight())
        initViewPager2()
        initTab()
    }

    private fun initViewPager2() {
        pageAdapter = object : FragmentStateAdapter(this) {
            override fun getItemCount(): Int {
                return fragments.size
            }

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

        }
        binding.viewPager2.run {
            isUserInputEnabled = false
            offscreenPageLimit = 1
            //https://www.jianshu.com/p/f69bd30cf5b0
            //FragmentStateAdapter 这里必须传人fragment
            adapter = pageAdapter
        }
        binding.viewPager2.registerOnPageChangeCallback(object :
            ViewPager2.OnPageChangeCallback() {

            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
                super.onPageScrolled(position, positionOffset, positionOffsetPixels)
            }

            override fun onPageSelected(position: Int) {
            }
        })
    }

    private fun initTab() {
        binding.dslTabLayout.tabIndicator.indicatorDrawable =
            ContextCompat.getDrawable(requireContext(), R.drawable.indicator_bottom_line)

        binding.dslTabLayout.tabIndicator.indicatorWidth = resources.getDimensionPixelSize(R.dimen.dp_50)
        binding.dslTabLayout.tabIndicator.indicatorHeight = resources.getDimensionPixelSize(R.dimen.dp_2)
        binding.dslTabLayout.tabIndicator.ignoreChildPadding = true

        binding.dslTabLayout.configTabLayoutConfig {
            onSelectIndexChange = { fromIndex, selectIndexList, reselect, fromUser ->
                val toIndex = selectIndexList.first()
            }
        }
        ViewPager2Delegate.install(binding.viewPager2, binding.dslTabLayout)
    }

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

}