package com.hongyegroup.cpt_pensonal.ui.activity

import android.annotation.SuppressLint
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.guadou.cs_cptservices.base.activity.YYBaseVDBActivity
import com.guadou.lib_baselib.base.vm.EmptyViewModel
import com.guadou.lib_baselib.bean.DataBindingConfig
import com.guadou.lib_baselib.utils.CommUtils
import com.hongyegroup.cpt_pensonal.BR
import com.hongyegroup.cpt_pensonal.R
import com.hongyegroup.cpt_pensonal.databinding.ActivityPensonalMainBinding
import com.hongyegroup.cpt_pensonal.ui.fragment.PensonalCompanyInfoFragment
import com.hongyegroup.cpt_pensonal.ui.fragment.PensonalMeFragment
import com.hongyegroup.cpt_pensonal.ui.fragment.PensonalMyAppointmentFragment
import com.hongyegroup.cpt_pensonal.ui.fragment.PensonalSettingFragment

/**
 * 个人用户的首页 底部4Tab+Fragment
 */
class PensonalMainActivity : YYBaseVDBActivity<EmptyViewModel, ActivityPensonalMainBinding>() {

    //首页的4个TabFragment
    private var mCompanyFragment: PensonalCompanyInfoFragment? = null
    private var mAppointmentFragment: PensonalMyAppointmentFragment? = null
    private var mMeFragment: PensonalMeFragment? = null
    private var mSettingFragment: PensonalSettingFragment? = null

    private var mCurPosition = 0  //当前Fragment选中的索引
    private var mClickPage = 0  //当前Fragment选中的索引

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

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

    override fun startObserve() {

    }

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

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

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

        when (index) {
            0 -> {
                targetFragment = mCompanyFragment
            }
            1 -> {
                targetFragment = mAppointmentFragment
            }
            2 -> {
                targetFragment = mMeFragment
            }
            3 -> {
                targetFragment = mSettingFragment
            }
            else -> {
                targetFragment = null
            }

        }

        if (null == targetFragment) {
            return
        }

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

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

        mCurPosition = index

        setBottomSelected(index)

    }


    // 隐藏 fragment
    private fun hideFragment(transaction: FragmentTransaction) {
        mCompanyFragment?.let {
            transaction.hide(it)
        }
        mAppointmentFragment?.let {
            transaction.hide(it)
        }
        mMeFragment?.let {
            transaction.hide(it)
        }
        mSettingFragment?.let {
            transaction.hide(it)
        }
    }

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

        //传递进来的Position设置为选中：
        when (position) {
            0 -> {
                mBinding.tabCompany.isSelected = true
                mBinding.tabAppointment.isSelected = false
                mBinding.tabMe.isSelected = false
                mBinding.tabSetting.isSelected = false
            }
            1 -> {
                mBinding.tabCompany.isSelected = false
                mBinding.tabAppointment.isSelected = true
                mBinding.tabMe.isSelected = false
                mBinding.tabSetting.isSelected = false
            }
            2 -> {
                mBinding.tabCompany.isSelected = false
                mBinding.tabAppointment.isSelected = false
                mBinding.tabMe.isSelected = true
                mBinding.tabSetting.isSelected = false
            }
            else -> {
                mBinding.tabCompany.isSelected = false
                mBinding.tabAppointment.isSelected = false
                mBinding.tabMe.isSelected = false
                mBinding.tabSetting.isSelected = true
            }
        }
    }

    /**
     * 初始化Fragment
     */
    private fun initFragment() {

        // 正常情况下初始化
        mCompanyFragment = PensonalCompanyInfoFragment()
        mAppointmentFragment = PensonalMyAppointmentFragment()
        mMeFragment = PensonalMeFragment()
        mSettingFragment = PensonalSettingFragment()

        //第一次显示，选中第一个
        switchFragment(mCurPosition)

    }

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

            // 复用
            mCompanyFragment = if (f0 != null) {
                f0 as PensonalCompanyInfoFragment
            } else {
                PensonalCompanyInfoFragment()
            }

            mAppointmentFragment = if (f1 != null) {
                f1 as PensonalMyAppointmentFragment
            } else {
                PensonalMyAppointmentFragment()
            }

            mMeFragment = if (f2 != null) {
                f2 as PensonalMeFragment
            } else {
                PensonalMeFragment()
            }

            mSettingFragment = if (f3 != null) {
                f3 as PensonalSettingFragment
            } else {
                PensonalSettingFragment()
            }
        }
    }

    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 switchCompany() {
            mClickPage = 0
            if (mClickPage == mCurPosition) {
                //重复点击
                mCompanyFragment?.run {
                    scrollTopRefresh()
                }
            } else {
                switchFragment(0)
            }
        }

        fun switchAppointment() {
            mClickPage = 1
            if (mClickPage == mCurPosition) {
                //重复点击
                mAppointmentFragment?.run {
                    scrollTopRefresh()
                }
            } else {
                switchFragment(1)
            }
        }

        fun switchMe() {
            mClickPage = 2
            if (mClickPage == mCurPosition) {
                //重复点击
                mMeFragment?.run {
                    scrollTopRefresh()
                }
            } else {
                switchFragment(2)
            }
        }

        fun switchSetting() {
            mClickPage = 3
            if (mClickPage == mCurPosition) {
                //重复点击
                mSettingFragment?.run {
                    scrollTopRefresh()
                }
            } else {
                switchFragment(3)
            }
        }

    }
}