package com.example.defenseapplication.home

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.fragment.app.Fragment
import com.example.defenseapplication.R
import com.example.defenseapplication.base.BaseActivity
import com.example.defenseapplication.databinding.HomeActivityBinding
import com.example.defenseapplication.databinding.HomeMenuFragmentBinding
import com.gyf.immersionbar.ImmersionBar

class HomeActivity : BaseActivity() {
    // ViewBinding 核心对象
    private lateinit var binding: HomeActivityBinding

    // 定义两个 Fragment
    private val homeMenuFragment = HomeMenuFragment()
    private val personalFragment = PersonalFragment()

    // 当前显示的 Fragment
    private var currentFragment: Fragment = homeMenuFragment

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // 初始化 ViewBinding
        binding = HomeActivityBinding.inflate(layoutInflater)
        setContentView(binding.root)
        // 默认显示首页
        switchFragment(homeMenuFragment)
        // 第一次加载，只 add 首页
        supportFragmentManager.beginTransaction()
            .add(R.id.fragment_container, homeMenuFragment)
            .commit()
        // ========== 首页点击 ==========
        binding.tabHome.setOnClickListener {
            switchFragment(homeMenuFragment)
            // 切换图标 + 文字颜色
            binding.ivHome.setImageResource(R.drawable.home_checked)
            binding.tvHome.setTextColor(resources.getColor(R.color.ic_selected))

            binding.ivProfile.setImageResource(R.drawable.profile)
            binding.tvProfile.setTextColor(resources.getColor(R.color.ic_normal))
        }

        // ========== 个人点击 ==========
        binding.tabProfile.setOnClickListener {
            switchFragment(personalFragment)
            // 切换图标 + 文字颜色
            binding.ivHome.setImageResource(R.drawable.home)
            binding.tvHome.setTextColor(resources.getColor(R.color.ic_normal))

            binding.ivProfile.setImageResource(R.drawable.profile_checked)
            binding.tvProfile.setTextColor(resources.getColor(R.color.ic_selected))
        }
    }

    /**
     * 切换 Fragment 的方法
     */
    private fun switchFragment(fragment: Fragment) {
        if (currentFragment == fragment) return

        val transaction = supportFragmentManager.beginTransaction()

        // 如果没添加过，才 add
        if (!fragment.isAdded) {
            transaction.add(R.id.fragment_container, fragment)
        }

        // 隐藏当前，显示目标
        transaction.hide(currentFragment)
        transaction.show(fragment)
        transaction.commit()

        currentFragment = fragment
    }
}