package com.yidian.shenghuoquan.bmanagercenter.service

import com.google.gson.Gson
import com.yidian.bcommon.constant.XEventConfig
import com.yidian.bcommon.constant.XRouterPathConstants
import com.yidian.shenghuoquan.bmanagercenter.ui.store.ChooseStoreActivity
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.JSONArray
import org.json.JSONObject


/**
 * 选择门店服务
 */
class SelectStoreService : 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) {
      "selectStore" -> {// 选择门店
        gotoSelectStore(params)
      }
    }
  }

  /**
   * 选择门店
   */
  private fun gotoSelectStore(params: JSONObject) {
    val lastSelectStoreArray = params.optJSONArray("selectedStore")
    if (lastSelectStoreArray == null || lastSelectStoreArray.length() <= 0) {
      XPageManager.push(XRouterPathConstants.CHOOSE_STORE_ACTIVITY, null)
    } else {
      val list = mutableListOf<String>()
      for (i in 0 until lastSelectStoreArray.length()) {
        list.add(lastSelectStoreArray.getString(i))
      }
      val map = HashMap<String, Any?>()
      map[ChooseStoreActivity.lastSelectStoreKey] = list
      XPageManager.push(XRouterPathConstants.CHOOSE_STORE_ACTIVITY, map)
    }
  }

  @Subscribe(sticky = false, threadMode = ThreadMode.MAIN)
  fun onEvent(event: XBaseEvent?) {
    when (event?.name) {
      XEventConfig.CHOOSE_STORE_SUCCESS -> {// 选中的门店回传H5
        val list = event.body as List<*>
        val params = Gson().toJson(list)
        resolver.success(JSONArray(params))
      }
    }
  }

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

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

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