package com.gh.gamecenter.subject.tab

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.CheckedTextView
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentStatePagerAdapter
import androidx.viewpager.widget.ViewPager
import com.gh.common.util.NewLogUtils
import com.gh.gamecenter.R
import com.gh.gamecenter.common.base.fragment.BaseFragment
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.common.utils.dip2px
import com.gh.gamecenter.common.utils.toColor
import com.gh.gamecenter.common.utils.toDrawable
import com.gh.gamecenter.core.utils.MtaHelper
import com.gh.gamecenter.core.utils.UrlFilterUtils
import com.gh.gamecenter.databinding.FragmentSubjectTabBinding
import com.gh.gamecenter.entity.SubjectData
import com.gh.gamecenter.entity.SubjectSettingEntity
import com.gh.gamecenter.subject.SubjectListFragment
import com.google.android.material.tabs.TabLayout

class SubjectTabFragment : BaseFragment<Any>() {

    private val mBinding by lazy { FragmentSubjectTabBinding.inflate(layoutInflater) }

    override fun getLayoutId() = 0
    override fun getInflatedLayout() = mBinding.root

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val mSubjectList = arguments?.getParcelableArrayList<SubjectData>(EntranceConsts.KEY_DATA)
        val fragments = ArrayList<Fragment>()
        var tagList = arrayListOf<String>()
        val fragmentTag = "android:switcher:${mBinding.subjectViewpager.id}:"
        if (mSubjectList.isNullOrEmpty()) {
            // 专题详情
            val subjectData = arguments?.getParcelable<SubjectData>(EntranceConsts.KEY_SUBJECT_DATA)
                ?: return
            val settingsEntity =
                arguments?.getParcelable<SubjectSettingEntity>(SubjectSettingEntity::class.java.simpleName)
                    ?: return
            tagList = settingsEntity.typeEntity.content as ArrayList<String>
            if (tagList.size > 1) {
                mBinding.subjectTabContainer.visibility = View.VISIBLE
            }
            tagList.forEachIndexed { index, tag ->
                val element = childFragmentManager.findFragmentByTag("${fragmentTag}$index")
                    ?: SubjectListFragment()
                val bundle = arguments?.clone() as Bundle?
                val copyData = subjectData.deepCopy()
                copyData.filter = if (tag == "全部") {
                    UrlFilterUtils.getFilterQuery("tags", tag, "type", "全部")
                } else {
                    UrlFilterUtils.getFilterQuery("tags", tag)
                }
                bundle?.putParcelable(EntranceConsts.KEY_SUBJECT_DATA, copyData)
                bundle?.putString(EntranceConsts.KEY_SUBJECT_TYPE, "detail")
                element.arguments = bundle
                fragments.add(element)
            }
        } else {
            // 排行榜
            mBinding.subjectTabContainer.visibility = View.VISIBLE

            mSubjectList.filterIndexed { index, subject ->
                val element = childFragmentManager.findFragmentByTag("${fragmentTag}$index")
                    ?: SubjectListFragment()
                val bundle = arguments?.clone() as Bundle?
                bundle?.putParcelable(EntranceConsts.KEY_SUBJECT_DATA, subject)
                bundle?.putString(EntranceConsts.KEY_SUBJECT_TYPE, "tab")
                element.arguments = bundle
                fragments.add(element)

                tagList.add(subject.subjectName ?: "")
            }

            mBinding.subjectViewpager.post {
                mBinding.subjectViewpager.offscreenPageLimit = fragments.size
                var position = arguments?.getInt(EntranceConsts.KEY_POSITION, 0) ?: 0
                val columnName = arguments?.getString(EntranceConsts.KEY_COLUMNNAME) ?: ""
                if (columnName.isNotEmpty()) {
                    position = mSubjectList.indexOfFirst { it.subjectName == columnName }
                }
                if (position < mSubjectList.size) {
                    mBinding.subjectViewpager.setCurrentItem(position, false)
                    if (position == 0) {
                        MtaHelper.onEvent("游戏专题合集", "详情Tab", mSubjectList[position].subjectName)
                    }
                }
            }
            val categoryId = requireArguments().getString(EntranceConsts.KEY_GAME_COLLECTION_ID, "")
            val categoryName = requireArguments().getString(EntranceConsts.KEY_GAME_COLLECTION_TITLE, "")

            mBinding.subjectViewpager.addOnPageChangeListener(object : ViewPager.SimpleOnPageChangeListener() {
                override fun onPageSelected(position: Int) {
                    mSubjectList[position]?.let {
                        MtaHelper.onEvent("游戏专题合集", "详情Tab", it.subjectName)
                        NewLogUtils.logColumnCategoryDetailContentClick(
                            it.subjectName ?: "", it.subjectId ?: "", categoryName, categoryId
                        )
                    }

                }
            })
        }

        if (mBinding.subjectTabContainer.visibility == View.VISIBLE) {
            mBinding.subjectTabIndicator.setupWithTabLayout(mBinding.subjectTab)
            mBinding.subjectTabIndicator.setupWithViewPager(mBinding.subjectViewpager)
        }

        val adapter = object : FragmentStatePagerAdapter(childFragmentManager) {
            override fun getItem(position: Int): Fragment {
                return fragments[position]
            }

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

            override fun getPageTitle(position: Int): CharSequence? {
                return tagList[position]
            }

            override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
//                super.destroyItem(container, position, `object`)
            }
        }
        mBinding.subjectViewpager.adapter = adapter
        mBinding.subjectTab.setupWithViewPager(mBinding.subjectViewpager)
        // 首页样式的 tabLayout
        if (arguments?.getBoolean(EntranceConsts.KEY_IS_HOME) == true) {
            mBinding.subjectTabIndicator.visibility = View.GONE
            for (i in 0 until mBinding.subjectTab.tabCount) {
                val tab = mBinding.subjectTab.getTabAt(i) ?: continue
                val tabTitle = if (tab.text != null) tab.text.toString() else ""

                tab.customView = provideTabView(tabTitle)
                if (i == 0) {
                    tab.customView?.background = R.drawable.border_round_theme_14.toDrawable(requireContext())
                    tab.customView?.findViewById<TextView>(R.id.tab_title)
                        ?.setTextColor(R.color.theme_font.toColor(requireContext()))
                } else {
                    tab.customView?.background = R.drawable.border_round_eee_14.toDrawable(requireContext())
                    tab.customView?.findViewById<TextView>(R.id.tab_title)
                        ?.setTextColor(R.color.text_title.toColor(requireContext()))
                }

                when (i) {
                    0 -> tab.view.setPadding(12F.dip2px(), 0, 0, 0)

                    mBinding.subjectTab.tabCount - 1 -> tab.view.setPadding(8F.dip2px(), 0, 12F.dip2px(), 0)

                    else -> tab.view.setPadding(8F.dip2px(), 0, 0, 0)
                }
            }

            mBinding.subjectTab.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
                override fun onTabReselected(tab: TabLayout.Tab?) {}

                override fun onTabUnselected(tab: TabLayout.Tab?) {
                    tab?.customView?.background = R.drawable.border_round_eee_14.toDrawable(requireContext())
                    tab?.customView?.findViewById<TextView>(R.id.tab_title)
                        ?.setTextColor(R.color.text_title.toColor(requireContext()))
                }

                override fun onTabSelected(tab: TabLayout.Tab?) {
                    tab?.customView?.background = R.drawable.border_round_theme_14.toDrawable(requireContext())
                    tab?.customView?.findViewById<TextView>(R.id.tab_title)
                        ?.setTextColor(R.color.theme_font.toColor(requireContext()))
                }
            })
        }
    }

    private fun provideTabView(title: String): View {
        val view = LayoutInflater.from(requireContext()).inflate(R.layout.tab_item_ranking_home, null)
        val tabTitle = view.findViewById<View>(R.id.tab_title)
        if (tabTitle is CheckedTextView) {
            tabTitle.text = title
        }
        return view
    }

    override fun onDarkModeChanged() {
        super.onDarkModeChanged()
        for (i in 0 until mBinding.subjectTab.tabCount) {
            val tab = mBinding.subjectTab.getTabAt(i) ?: continue
            tab.customView?.background =
                if (tab.isSelected) R.drawable.border_round_theme_14.toDrawable(requireContext()) else R.drawable.border_round_eee_14.toDrawable(
                    requireContext()
                )
            tab.customView?.findViewById<TextView>(R.id.tab_title)
                ?.setTextColor(
                    if (tab.isSelected) R.color.theme_font.toColor(requireContext()) else R.color.text_title.toColor(
                        requireContext()
                    )
                )
        }
    }
}
