package com.hongyegroup.cpt_main.ui

import android.content.Intent
import android.os.Bundle
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentTransaction
import com.alibaba.android.arouter.facade.annotation.Route
import com.guadou.cs_cptservices.base.activity.YYBaseVDBActivity
import com.guadou.cs_cptservices.interfaces.IFragmentRefresh
import com.guadou.cs_router.ARouterPath
import com.guadou.cs_router.YYRouterService
import com.guadou.lib_baselib.bean.DataBindingConfig
import com.guadou.lib_baselib.utils.CommUtils
import com.guadou.lib_baselib.utils.NetWorkUtil
import com.guadou.lib_baselib.utils.StatusBarUtils
import com.hongyegroup.cpt_main.BR
import com.hongyegroup.cpt_main.R
import com.hongyegroup.cpt_main.databinding.ActivityMainBinding
import com.hongyegroup.cpt_main.mvvm.MainViewModel
import dagger.hilt.android.AndroidEntryPoint

/**
 * 首页Tab+Fragment
 */
@Route(path = ARouterPath.PATH_MAIN_PAGE_MAIN)
@AndroidEntryPoint
class MainActivity : YYBaseVDBActivity<MainViewModel, ActivityMainBinding>() {

    //首页的5个TabFragment
    private var mHomeFragment: Fragment? = null
    private var mPartTimeFragment: Fragment? = null
    private var mActivesFragment: Fragment? = null
    private var mEWalletFragment: Fragment? = null
    private var mProfileFragment: Fragment? = null
    private var mCurPosition = 0  //当前Fragment选中的索引
    private var mClickPage = 0  //当前Fragment选中的索引

    companion object {
        fun startInstance() {
            val context = CommUtils.getContext()
            val intent = Intent(context, MainActivity::class.java)
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            context.startActivity(intent)
        }
    }

    override fun getDataBindingConfig(): DataBindingConfig {
        return DataBindingConfig(R.layout.activity_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() {

    }

    override fun needRegistNetworkChangeObserver(): Boolean = true

    override fun onNetworkConnectionChanged(isConnected: Boolean, networkType: NetWorkUtil.NetworkType?) {
        if (isConnected) {
            when (mCurPosition) {
                0 -> {
                    mHomeFragment?.let {
                        if (it is IFragmentRefresh) (it as IFragmentRefresh).scrollTopRefresh()
                    }
                }
                1 -> {
                    mPartTimeFragment?.let {
                        if (it is IFragmentRefresh) (it as IFragmentRefresh).scrollTopRefresh()
                    }
                }
                2 -> {
                    mActivesFragment?.let {
                        if (it is IFragmentRefresh) (it as IFragmentRefresh).scrollTopRefresh()
                    }
                }
                3 -> {
                    mEWalletFragment?.let {
                        if (it is IFragmentRefresh) (it as IFragmentRefresh).scrollTopRefresh()
                    }
                }
                4 -> {
                    mProfileFragment?.let {
                        if (it is IFragmentRefresh) (it as IFragmentRefresh).scrollTopRefresh()
                    }
                }
            }
        }
    }

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

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

        when (index) {
            0 -> {
                targetFragment = mHomeFragment
            }
            1 -> {
                targetFragment = mPartTimeFragment
            }
            2 -> {
                targetFragment = mActivesFragment
            }
            3 -> {
                targetFragment = mEWalletFragment
            }
            4 -> {
                targetFragment = mProfileFragment
            }
            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) {
            2, 3, 4 -> setStatusBarWhiteText()
            else -> setStatusBarBlackText()
        }
    }

    // 隐藏 fragment
    private fun hideFragment(transaction: FragmentTransaction) {
        mHomeFragment?.let {
            transaction.hide(it)
        }
        mPartTimeFragment?.let {
            transaction.hide(it)
        }
        mActivesFragment?.let {
            transaction.hide(it)
        }
        mEWalletFragment?.let {
            transaction.hide(it)
        }
        mProfileFragment?.let {
            transaction.hide(it)
        }
    }

    //底部Tab的选中效果
    private fun setBottomSelected(position: Int) {
        mBinding.groupTabParttime.isSelected = false

        //传递进来的Position设置为选中：
        when (position) {
            0 -> {
                mBinding.groupTabHome.isSelected = true
                mBinding.groupTabParttime.isSelected = false
                mBinding.groupTabActives.isSelected = false
                mBinding.groupTabWallet.isSelected = false
                mBinding.groupTabMe.isSelected = false
            }
            1 -> {
                mBinding.groupTabHome.isSelected = false
                mBinding.groupTabParttime.isSelected = true
                mBinding.groupTabActives.isSelected = false
                mBinding.groupTabWallet.isSelected = false
                mBinding.groupTabMe.isSelected = false
            }
            2 -> {
                mBinding.groupTabHome.isSelected = false
                mBinding.groupTabParttime.isSelected = false
                mBinding.groupTabActives.isSelected = true
                mBinding.groupTabWallet.isSelected = false
                mBinding.groupTabMe.isSelected = false
            }
            3 -> {
                mBinding.groupTabHome.isSelected = false
                mBinding.groupTabParttime.isSelected = false
                mBinding.groupTabActives.isSelected = false
                mBinding.groupTabWallet.isSelected = true
                mBinding.groupTabMe.isSelected = false
            }
            else -> {
                mBinding.groupTabHome.isSelected = false
                mBinding.groupTabParttime.isSelected = false
                mBinding.groupTabActives.isSelected = false
                mBinding.groupTabWallet.isSelected = false
                mBinding.groupTabMe.isSelected = true
            }
        }
    }

    /**
     * 初始化Fragment
     */
    private fun initFragment() {
        // 正常情况下初始化
        mHomeFragment = HomeFragment()
        mPartTimeFragment = YYRouterService.parttimeComponentServer?.obtainPartTimeMainFragment()
        mActivesFragment = YYRouterService.parttimeComponentServer?.obtainPartTimeActivesFragment()
        mEWalletFragment = YYRouterService.eWalletComponentServer?.obtainEWalletMainFragment()
        mProfileFragment = YYRouterService.parttimeComponentServer?.obtainPartTimeProfileFragment()
    }

    // 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")

            // 复用
            mHomeFragment = f0 ?: HomeFragment()
            mPartTimeFragment = f1 ?: YYRouterService.parttimeComponentServer?.obtainPartTimeMainFragment()
            mActivesFragment = f2 ?: YYRouterService.parttimeComponentServer?.obtainPartTimeActivesFragment()
            mEWalletFragment = f3 ?: YYRouterService.eWalletComponentServer?.obtainEWalletMainFragment()
            mProfileFragment = f4 ?: YYRouterService.parttimeComponentServer?.obtainPartTimeProfileFragment()
        }
    }

    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) {
                //重复点击
                mHomeFragment?.let {
                    if (it is IFragmentRefresh) (it as IFragmentRefresh).scrollTopRefresh()
                }
            } else {
                switchFragment(0)
            }
        }

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

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

        //切换消息页面Tab
        fun switchEWallet() {
            mClickPage = 3
            if (mClickPage == mCurPosition) {
                //重复点击
                mEWalletFragment?.let {
                    if (it is IFragmentRefresh) (it as IFragmentRefresh).scrollTopRefresh()
                }
            } else {
                switchFragment(3)
            }
        }

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

    }
}