package com.hongyegroup.cpt_parttime.ui.activity

import android.os.Bundle
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentTransaction
import com.guadou.cs_cptservices.YYConstants
import com.guadou.cs_cptservices.base.activity.YYBaseVDBActivity
import com.guadou.cs_cptservices.interfaces.IFragmentRefresh
import com.guadou.cs_router.YYRouterService
import com.guadou.lib_baselib.bean.DataBindingConfig
import com.guadou.lib_baselib.ext.commContext
import com.guadou.lib_baselib.ext.gotoActivity
import com.guadou.lib_baselib.utils.NetWorkUtil
import com.guadou.lib_baselib.utils.StatusBarUtils
import com.hongyegroup.cpt_parttime.BR
import com.hongyegroup.cpt_parttime.R
import com.hongyegroup.cpt_parttime.databinding.ActivityPartTimeMainBinding
import com.hongyegroup.cpt_parttime.mvvm.PartTimeMainViewModel
import com.hongyegroup.cpt_parttime.ui.main.PartTimeActivesFragment
import com.hongyegroup.cpt_parttime.ui.main.PartTimeHomeFragment
import com.hongyegroup.cpt_parttime.ui.main.PartTimeProfileFragment
import com.hongyegroup.cpt_parttime.ui.main.PartTimeTrainFragment
import com.jeremyliao.liveeventbus.LiveEventBus
import dagger.hilt.android.AndroidEntryPoint

/**
 * 兼职首页Tab + Fragment
 */
@AndroidEntryPoint
class PartTimeMainActivity : YYBaseVDBActivity<PartTimeMainViewModel, ActivityPartTimeMainBinding>() {

    //首页的5个TabFragment
    private var mPartTimeHomeFragment: Fragment? = null
    private var mPartTimeActiveFragment: Fragment? = null
    private var mPartTimeWalletFragment: Fragment? = null
    private var mPartTimeTrainFragment: Fragment? = null
    private var mPartTimeMeFragment: Fragment? = null
    private var mCurPosition = 0  //当前Fragment选中的索引
    private var mClickPage = 0  //当前Fragment选中的索引

    companion object {
        fun startInstance() {
            commContext().gotoActivity<PartTimeMainActivity>()
        }
    }

    override fun getDataBindingConfig(): DataBindingConfig {
        return DataBindingConfig(R.layout.activity_part_time_main, BR.viewModel, mViewModel)
            .addBindingParams(BR.click, ClickProxy())
    }

    override fun init(savedInstanceState: Bundle?) {
        //沉浸式状态栏
        StatusBarUtils.immersive(this)

        if (savedInstanceState == null) {
            initFragment()
            //第一次初始化首页默认显示第一个fragment
            switchFragment(mCurPosition)
        } else {
            // Activity因为内存不足的时候，这里进行Fragment恢复
            restoreFragmentInstance(savedInstanceState)
            // 因为内存原因Activity退到后天被kill，再打开的时候，会重新走onCreate
            // 这时候恢复的Fragment默认恢复第一个
            // 实际中这里可以根据需求进行修改
            switchFragment(mCurPosition)
        }
    }

    override fun startObserve() {
        //收到消息-回到第一个Tab
        LiveEventBus.get<Boolean>(YYConstants.ENENT_PART_TIME_BACK).observe(this) {
            mClickPage = 0
            switchFragment(0)
        }
    }

    override fun needRegistNetworkChangeObserver(): Boolean = true

    override fun onNetworkConnectionChanged(isConnected: Boolean, networkType: NetWorkUtil.NetworkType?) {
        if (isConnected) {
            when (mCurPosition) {
                0 -> {
                    mPartTimeHomeFragment?.let {
                        if (it is IFragmentRefresh) (it as IFragmentRefresh).scrollTopRefresh()
                    }
                }
                1 -> {
                    mPartTimeActiveFragment?.let {
                        if (it is IFragmentRefresh) (it as IFragmentRefresh).scrollTopRefresh()
                    }
                }
                2 -> {
                    mPartTimeWalletFragment?.let {
                        if (it is IFragmentRefresh) (it as IFragmentRefresh).scrollTopRefresh()
                    }
                }
                3 -> {
                    mPartTimeTrainFragment?.let {
                        if (it is IFragmentRefresh) (it as IFragmentRefresh).scrollTopRefresh()
                    }
                }
                4 -> {
                    mPartTimeMeFragment?.let {
                        if (it is IFragmentRefresh) (it as IFragmentRefresh).scrollTopRefresh()
                    }
                }
            }
        }
    }

    // ============================  Fragment begin ↓  =============================

    //切换索引
    fun switchFragment(index: Int) {
        val targetFragment: Fragment?
        val targetTag = index.toString()

        when (index) {
            0 -> {
                targetFragment = mPartTimeHomeFragment
            }
            1 -> {
                targetFragment = mPartTimeActiveFragment
            }
            2 -> {
                targetFragment = mPartTimeWalletFragment
            }
            3 -> {
                targetFragment = mPartTimeTrainFragment
            }
            4 -> {
                targetFragment = mPartTimeMeFragment
            }
            else -> {
                targetFragment = null
            }
        }

        if (null == targetFragment) {
            return
        }

        val transaction: FragmentTransaction = supportFragmentManager.beginTransaction()
        // 先隐藏掉所有的Fragment
        hideFragment(transaction)

        // 在 show 操作
        if (!targetFragment.isAdded) {
            transaction.add(R.id.main_fragment_container, targetFragment, targetTag)
            transaction.show(targetFragment)
            transaction.commit()
        } else {
            transaction.show(targetFragment).commit()
        }

        mCurPosition = index

        setBottomSelected(index)
        setupStatusBarColor()
    }

    //设置或重置状态栏颜色
    private fun setupStatusBarColor() {
        //只有Profile页面变白色
        when (mCurPosition) {
            1, 2, 4 -> setStatusBarWhiteText()
            else -> setStatusBarBlackText()
        }
    }

    // 隐藏 fragment
    private fun hideFragment(transaction: FragmentTransaction) {
        mPartTimeHomeFragment?.let {
            transaction.hide(it)
        }
        mPartTimeActiveFragment?.let {
            transaction.hide(it)
        }
        mPartTimeWalletFragment?.let {
            transaction.hide(it)
        }
        mPartTimeTrainFragment?.let {
            transaction.hide(it)
        }
        mPartTimeMeFragment?.let {
            transaction.hide(it)
        }
    }

    //底部Tab的选中效果
    private fun setBottomSelected(position: Int) {

        //传递进来的Position设置为选中：
        when (position) {
            0 -> {
                mBinding.llTabHome.isSelected = true
                mBinding.llTabActive.isSelected = false
                mBinding.llTabWallet.isSelected = false
                mBinding.llTabTrain.isSelected = false
                mBinding.llTabMe.isSelected = false
            }
            1 -> {
                mBinding.llTabHome.isSelected = false
                mBinding.llTabActive.isSelected = true
                mBinding.llTabWallet.isSelected = false
                mBinding.llTabTrain.isSelected = false
                mBinding.llTabMe.isSelected = false
            }
            2 -> {
                mBinding.llTabHome.isSelected = false
                mBinding.llTabActive.isSelected = false
                mBinding.llTabWallet.isSelected = true
                mBinding.llTabTrain.isSelected = false
                mBinding.llTabMe.isSelected = false
            }
            3 -> {
                mBinding.llTabHome.isSelected = false
                mBinding.llTabActive.isSelected = false
                mBinding.llTabWallet.isSelected = false
                mBinding.llTabTrain.isSelected = true
                mBinding.llTabMe.isSelected = false
            }
            4 -> {
                mBinding.llTabHome.isSelected = false
                mBinding.llTabActive.isSelected = false
                mBinding.llTabWallet.isSelected = false
                mBinding.llTabTrain.isSelected = false
                mBinding.llTabMe.isSelected = true
            }
        }
    }

    /**
     * 初始化Fragment
     */
    private fun initFragment() {
        // 正常情况下初始化
        mPartTimeHomeFragment = PartTimeHomeFragment()
        mPartTimeActiveFragment = PartTimeActivesFragment()
        mPartTimeWalletFragment = YYRouterService.eWalletComponentServer?.obtainEWalletMainFragment(true)
        mPartTimeTrainFragment = PartTimeTrainFragment()
        mPartTimeMeFragment = PartTimeProfileFragment()
    }

    // activity的销毁标识
    private var isHomeActDestroy = false
    private val EXTRA_SAVE_INDEX = "SaveIndex"
    private val EXTRA_IS_HOME_ACT_DESTROY = "isHomeActDestroy"

    //恢复Fragment
    private fun restoreFragmentInstance(savedInstanceState: Bundle?) {
        if (savedInstanceState != null) {
            mCurPosition = savedInstanceState.getInt(EXTRA_SAVE_INDEX, 0)
            isHomeActDestroy = savedInstanceState.getBoolean(EXTRA_IS_HOME_ACT_DESTROY, false)

            val manager: FragmentManager = supportFragmentManager
            val f0 = manager.findFragmentByTag("0")
            val f1 = manager.findFragmentByTag("1")
            val f2 = manager.findFragmentByTag("2")
            val f3 = manager.findFragmentByTag("3")
            val f4 = manager.findFragmentByTag("4")

            // 复用
            mPartTimeHomeFragment = f0 ?: PartTimeHomeFragment()
            mPartTimeActiveFragment = f1 ?: PartTimeActivesFragment()
            mPartTimeWalletFragment = f2 ?: YYRouterService.eWalletComponentServer?.obtainEWalletMainFragment(true)
            mPartTimeTrainFragment = f3 ?: PartTimeTrainFragment()
            mPartTimeMeFragment = f4 ?: PartTimeProfileFragment()
        }
    }

    override fun onSaveInstanceState(outState: Bundle) {
        hideFragment(supportFragmentManager.beginTransaction())
        outState.putInt(EXTRA_SAVE_INDEX, mCurPosition)
        outState.putBoolean(EXTRA_IS_HOME_ACT_DESTROY, true)
        super.onSaveInstanceState(outState)
    }

    // ============================  Fragment end ↑  =============================

    /**
     * DataBinding事件处理
     */
    inner class ClickProxy {

        fun switchHome() {
            mClickPage = 0
            if (mClickPage == mCurPosition) {
                //重复点击
                mPartTimeHomeFragment?.let {
                    if (it is IFragmentRefresh) (it as IFragmentRefresh).scrollTopRefresh()
                }
            } else {
                switchFragment(0)
            }
        }

        fun switchActive() {
            mClickPage = 1
            if (mClickPage == mCurPosition) {
                //重复点击
                mPartTimeActiveFragment?.let {
                    if (it is IFragmentRefresh) (it as IFragmentRefresh).scrollTopRefresh()
                }
            } else {
                switchFragment(1)
            }
        }

        fun switchEWallet() {
            mClickPage = 2
            if (mClickPage == mCurPosition) {
                //重复点击
                mPartTimeWalletFragment?.let {
                    if (it is IFragmentRefresh) (it as IFragmentRefresh).scrollTopRefresh()
                }
            } else {
                switchFragment(2)
            }
        }

        fun switchTrain() {
            mClickPage = 3
            if (mClickPage == mCurPosition) {
                //重复点击
                mPartTimeTrainFragment?.let {
                    if (it is IFragmentRefresh) (it as IFragmentRefresh).scrollTopRefresh()
                }
            } else {
                switchFragment(3)
            }
        }

        //切换Me页面Tab
        fun switchMe() {
            mClickPage = 4
            if (mClickPage == mCurPosition) {
                //重复点击
                mPartTimeMeFragment?.let {
                    if (it is IFragmentRefresh) (it as IFragmentRefresh).scrollTopRefresh()
                }
            } else {
                switchFragment(4)
            }
        }

    }
}