package com.duben.microtribe.ui.fragment

import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
import com.duben.microtribe.R
import com.duben.microtribe.common.AppConfig
import com.duben.microtribe.common.Constant
import com.duben.microtribe.manager.UserManager
import com.duben.microtribe.ui.activitys.MainActivity
import com.duben.microtribe.ui.adapter.RecommendPageAdapter
import com.duben.microtribe.ui.fragment.base.BaseFragment
import com.duben.microtribe.video.csj.DramaTabFragment
import com.duben.microtribe.video.tx.TxVideoFragment
import com.duben.library.utils.nodoubleclick.AntiShake
import kotlinx.android.synthetic.main.fragment_recommend.*

/**
 *  @author Assen
 *  @date 2023/7/5
 *  @desc 主页 -> 推荐
 */
class RecommendFragment : BaseFragment(), View.OnClickListener {

    private var mCurrentNewFlag = false

    private var mSelectTabIndex = 0
    private val tabsData = mutableListOf<String>()
    private val fragments = mutableListOf<Fragment>()
    private var vpAdapter: RecommendPageAdapter? = null

    override fun initViewsAndEvents() {
        iv_edit.setOnClickListener(this)
        iv_edit_close.setOnClickListener(this)

        initVp2()
    }

    override fun getContentViewLayoutID() = R.layout.fragment_recommend

    private fun initVp2() {
        mCurrentNewFlag = UserManager.getInstance().newFlag
        fragments.clear()
        tabsData.add("追剧")
        tabsData.add("推荐")

        fragments.clear()
        if (mCurrentNewFlag) {
            fragments.add(FollowVideoFragment.newInstance())
            fragments.add(TxVideoFragment.newInstance())
        } else {
            fragments.add(FollowVideoFragment.newInstance())
            fragments.add(DramaTabFragment())
        }

        vpAdapter = RecommendPageAdapter(fragments, this)
        vp2_recommend.adapter = vpAdapter

        TabLayoutMediator(tab_recommend, vp2_recommend) { tab, position ->
            // 初始化Tab
            tab.id = position
            tab.customView = getTabView(position)
        }.attach()
        tab_recommend.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab?) {
                mSelectTabIndex = tab!!.id
                updateTab(tab, true, mSelectTabIndex)
                if (mSelectTabIndex == 0) {
                    changeBottomTabColor(false)
                } else {
                    changeBottomTabColor(true)
                    iv_edit.visibility = View.GONE
                }
            }

            override fun onTabUnselected(tab: TabLayout.Tab?) {
                updateTab(tab, false, mSelectTabIndex)
            }

            override fun onTabReselected(tab: TabLayout.Tab?) {
            }
        })
        // 默认选中第二个
        tab_recommend.getTabAt(1)?.select()
        vp2_recommend.setCurrentItem(1, false)
        vp2_recommend.offscreenPageLimit = 1
        vp2_recommend.isUserInputEnabled = false
    }

    private fun getTabView(position: Int): View {
        val view = LayoutInflater.from(requireContext()).inflate(R.layout.item_recommend_tab, null)
        view.findViewById<TextView>(R.id.item_tv).text = tabsData[position]
        if (position == 0) {
            view.findViewById<View>(R.id.item_line).background =
                ContextCompat.getDrawable(requireContext(), R.drawable.shape_line_corner_red)
        }
        return view
    }

    private fun updateTab(tab: TabLayout.Tab?, isSelected: Boolean, position: Int) {
        tab?.customView?.let {
            val text = it.findViewById<TextView>(R.id.item_tv)
            val line = it.findViewById<View>(R.id.item_line)
            line.visibility = if (isSelected) View.VISIBLE else View.INVISIBLE
            if (position == 0) {
                if (isSelected) {
                    text.setTextColor(ContextCompat.getColor(requireContext(), R.color.black))
                } else {
                    text.setTextColor(
                        ContextCompat.getColor(
                            requireContext(),
                            R.color.my_color_gray
                        )
                    )
                }
                line.background =
                    ContextCompat.getDrawable(requireContext(), R.drawable.shape_line_corner_red)
            } else {
                if (isSelected) {
                    text.setTextColor(ContextCompat.getColor(requireContext(), R.color.white))
                } else {
                    text.setTextColor(
                        ContextCompat.getColor(
                            requireContext(),
                            R.color.color_8D8F90
                        )
                    )
                }
                line.background =
                    ContextCompat.getDrawable(requireContext(), R.drawable.shape_line_corner_white)
            }

        }
    }


    override fun onResume() {
        super.onResume()

        if (AppConfig.fragmentClickFlag == Constant.FRAGMENT_CLICK_TWO) {
            if (mCurrentNewFlag != UserManager.getInstance().newFlag) {
                mCurrentNewFlag = UserManager.getInstance().newFlag
                // 重置状态
                initVp2()
            }
        }
    }

    override fun onClick(v: View?) {
        if (AntiShake.check(v?.id)) return

        when (v?.id) {
            R.id.iv_edit -> {
                handleEditStyle(true)
            }
            R.id.iv_edit_close -> {
                handleEditStyle(false)
            }
            else -> {}
        }
    }

    private fun handleEditStyle(isEdit: Boolean) {
        if (isEdit) {
            // 禁止滑动
            iv_edit.visibility = View.GONE
            iv_edit_close.visibility = View.VISIBLE
            tab_recommend.visibility = View.GONE
            tv_edit_text.visibility = View.VISIBLE
        } else {
            // 允许滑动
            iv_edit.visibility = View.VISIBLE
            iv_edit_close.visibility = View.GONE
            tab_recommend.visibility = View.VISIBLE
            tv_edit_text.visibility = View.GONE
        }
        (requireActivity() as MainActivity).showEdit(isEdit)
        (fragments[0] as FollowVideoFragment).getAdapter()?.setEditStyle(isEdit)
    }

    private fun changeBottomTabColor(showBlack: Boolean) {
        (requireActivity() as MainActivity).showBlack(showBlack)
        (requireActivity() as MainActivity).statusBarDark(!showBlack)
    }

    fun showEditView(show: Boolean) {
        handleEditStyle(!show)
    }

    fun fullChoice() {
        (fragments[0] as FollowVideoFragment).getAdapter()?.fullChoice()
    }

    fun changeTab(index: Int) {
        tab_recommend.getTabAt(index)?.select()
    }

    fun delete() {
        (fragments[0] as FollowVideoFragment).delete()
    }

    fun hideEditView(hide: Boolean) {
        if (hide) {
            iv_edit.visibility = View.GONE
        } else {
            iv_edit.visibility = View.VISIBLE
        }
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        if (mSelectTabIndex == 0) return

        // 传递生命周期
        if (hidden) {
            fragments[1].onPause()
            onPause()
        } else {
            fragments[1].onResume()
            onResume()
        }
    }

}