package com.yidian.shenghuoquan.buserorder.ui.widget

import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.LifecycleOwner
import com.yidian.bcommon.constant.XEventConfig
import com.yidian.shenghuoquan.buserorder.R
import com.yidian.shenghuoquan.buserorder.databinding.BorderViewPickupPointSearchBinding
import com.yidian.shenghuoquan.buserorder.viewmodel.PickupPointSearchViewModel
import com.yidian.xarc.xevent.XBaseEvent
import com.yidian.xarc.xevent.XEventManager

/**
 * author: yinjiacheng
 * date: 2021/8/24 15:07
 * description: 自提点搜索框
 */
class PickupPointSearchView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyle: Int = 0) :
  ConstraintLayout(context, attrs, defStyle) {

  private val binding = DataBindingUtil.inflate<BorderViewPickupPointSearchBinding>(
    LayoutInflater.from(getContext()),
    R.layout.border_view_pickup_point_search,
    this,
    true
  )
  private val vm by lazy { PickupPointSearchViewModel() }

  init {
    binding.vm = vm
    registerUIEvent()
    initView()
  }

  private fun initView() {
    binding.etSearch.setOnEditorActionListener { v, actionId, _ ->
      if (actionId == EditorInfo.IME_ACTION_SEARCH) {
        // 隐藏软键盘
        val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.hideSoftInputFromWindow(windowToken, 0)
        // 通知开始搜索
        XEventManager.post(XBaseEvent(XEventConfig.SEARCH_PICKUP_POINT_START, v.text.toString()))
      }
      true
    }
  }

  /**
   * 注册UI事件监听
   */
  private fun registerUIEvent() {
    vm.clearSearch.observe(context as LifecycleOwner, {
      // 清空搜索框
      binding.etSearch.setText("")
      // 通知取消搜索
      XEventManager.post(XBaseEvent(XEventConfig.SEARCH_PICKUP_POINT_CANCEL, null))
    })
  }
}
