package com.yidian.shenghuoquan.bgoods.ui.coupon

import android.view.KeyEvent
import androidx.activity.viewModels
import androidx.core.view.isVisible
import com.yidian.bcommon.XEventConfig
import com.yidian.bcommon.extensions.initTitleBar
import com.yidian.bcommon.mvvm.BaseMvvmActivity
import com.yidian.shenghuoquan.bgoods.R
import com.yidian.shenghuoquan.bgoods.databinding.CommodityActivityCategorySearchBinding
import com.yidian.shenghuoquan.bgoods.dto.SelectCategoryDto
import com.yidian.shenghuoquan.bgoods.ui.coupon.adapter.CategorySearchListAdapter
import com.yidian.xarc.xevent.XBaseEvent
import com.yidian.xarc.xevent.XEventManager

/**
 * 搜索类目
 */
class CategorySearchActivity : BaseMvvmActivity<CommodityActivityCategorySearchBinding, CategorySearchViewModel>() {

  private val adapter = CategorySearchListAdapter()

  override val layoutId: Int = R.layout.commodity_activity_category_search

  override val vm: CategorySearchViewModel by viewModels()

  override fun initView() {
    initTitleBar(binding.include.toolbar, binding.include.tvTitle, "选择类目")
    setupRecyclerView()
    subscribeUiEvent()
    initClick()
  }

  private fun initClick() {
    binding.etSearchKeyword.setOnKeyListener { _, keyCode, event ->
      if (event.action == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER) {
        vm.toSearch()
      }
      false
    }
  }

  private fun setupRecyclerView() {
    binding.rvCategoryList.adapter = adapter
    adapter.setOnItemClickListener { adapter, _, position ->
      val selectCategoryDto = adapter.getItem(position) as SelectCategoryDto
      // 关闭选择类目页面
      XEventManager.post(XBaseEvent(XEventConfig.CHOOSE_CATEGORY_SUCCESS, selectCategoryDto))
      finish()
    }
  }

  private fun subscribeUiEvent() {
    vm.sendKeywordEvent.observe(this, {
      adapter.setKeyword(it)
    })
    vm.searchSuccessEvent.observe(this, {
      if (it.isNullOrEmpty()) {
        binding.rvCategoryList.isVisible = false
        binding.pvEmptyPage.isVisible = true
        adapter.setList(null)
      } else {
        binding.rvCategoryList.isVisible = true
        binding.pvEmptyPage.isVisible = false
        adapter.setList(it)
      }
    })
    vm.clearEditEvent.observe(this, {
      binding.etSearchKeyword.setText("")
      binding.rvCategoryList.isVisible = false
      adapter.setList(null)
    })
  }

}
