package com.bricks.mp.actions import com.bricks.mp.core.BricksBind import com.bricks.mp.core.BricksContext import com.bricks.mp.core.BricksHttp import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.serialization.json.* /** * 事件分发器 - 处理 actiontype: urlwidget/method/script/registerfunction/event */ class ActionDispatcher( private val context: BricksContext, private val http: BricksHttp, private val scope: CoroutineScope ) { private val registeredFunctions = mutableMapOf Unit>() /** * 注册回调函数 (registerfunction) */ fun registerFunction(name: String, func: () -> Unit) { registeredFunctions[name] = func } /** * 分发事件 */ fun dispatch(bind: BricksBind) { when (bind.actiontype) { "urlwidget" -> handleUrlWidget(bind) "method" -> handleMethod(bind) "script" -> handleScript(bind) "registerfunction" -> handleRegisterFunction(bind) "event" -> handleEvent(bind) else -> println("[Bricks] Unknown actiontype: ${bind.actiontype}") } } private fun handleUrlWidget(bind: BricksBind) { scope.launch { val url = bind.url ?: return@launch val fullUrl = context.entireUrl(url) try { val result = http.getJson(fullUrl) // 加载新的 widget 并更新 UI println("[Bricks] urlwidget loaded: $fullUrl") } catch (e: Exception) { println("[Bricks] urlwidget error: ${e.message}") } } } private fun handleMethod(bind: BricksBind) { // 调用客户端方法 println("[Bricks] method called: ${bind.methodname}") } private fun handleScript(bind: BricksBind) { scope.launch { // 服务端脚本调用 val script = bind.script ?: return@launch println("[Bricks] script: $script") } } private fun handleRegisterFunction(bind: BricksBind) { val name = bind.target ?: return registeredFunctions[name]?.invoke() } private fun handleEvent(bind: BricksBind) { println("[Bricks] event: ${bind.event} -> ${bind.actiontype}") } }