@file:Suppress("unused")

package com.base.scanqrclear.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
import com.base.scanqrclear.utils.LogEx
import kotlin.random.Random

/**
 *
 * @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
    private val tagNo = Random.nextInt(500)

    //重写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
    }

    private var onViewCreatedI = 0
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initView()
        initListener()
        onViewCreatedI++
        LogEx.logDebug(TAG, "lifecycle $tagNo onViewCreated ${javaClass.simpleName} $onViewCreatedI")
    }

    protected open fun initView() {}

    protected open fun initListener() {}

    open fun onResumeOneShoot() = Unit

    private var onResumeOneShootI = 0
    override fun onResume() {
        if (!fragmentInit) {
            onResumeOneShoot()
            onResumeOneShootI++
            LogEx.logDebug(TAG, "lifecycle $tagNo onResumeOneShoot ${javaClass.simpleName} $onResumeOneShootI")
            fragmentInit = true
        }
        super.onResume()
    }

    private var onDestroyViewI = 0
    override fun onDestroyView() {
        super.onDestroyView()
        //要手动置null防止内存泄漏
        _binding = null
        onDestroyViewI++
        LogEx.logDebug(TAG, "lifecycle $tagNo onDestroyView ${javaClass.simpleName} $onDestroyViewI")

    }
    private var onStopI = 0
    override fun onStop() {
        super.onStop()
        onStopI++
        LogEx.logDebug(TAG, "lifecycle $tagNo onStop ${javaClass.simpleName} $onStopI")
        fragmentInit = false
    }

    private var onDestroyI = 0
    override fun onDestroy() {
        super.onDestroy()
        onDestroyI++
        LogEx.logDebug(TAG, "lifecycle $tagNo onDestroy ${javaClass.simpleName} $onDestroyI")
    }
}

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))
}
