package com.yidianling.common.view.popupwindow

import android.app.Activity
import android.view.Gravity
import android.view.MotionEvent
import android.view.View
import android.view.Window
import android.widget.PopupWindow

/**
 * @author jiucheng
 * @描述:PopupWindow基类，后续PopupWindow可统一继承
 * @Copyright Copyright (c) 2018
 * @Company 壹点灵
 * @date 2018/8/9
 */
open class BasePopupWindow : View.OnTouchListener, PopupWindow.OnDismissListener {
    protected var popupWindow: PopupWindow? = null
    protected var mContext: Activity? = null
    protected var mView: View? = null
    protected var window: Window? = null

    constructor(mContext: Activity) {
        this.mContext = mContext
        popupWindow = PopupWindow(mContext)
        window = mContext.window
    }

    open fun initPopupwindow() {
        //设置点击空白处消失
        popupWindow!!.isTouchable = true
        popupWindow!!.setTouchInterceptor(this)
        popupWindow!!.isOutsideTouchable = true
        popupWindow!!.isFocusable = true
        popupWindow!!.setOnDismissListener(this)
    }


    override fun onDismiss() {
        val params = window!!.getAttributes()
        params.alpha = 1f
        window!!.setAttributes(params)
    }

    override fun onTouch(v: View?, event: MotionEvent?): Boolean {
        if (event != null) {
            if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
                dismiss()
                return true
            }
        }
        return false
    }


    open fun dismiss() {
        if (popupWindow != null)
            popupWindow!!.dismiss()

        val params = window!!.attributes
        params.alpha = 1f
        window!!.attributes = params
    }


    open fun showAtLocation(parent: View, gravity: Int, x: Int, y: Int) {
        val params = window!!.attributes
        params.alpha = 0.5f
        window!!.attributes = params

        if (popupWindow != null) {
            popupWindow!!.showAtLocation(parent, gravity, x, y)
        }
    }

    open fun showAsDropDown(anchor: View, xoff: Int, yoff: Int) {
        val params = window!!.attributes
        params.alpha = 0.5f
        window!!.attributes = params
        if (popupWindow != null) {
            popupWindow!!.showAsDropDown(anchor, xoff, yoff)
        }
    }


    /**
     * 在底部显示
     */
    open fun showBottom(v: View) {
        showAtLocation(v, Gravity.BOTTOM, 0, 0)
    }
}