package com.yidian.shenghuoquan.broot.service

import android.util.Log
import com.yidian.xarc.xbrid.XBridManager
import com.yidian.xarc.xevent.XBaseEvent
import com.yidian.xarc.xevent.XEventManager
import com.yidian.xarc.xrouter.ResultResolver
import com.yidian.yac.core.zap.ZapService
import com.yidian.yac.core.zap.ZapTicket
import org.json.JSONObject

/**
 * XEventService服务
 * ⚠️ 注意：架构需要使用，请勿随意修改
 **/

class XEventService : ZapService() {

  override fun onAction(
    path: String,
    action: String,
    params: Any,
    options: Any,
    resolver: ResultResolver
  ) {
    when (action) {
      "postEvent" -> {
        params as JSONObject
        val name: String = params["name"] as String
        val body = params["body"]
        //向客户端发送Event
        XEventManager.post(XBaseEvent(name, body))
        //向flutter发送Event
        ZapTicket("flutter-event")
          .withAction("handleEvent")
          .withServiceParams(params)
          .onLost { result ->
            Log.d(TAG, "onLost: $result")
          }
          .onResult { result ->
            Log.d(TAG, "flutter-event+onResult: $result")
          }.ship()
        //向h5发送Event
        XBridManager.postEvent(name, body, null)
        resolver.success("事件已发送")
      }
    }
  }

  override fun onInit() {
  }

  override fun onExit() {
  }

  companion object {
    const val SERVICE_NAME: String = "xevent"
    private val TAG = "XEventService"

    // 调用XEventService的示例代码如下：使用ZapTicket
    fun postEvent(xbaseEvent: XBaseEvent) {
      val jsonObject = JSONObject()
      jsonObject.put("name", xbaseEvent.name)
      jsonObject.put("body", xbaseEvent.body)
      ZapTicket(SERVICE_NAME)
        .withAction("postEvent")
        .withServiceParams(jsonObject)
        .onLost { result ->
          Log.d(TAG, "onLost: $result")
        }
        .onResult { result ->
          Log.d(TAG, "onResult: $result")
        }.ship()
    }
  }

}
