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

import android.content.Intent
import androidx.activity.viewModels
import com.yidian.bcommon.constant.XEventConfig
import com.yidian.bcommon.constant.XRouterPathConstants
import com.yidian.bcommon.extensions.initTitleBar
import com.yidian.bcommon.mvvm.BaseMvvmActivity
import com.yidian.shenghuoquan.bgoods.R
import com.yidian.shenghuoquan.bgoods.databinding.CommodityActivityChooseCategoryBinding
import com.yidian.shenghuoquan.bgoods.dto.CategoryListDto
import com.yidian.shenghuoquan.bgoods.dto.SelectCategoryDto
import com.yidian.shenghuoquan.bgoods.dto.SubCategory
import com.yidian.shenghuoquan.bgoods.ui.coupon.adapter.CategoryListAdapter
import com.yidian.shenghuoquan.bgoods.ui.coupon.adapter.CategorySubListAdapter
import com.yidian.xarc.xevent.XBaseEvent
import com.yidian.xarc.xevent.XEventManager
import com.yidian.xpage.XPageViewProtocol
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode


/**
 * 商品选择类目
 */
class ChooseCategoryActivity : BaseMvvmActivity<CommodityActivityChooseCategoryBinding, ChooseCategoryViewModel>(), XPageViewProtocol {

  private lateinit var categoryList: MutableList<CategoryListDto>
  private val adapter = CategoryListAdapter()
  private val subAdapter = CategorySubListAdapter()

  override val layoutId: Int = R.layout.commodity_activity_choose_category

  override val vm: ChooseCategoryViewModel by viewModels()

  override fun getXPageName(): String {
    return XRouterPathConstants.CHOOSE_CATEGORY_ACTIVITY
  }

  override fun initView() {
    getIntentData()
    XEventManager.register(this)
    initTitleBar(binding.include.toolbar, binding.include.tvTitle, "选择类目")
    setupRecyclerView()
    subscribeUiEvent()
    vm.requestCategoryList()
  }

  private fun getIntentData() {
    val paramsMap = intent?.getSerializableExtra(XRouterPathConstants.ParamsKey)
    paramsMap?.let {
      it as HashMap<*, *>
      val firstId = it[firstCategoryId] as Long
      val firstName = it[firstCategoryName] as String
      val secondId = it[secondCategoryId] as Long
      val secondName = it[secondCategoryName] as String
      vm.setLastSelected(SelectCategoryDto(firstId, firstName, secondId, secondName))
    }
  }

  /**
   * 设置列表
   */
  private fun setupRecyclerView() {
    binding.rvCategoryList.adapter = adapter
    adapter.setEmptyView(R.layout.empty_view)
    subAdapter.setEmptyView(R.layout.empty_view)

    adapter.setOnItemClickListener { adapter, _, position ->
      // 记录当前选中的一级分类
      val firstCategory = adapter.data[position] as CategoryListDto
      // 更新列表显示二级分类
      binding.rvCategoryList.adapter = subAdapter
      subAdapter.setList(firstCategory.sub_list)
      vm.showSelectFirstLevelName(firstCategory)
    }
    subAdapter.setOnItemClickListener { adapter, _, position ->
      // 记录选中的二级分类，并回传一级+二级
      val secondCategory = adapter.data[position] as SubCategory
      val selectCategoryDto = vm.showSelectSecondLevelName(secondCategory)
      // 关闭选择类目页面
      XEventManager.post(XBaseEvent(XEventConfig.CHOOSE_CATEGORY_SUCCESS, selectCategoryDto))
      finish()
    }
  }

  private fun subscribeUiEvent() {
    vm.addListEvent.observe(this, {
      it?.let {
        categoryList = it
        adapter.setList(it)
      } ?: adapter.setList(null)
    })
    // 点击已经选择的一级类目
    vm.showFirstLevelListEvent.observe(this, {
      binding.rvCategoryList.adapter = adapter
      if (::categoryList.isInitialized) {
        adapter.setList(categoryList)
        vm.showSelectFirstLevelName()
      }
    })
    vm.goNextEvent.observe(this, {
      startActivity(Intent(this, CategorySearchActivity::class.java))
    })
    // 匹配上次选中的数据成功，显示赏析选中的二级列表
    vm.matchListEvent.observe(this, {
      it?.let {
        // 给类目列表赋值，便于后续切换使用
        categoryList = it
        // 更新列表显示二级分类
        val lastSelectSecondLevelList = vm.getLastSelectSecondLevelList()
        if (lastSelectSecondLevelList != null) {
          binding.rvCategoryList.adapter = subAdapter
          subAdapter.setList(lastSelectSecondLevelList.sub_list)
          vm.showSelectFirstLevelName(lastSelectSecondLevelList)
        }
      }
    })
  }

  @Subscribe(sticky = false, threadMode = ThreadMode.MAIN)
  fun onEvent(event: XBaseEvent?) {
    when (event?.name) {
      // 在当前页面或搜索页面选择成功关闭当前页面
      XEventConfig.CHOOSE_CATEGORY_SUCCESS -> {
        this.finish()
      }
    }
  }

  override fun onDestroy() {
    super.onDestroy()
    XEventManager.unRegister(this)
  }

  companion object {
    const val firstCategoryId = "firstCategoryId"
    const val firstCategoryName = "firstCategoryName"
    const val secondCategoryId = "secondCategoryId"
    const val secondCategoryName = "secondCategoryName"
  }

}
