package com.yidian.shenghuoquan.bgoods.service

import com.google.gson.Gson
import com.yidian.bcommon.XEventConfig
import com.yidian.bcommon.XRouterPathConstants
import com.yidian.shenghuoquan.bgoods.dto.SelectCategoryDto
import com.yidian.shenghuoquan.bgoods.ui.coupon.ChooseCategoryActivity
import com.yidian.xarc.xevent.XBaseEvent
import com.yidian.xarc.xevent.XEventManager
import com.yidian.xarc.xrouter.ResultResolver
import com.yidian.xpage.XPageManager
import com.yidian.yac.core.zap.ZapService
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.json.JSONObject

/**
 * 发布优惠券相关服务
 */
class SelectCategoryService : ZapService() {

  private lateinit var resolver: ResultResolver

  override fun onAction(path: String, action: String, params: Any, options: Any, resolver: ResultResolver) {
    this.resolver = resolver
    params as JSONObject
    when (action) {
      "selectGoodsCategory" -> {// 选择类目
        gotoSelectCategory(params)
      }
    }
  }

  /**
   * 选择类目
   */
  private fun gotoSelectCategory(params: JSONObject) {
    val lastSelectCategory = params.optJSONObject("selectedCategory")
    lastSelectCategory?.let {
      val firstCategoryId = it.optLong("firstCategoryId")
      val firstCategoryName = it.optString("firstCategoryName")
      val secondCategoryId = it.optLong("secondCategoryId")
      val secondCategoryName = it.optString("secondCategoryName")
      if (firstCategoryId == 0L || firstCategoryName.isNullOrBlank() || secondCategoryId == 0L || secondCategoryName.isNullOrBlank()) {
        XPageManager.push(XRouterPathConstants.CHOOSE_CATEGORY_ACTIVITY, null)
        return
      }
      val map = HashMap<String, Any>()
      map[ChooseCategoryActivity.firstCategoryId] = firstCategoryId
      map[ChooseCategoryActivity.firstCategoryName] = firstCategoryName
      map[ChooseCategoryActivity.secondCategoryId] = secondCategoryId
      map[ChooseCategoryActivity.secondCategoryName] = secondCategoryName
      XPageManager.push(XRouterPathConstants.CHOOSE_CATEGORY_ACTIVITY, map)
    } ?: XPageManager.push(XRouterPathConstants.CHOOSE_CATEGORY_ACTIVITY, null)
  }

  @Subscribe(sticky = false, threadMode = ThreadMode.MAIN)
  fun onEvent(event: XBaseEvent?) {
    when (event?.name) {
      XEventConfig.CHOOSE_CATEGORY_SUCCESS -> {// 选中的类目回传H5
        val selectedCategory = event.body as SelectCategoryDto
        val params = Gson().toJson(selectedCategory)
        resolver.success(JSONObject(params))
      }
    }
  }

  override fun onExit() {
    XEventManager.unRegister(this)
  }

  override fun onInit() {
    XEventManager.register(this)
  }

  companion object {
    const val serviceName: String = "selectCategoryService"
  }

}
