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

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.yidian.bcommon.mvvm.BaseViewModel
import com.yidian.bcommon.utils.ToastUtils
import com.yidian.shenghuoquan.bgoods.dto.CategoryListDto
import com.yidian.shenghuoquan.bgoods.dto.SelectCategoryDto
import com.yidian.shenghuoquan.bgoods.http.CouponDataSource
import com.yidian.shenghuoquan.bgoods.http.callback.ICategoryListCallback

class CategorySearchViewModel : BaseViewModel() {


  var searchKeyword = MutableLiveData("")

  /**
   * 清空输入框
   */
  private val _clearEditEvent = MutableLiveData<Unit>()
  val clearEditEvent: LiveData<Unit> = _clearEditEvent

  /**
   * 发送搜索关键字
   */
  private val _sendKeywordEvent = MutableLiveData<String>()
  val sendKeywordEvent: LiveData<String> = _sendKeywordEvent

  /**
   * 搜索成功 Event
   */
  private val _searchSuccessEvent = MutableLiveData<MutableList<SelectCategoryDto>?>()
  val searchSuccessEvent: LiveData<MutableList<SelectCategoryDto>?> = _searchSuccessEvent


  fun toSearch() {
    if (searchKeyword.value.isNullOrBlank()) {
      ToastUtils.showShortSafe("请输入关键词搜索商品类目")
      return
    }
    requestCategoryList()
  }

  /**
   * 请求类目列表
   */
  private fun requestCategoryList() {
    val paramsMap = HashMap<String, String?>()
    paramsMap["category_name"] = searchKeyword.value
    CouponDataSource.getCategoryList(requestCategoryListCallBack, paramsMap)
  }

  private val requestCategoryListCallBack = object : ICategoryListCallback {
    override fun getCategoryListSuccess(dto: MutableList<CategoryListDto>?) {
      if (dto.isNullOrEmpty()) {
        _searchSuccessEvent.value = null
      } else {
        // 向adapter中传入搜索关键字
        _sendKeywordEvent.value = searchKeyword.value
        // 转换列表
        val resultList = mutableListOf<SelectCategoryDto>()
        dto.forEachIndexed { index, categoryListDto ->
          if (!dto[index].sub_list.isNullOrEmpty()) {
            dto[index].sub_list.forEach {
              val selectCategoryDto = SelectCategoryDto(categoryListDto.category_id, categoryListDto.name, it.category_id, it.name)
              resultList.add(selectCategoryDto)
            }
          }
        }
        _searchSuccessEvent.value = resultList
      }
    }
  }

  fun toClear() {
    _clearEditEvent.value = Unit
  }

}
