package com.gh.vspace

import android.content.Intent
import android.os.Bundle
import android.view.MenuItem
import android.view.View
import android.widget.TextView
import androidx.fragment.app.Fragment
import com.gh.gamecenter.R
import com.gh.gamecenter.common.base.fragment.BaseLazyTabFragment
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.common.utils.viewModelProvider
import com.gh.gamecenter.databinding.FragmentVdownloadManagerWrapperBinding
import com.gh.gamecenter.history.IBatchDelete
import com.gh.gamecenter.history.ManageOption

class VDownloadManagerWrapperFragment : BaseLazyTabFragment() {

    private var mLastPosition = 0
    private var mManageMenu: MenuItem? = null
    private val mViewModel: VDownloadManagerWrapperViewModel by lazy { viewModelProvider() }
    private val mBinding by lazy { FragmentVdownloadManagerWrapperBinding.inflate(layoutInflater) }

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

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        setNavigationTitle("畅玩游戏管理")

        initMenu(R.menu.menu_manage)
        mBinding.bottomContainer.setOnClickListener {
            VHelper.startVSpaceSquare(requireContext())
        }

        arguments?.getInt(EntranceConsts.KEY_POSITION)?.let {
            mViewPager.post { mViewPager.currentItem = it }
        }

        mManageMenu = getItemMenu(R.id.layout_menu_manage)
        mManageMenu?.actionView?.setOnClickListener {
            when (mViewModel.currentOptionLiveData.value) {
                ManageOption.OPTION_MANAGER -> {
                    mViewModel.currentOptionLiveData.value = ManageOption.OPTION_CANCEL_SELECT
                }
                ManageOption.OPTION_CANCEL_SELECT -> {
                    mViewModel.currentOptionLiveData.value = ManageOption.OPTION_MANAGER
                }
                else -> {
                    // do nothing
                }
            }
            changeOption()
        }
        changeMenuTextByOption()
    }

    override fun initFragmentList(fragments: MutableList<Fragment>) {
        fragments.add(VDownloadManagerFragment().with(Bundle().apply {
            putString(VDownloadManagerViewModel.TYPE, VDownloadManagerViewModel.TYPE_DOWNLOADED)
            putBoolean(
                EntranceConsts.KEY_IS_FROM_HOME_RECENT,
                arguments?.getBoolean(EntranceConsts.KEY_IS_FROM_HOME_RECENT) ?: false
            )
        }))
        fragments.add(VDownloadManagerFragment().with(Bundle().apply {
            putString(VDownloadManagerViewModel.TYPE, VDownloadManagerViewModel.TYPE_DOWNLOADING)
        }))
    }

    override fun initTabTitleList(tabTitleList: MutableList<String>) {
        tabTitleList.add("在玩")
        tabTitleList.add("下载")
    }

    fun onNewIntent(intent: Intent?) {
        childFragmentManager.fragments.forEach {
            if (it.isAdded && it is VDownloadManagerFragment) {
                it.onLoadRefresh()
            }
        }

        intent?.getIntExtra(EntranceConsts.KEY_POSITION, 0)?.let {
            mViewPager.post { mViewPager.currentItem = it }
        }
    }

    override fun onPageSelected(position: Int) {
        super.onPageSelected(position)
        mViewModel.currentOptionLiveData.value = ManageOption.OPTION_MANAGER
        changeOption()
        mLastPosition = position
    }

    private fun changeMenuTextByOption() {
        (mManageMenu?.actionView as? TextView)?.apply {
            text = when (mViewModel.currentOptionLiveData.value) {
                ManageOption.OPTION_MANAGER -> "管理"
                ManageOption.OPTION_CANCEL_SELECT -> "取消"
                else -> ""
            }
        }
    }

    fun changeOption() {
        try {
            val fragments = childFragmentManager.fragments
            mViewModel.currentOptionLiveData.value?.let {
                fragments.forEachIndexed { index, fragment ->
                    if (fragment is IBatchDelete) {
                        if (index == mViewPager.currentItem) {
                            fragment.changeOption(it)
                        } else if (index == mLastPosition) {
                            fragment.changeOption(ManageOption.OPTION_MANAGER)
                        }
                    }
                }
            }
            changeMenuTextByOption()
        } catch (e: IllegalStateException) {
            // 忽略页面快速滚动时 childFragment 尚未添加到 fragmentManager 的情况
        }
    }

}