package com.ydl.component.service.web

import com.google.gson.JsonObject
import com.google.gson.JsonParser
import com.ydl.confide.home.event.ConfideDialogEvent
import com.ydl.webview.H5Params
import com.ydl.webview.NewH5Activity
import com.ydl.ydlcommon.base.BaseActivityMgr
import com.ydl.ydlcommon.ui.Loading
import com.yidianling.common.tools.ToastUtil
import de.greenrobot.event.EventBus


class JsMethod {


    fun handle(param: String): Boolean {
        try {
            val obj = JsonParser().parse(param).asJsonObject
            val cmd = obj.getAsJsonObject("cmd")
            val actionName = cmd?.getAsJsonPrimitive("action_name")?.asString
            if (actionName.isNullOrBlank()) return false
            return innerHandle(actionName, cmd)
        } catch (throwable: Throwable) {
            throwable.printStackTrace()
            return false
        }
    }

    private fun innerHandle(actionName: String, obj: JsonObject): Boolean {
        val param = obj.getAsJsonObject("params")
        when (actionName) {
            "handle_confide_btn" -> {
                val show = param.getAsJsonPrimitive("show").asInt
                EventBus.getDefault().post(ConfideDialogEvent(show))
                return true
            }
            "show_loading" -> {
//                val topActivity = BaseActivityMgr.INST.getTopActivity()
//                Loading.show(topActivity)
                return true
            }
            "close_loading" -> {
//                Loading.close()
                return true
            }
            "open_app_eval_list"->{
                val url = param.getAsJsonPrimitive("url").asString
                val topActivity = BaseActivityMgr.INST.getTopActivity()
                NewH5Activity.start(topActivity, H5Params(url, ""))
                return true
            }
            "toast" -> {
                val msg = param.getAsJsonPrimitive("msg").asString
                if (!msg.isNullOrBlank()) {
                    ToastUtil.toastShort(msg)
                }
                return true
            }
            else -> {
                return false
            }
        }
    }
}