package zs.qimai.com.dialog

import android.app.Activity
import android.content.DialogInterface
import android.content.Intent
import android.graphics.Point
import android.os.Build
import android.os.Bundle
import android.util.DisplayMetrics
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.fragment.app.FragmentManager

class QmDialogFragment : BaseDialogFragment() {
    var dialogController: DialogController = DialogController()

    var mDialogTheme = R.style.QmDialogTheme
    override fun getLayoutId() = dialogController.layoutResId

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setStyle(STYLE_NO_TITLE, mDialogTheme)
    }

    override fun onDismiss(dialog: DialogInterface) {
        dialogController.dismissListener?.onDismiss(dialog)
        this.dialog?.setOnShowListener(null)
        this.dialog?.setOnCancelListener(null)
        this.dialog?.setOnDismissListener(null)
        dialogController.mDismissListenerList.forEach {
            it.onDismiss(dialog)
        }
        super.onDismiss(dialog)
    }

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

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val view = super.onCreateView(inflater, container, savedInstanceState)
        dialogController.onViewInflateFinish?.onViewInflate(view, this)
        dialog?.setCanceledOnTouchOutside(dialogController.canceledOnTouchOutside)
        isCancelable = dialogController.cancelable
        return view
    }

    override fun bindView(v: View) {
        //设置取消，确认按钮监听事件
        getDialogChildView<View>(R.id.tv_cancel, v)
            ?.setOnClickListener {
                dialogController.negative(it, this)
                dismiss()
            }

        getDialogChildView<View>(R.id.tv_ok, v)?.setOnClickListener {
            dialogController.positive(it, this)
            dismiss()
        }
    }


    private fun <T : View> getDialogChildView(id: Int, v: View): T? {
        val childView: View? = v.findViewById<T>(id)
        return childView as? T
    }

    override fun getGravity(): Int {
        return dialogController.gravity
    }

    override fun getDialogWidth(): Int {
        return dialogController.width
    }

    override fun getDialogHeight(): Int {
        return dialogController.height
    }

    open class Builder private constructor(private var fragmentManager: FragmentManager) {
        constructor(fragmentActivity: FragmentActivity) : this(fragmentActivity.supportFragmentManager)
        constructor(fragment: Fragment) : this(fragment.childFragmentManager)

        private var params: DialogController.Params = DialogController.Params()

        //控件名称改变
        private var paramsMap: MutableMap<Int, String>? = null
        var mDialogTheme = R.style.QmDialogTheme

        init {

            params.fragmentManager = this.fragmentManager
        }

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

        @Deprecated("使用addDismissListener()")
        fun setOnDismissListener(listener: DialogInterface.OnDismissListener): Builder {
            params.dismissListener = listener
            return this
        }

        fun setOnViewInflateListener(listener: OnViewInflateFinish): Builder {
            params.onViewInflateFinish = listener
            return this
        }

        fun setOnActivityResultListener(listener: OnActivityResultListener): Builder {
            params.onActivityResultListener = listener
            return this
        }

        fun setWidth(width: Int): Builder {
            params.width = width
            return this
        }

        fun setWidthPercentage(activity: Activity, percentage: Float): Builder {
            val width = getRootWidth(activity)
            params.width = ((width * percentage).toInt())
            return this
        }

        fun setHeight(height: Int): Builder {
            params.height = height
            return this
        }

        fun setLayoutRes(layout: Int): Builder {
            params.layoutResId = layout
            return this
        }

        fun create(): QmDialogFragment {
            val qmDialogFragment = QmDialogFragment()
            params.apply(qmDialogFragment.dialogController)
            return qmDialogFragment
        }

        fun setItemViewClick(onViewClickListener: OnViewClickListener): Builder {
            params.onViewClickListener = onViewClickListener
            return this
        }

        fun withPositive(positive: (View, DialogFragment) -> Unit): Builder {
            params.positive = positive
            return this
        }

        fun withNegative(negative: (View, DialogFragment) -> Unit): Builder {
            params.negative = negative
            return this
        }

        fun setText(id: Int, text: String): Builder {
            if (paramsMap == null) {
                paramsMap = mutableMapOf()
            }
            //paramsMap!!.put(id,text)
            return this
        }

        fun setContext(text: String): Builder {
            if (paramsMap == null) {
                paramsMap = mutableMapOf()
            }
            return this
        }

        fun setTitle(text: String): Builder {
            if (paramsMap == null) {
                paramsMap = mutableMapOf()
            }
            return this
        }

        fun setDialogDismiss(dismissListener: DialogInterface.OnDismissListener): Builder {
            params.dismissListener = dismissListener
            return this
        }

        fun setCancelable(status: Boolean): Builder {
            params.Cancelable = status
            return this
        }

        fun setCanceledOnTouchOutside(status: Boolean): Builder {
            params.canceledOnTouchOutside = status
            return this
        }

        fun addDismissListener(dialogDismissListener: OnDialogDismissListener): Builder {
            params.mDismissListenerList.add(dialogDismissListener)
            return this
        }

        protected fun getRootWidth(activity: Activity): Int {
            var displayWidth = 0
            val display = activity.windowManager.defaultDisplay
            val point = Point()
            displayWidth = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                display.getRealSize(point)
                point.x
            } else {
                val dm = DisplayMetrics()
                activity.windowManager.defaultDisplay.getMetrics(dm)
                dm.widthPixels
            }
            return displayWidth
        }
/*
        protected fun getRootHeight(): Int {
            var displayHeight = 0
            val display = activity!!.windowManager.defaultDisplay
            val point = Point()
            displayHeight = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                display.getRealSize(point)
                point.y
            } else {
                val dm = DisplayMetrics()
                activity!!.windowManager.defaultDisplay.getMetrics(dm)
                dm.heightPixels
            }
            return displayHeight
        }*/
    }

    fun show(tag: String = "default"): QmDialogFragment {
        dialogController.fragmentManager.beginTransaction()
            .add(this, tag)
            .commitAllowingStateLoss()
        //   show(fragmentManager)
        return this
    }

    override fun onCancel(dialog: DialogInterface) {
        super.onCancel(dialog)
        this.dialog?.setOnShowListener(null)
        this.dialog?.setOnCancelListener(null)
        this.dialog?.setOnDismissListener(null)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        dialog?.setOnShowListener(null)
        dialog?.setOnCancelListener(null)
        dialog?.setOnDismissListener(null)
        if (dialog != null && dialog!!.isShowing()) {
            dialog!!.dismiss()
        }
    }
    /*var canceledOnTouchOutside = true
    var cancelable = true*/


    interface OnViewInflateFinish {
        fun onViewInflate(view: View?, dialog: QmDialogFragment)
    }

    interface OnActivityResultListener {
        fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        dialogController.onActivityResultListener?.onActivityResult(requestCode, resultCode, data)
    }


    companion object {


    }

}