package com.swago.baseswago.dialog

import android.os.Bundle
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.FragmentManager
import androidx.viewbinding.ViewBinding
import com.gyf.immersionbar.ImmersionBar
import com.swago.baseswago.R
import java.lang.reflect.ParameterizedType

/**
 *@date 2021/8/27 17:00
 *description:
 */
abstract class BaseDFragment<T : ViewBinding> : DialogFragment() {

    private var _binding: T? = null
    val binding get() = _binding!!

    private var mAmount = 0.5f
    private var gravity = Gravity.CENTER
    private var canCancel = true
    private var mHeight = ViewGroup.LayoutParams.WRAP_CONTENT

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setStyle(STYLE_NORMAL, R.style.cusDialogStyle)
    }

    override fun onStart() {
        super.onStart()
        //设置宽度
        val attrs = dialog?.window?.attributes
        attrs?.width = ViewGroup.LayoutParams.MATCH_PARENT
        attrs?.height = mHeight
        dialog?.window?.attributes = attrs
        dialog?.window?.setGravity(gravity)
        dialog?.window?.setDimAmount(mAmount)
        dialog?.setCanceledOnTouchOutside(canCancel)
    }

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

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        ImmersionBar.with(this).init()
    }

    fun setGravity(gravity: Int){
        this.gravity = gravity
    }

    fun setDimAmount(amount: Float) {
        mAmount = amount
    }

    fun setCanCancel(canCancel:Boolean){
        this.canCancel = canCancel
    }

    fun setHeightMatchParent(){
        mHeight = ViewGroup.LayoutParams.MATCH_PARENT
    }

    @Suppress("UNCHECKED_CAST")
    fun getViewBindingForFragment(layoutInflater: LayoutInflater, container: ViewGroup?): T {
        val type = javaClass.genericSuperclass as ParameterizedType
        val aClass = type.actualTypeArguments[0] as Class<*>
        val method = aClass.getDeclaredMethod("inflate", LayoutInflater::class.java)
        return method.invoke(null, layoutInflater) as T
    }

    override fun show(manager: FragmentManager, tag: String?) {
        try {
            //在每个add事务前增加一个remove事务，防止连续的add
            manager.beginTransaction().remove(this).commit()
            super.show(manager,tag)
        } catch (e: Exception) {
            //同一实例使用不同的tag会异常，这里捕获一下
            e.printStackTrace()
        }
    }



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