package com.example.base.ui

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.viewbinding.ViewBinding
import com.example.base.viewmodel.BaseViewModel
import java.lang.reflect.ParameterizedType

abstract class VBFragment<VB : ViewBinding, VM : BaseViewModel> : VMFragment<VM>() {

    private var _binding: VB? = null

    val binding get() = _binding!!

    override fun onCreateView(li: LayoutInflater, c: ViewGroup?, sis: Bundle?): View? {
        _binding = initVB()

        return binding.root
    }

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

        initView()

        initListener()

        initData()
    }

    @Suppress("UNCHECKED_CAST")
    private fun initVB(): VB {
        // 获取泛型的真实class
        val types = javaClass.genericSuperclass as ParameterizedType

        val type = types.actualTypeArguments.find {
            val clazz = it as Class<*>
            ViewBinding::class.java.isAssignableFrom(clazz)
        } ?: RuntimeException("子页面没有传入ViewBinding的泛型")

        val tClass = type as Class<VB>

        val method = tClass.getMethod("inflate", LayoutInflater::class.java)
        return method.invoke(null, layoutInflater) as VB
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

    // init View
    open fun initView() {}

    // init view的相关事件
    open fun initListener() {}

    // init Data
    open fun initData() {}
}

