@file:Suppress("unused")

package com.base.appzxhy.base

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.viewbinding.ViewBinding

/**
 *
 * @param VB : ViewBinding
 * 基本的fragment绑定数据
 */
abstract class BaseFragment<VB : ViewBinding>(
    private val bindingInflater: (LayoutInflater, ViewGroup?, Boolean) -> VB
) : Fragment() {
    private var _binding: VB? = null
    private var fragmentInit = false
    open val TAG = javaClass.simpleName

    //重写binding get()方法不直接暴露真实的可空_binding数据
    @Suppress("MemberVisibilityCanBePrivate")
    val binding: VB
        get() = _binding!!

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = bindingInflater.invoke(inflater, container, false)
        return binding.root
    }

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

    protected open fun initView() {}

    protected open fun initListener() {}

    open fun onResumeOneShoot() = Unit

    override fun onResume() {
        if (!fragmentInit) {
            onResumeOneShoot()
            fragmentInit = true
        }
        super.onResume()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        //要手动置null防止内存泄漏
        _binding = null
    }
}

inline fun <VB : ViewBinding> BaseFragment<VB>.viewBind(block: VB.() -> Unit) {
    binding.apply(block)
}

inline fun Fragment.goToAc(clazz: Class<out Activity>, block: (Intent.() -> Unit) = {}) {
    context?.startActivity(Intent(context, clazz).apply(block))
}
