package com.xty.base.dialog

import android.app.Dialog
import android.content.Context
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.view.WindowMetrics
import androidx.annotation.RequiresApi

abstract class BaseDialog(context: Context,theme:Int) : Dialog(context,theme) {
    constructor(context: Context ):this(context,0)
    private lateinit var view:View

      var percentHeight=0.5f //屏幕占比

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        view=setLayout()
        setContentView(setLayout())
        initView()
    }

    abstract fun setLayout(): View

    open fun initView() {
        window?.decorView?.let {
            it.setBackgroundColor(Color.TRANSPARENT)
            it.setPadding(0, 0, 0, 0)
        }

        var arrt = window!!.attributes
        arrt.width = ViewGroup.LayoutParams.MATCH_PARENT
        window!!.attributes = arrt

        window!!.setGravity(Gravity.CENTER)


    }


    open fun setDialogPadding(l: Int = 0, t: Int = 0, r: Int = 0, b: Int = 0) {
        window?.decorView?.let {
            it.setPadding(l, t, r, b)
        }
    }

    /**
     * 使用这个方法显示dialog  可以修改dialog 在屏幕上的占比
     */
    open fun showDialog(){
        show()
        view.addOnLayoutChangeListener { v, left, top, right, bottom, oldLeft, oldTop, oldRight, oldBottom ->
            var height = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                var currentWindow = window!!.windowManager.currentWindowMetrics
                currentWindow.bounds.height()
            } else {
                var disply = window!!.decorView.display
                disply.height
            }

            var needHeight=height *percentHeight
            if (v.height > needHeight) {
                var attr= window!!.attributes
                attr.height=needHeight.toInt()
                window!!.attributes=attr
            }
        }
    }

}