package com.yidian.shenghuoquan.commodity.ui.coupon.viewmodel

import androidx.lifecycle.MutableLiveData
import com.orhanobut.hawk.Hawk
import com.yidian.common.HawkConfig
import com.yidian.common.mvvm.BaseViewModel
import com.yidian.shenghuoquan.commodity.dto.CommodityManagementListDto
import com.yidian.shenghuoquan.commodity.dto.CommodityStatus
import com.yidian.shenghuoquan.commodity.dto.Goods
import com.yidian.shenghuoquan.commodity.http.CouponDataSource
import com.yidian.shenghuoquan.commodity.http.callback.IGetCommodityManagementListCallback

/**
 * author: yinjiacheng
 * date: 7/2/21 10:44 AM
 * description: 商品列表
 */
class CommodityListViewModel : BaseViewModel(), IGetCommodityManagementListCallback {

  companion object {
    // 商品类型
    private const val PARAMS_COMMODITY_TYPE = "type"

    // 当前生活号id
    private const val PARAMS_LIFE_ACCOUNT_ID = "life_account_id"

    // 每页数量
    private const val PARAMS_COMMODITY_LIST_PAGE_SIZE = "num"

    // 上一次列表中最后一个goods_spu_id
    private const val PARAMS_COMMODITY_LIST_LAST_ID = "last_id"
  }

  /**
   * 记录上一次请求列表中最后一项id
   */
  private var lastId: String? = null

  /**
   * 列表加载类型
   */
  private var loadType: LoadType? = null

  /**
   * 刷新完成和上拉加载完成LiveData
   */
  val refreshFinish by lazy { MutableLiveData<List<Goods>>() }
  val loadMoreFinish by lazy { MutableLiveData<List<Goods>>() }

  /**
   * 请求商品管理列表
   * @param status 商品状态
   * @param pageSize 每页数据量 分页加载用
   * @param type 列表加载类型
   */
  fun requestCommodityManagementList(status: CommodityStatus, pageSize: Int?, type: LoadType) {
    // 记录加载类型
    loadType = type
    // 下拉刷新重置lastRequestIndex
    if (type == LoadType.REFRESH) lastId = null
    val requestParams = HashMap<String, String?>(4)
    requestParams[PARAMS_COMMODITY_TYPE] = status.type
    requestParams[PARAMS_LIFE_ACCOUNT_ID] = Hawk.get(HawkConfig.LifeAccountId, "")
    pageSize?.let { requestParams[PARAMS_COMMODITY_LIST_PAGE_SIZE] = it.toString() }
    lastId?.let { requestParams[PARAMS_COMMODITY_LIST_LAST_ID] = it }
    CouponDataSource.getCommodityManagementList(this, requestParams)
  }

  override fun getCommodityListSuccess(result: CommodityManagementListDto?) {
    lastId = result?.lastId
    // 通知下拉刷新或上拉加载更多完成
    when (loadType) {
      LoadType.REFRESH -> refreshFinish.value = result?.goodsList
      LoadType.LOAD_MORE -> loadMoreFinish.value = result?.goodsList
      else -> return
    }
  }

  override fun getCommodityListFailure(message: String?) {
    when (loadType) {
      LoadType.REFRESH -> refreshFinish.value = null
      LoadType.LOAD_MORE -> loadMoreFinish.value = null
      else -> return
    }
  }

  /**
   * 列表加载类型
   */
  enum class LoadType {
    // 初次加载
    INITIALIZE,

    // 下拉刷新
    REFRESH,

    // 上拉加载更多
    LOAD_MORE
  }

}
