package com.adealink.weparty.commonui

import android.content.Context
import android.view.MotionEvent
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import com.adealink.frame.util.hideSoftKeyboard
import com.adealink.frame.util.uiThreadHandler

/**
 * @author lee
 * 点击输入法外部，隐藏输入法，取消焦点
 */
open class BaseKeyboardActivity : BaseActivity() {
    var editText: EditText? = null

    private fun isShouldHideInput(
        v: View?,
        event: MotionEvent
    ): Boolean {
        if (v != null && v is EditText) {
            editText = v
            val leftTop = intArrayOf(0, 0)
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop)
            val left = leftTop[0]
            val top = leftTop[1]
            val bottom = top + v.getHeight()
            val right = left + v.getWidth()
            return !(event.x > left && event.x < right && event.y > top && event.y < bottom)
        }
        return false
    }

    /**
     * 设置软键盘弹出与隐藏事件（在Activity被遮盖时隐藏软键盘，点击editText外部时隐藏软键盘）
     */
    override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
        if (!isFinishing) {
            if (ev?.action == MotionEvent.ACTION_DOWN) {
                val view: View? = currentFocus
                var viewLater: View?

                uiThreadHandler.postDelayed({
                    viewLater = currentFocus
                    if (viewLater != null && viewLater is EditText && !isShouldHideInput(viewLater, ev)) {
                        return@postDelayed
                    }
                    if (isShouldHideInput(view, ev)) {
                        getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                        view?.let {
                            hideSoftKeyboard(view)//软键盘工具类
                        }
                        if (editText != null) {
                            editText?.clearFocus()
                        }
                    }
                }, 100)

            }
        }
        return super.dispatchTouchEvent(ev)
    }
}