package com.ydl.component.service.web

import android.Manifest
import com.blankj.utilcode.util.PermissionUtils
import com.google.gson.JsonObject
import com.google.gson.JsonParser
import com.tencent.smtt.sdk.WebView
import com.ydl.audioim.YDLavManager
import com.ydl.confide.api.IConfideService
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.modular.findRouteService
import com.ydl.ydlcommon.ui.Loading
import com.yidianling.common.tools.ToastUtil
import com.yidianling.common.tools.asFragmentActivity
import com.yidianling.user.UserHelper
import de.greenrobot.event.EventBus


class JsMethod(private val webView: WebView?) {


    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
            }
            "has_audio_permission" -> {
                val callback = param.getAsJsonPrimitive("callback").asString
                if (callback.isNullOrBlank()) return true
                if (PermissionUtils.isGranted(Manifest.permission.RECORD_AUDIO)) {
                    webView?.post {
                        webView.loadUrl("javascript:$callback(1)")
                    }
                    return true
                }
                (webView?.context?.asFragmentActivity())?.let {
                    findRouteService(IConfideService::class.java).requestConfidePermission(it) { granted ->
                        webView.post {
                            webView.loadUrl("javascript:$callback(${if (granted) 1 else 0})")
                        }
                    }
                }
                return true
            }

            "confide_dial" -> {
                //倾诉链接 java接口，支持axb和声网
                val id = param.getAsJsonPrimitive("id").asInt
                val data = param.getAsJsonObject("data").toString()
                val topActivity = BaseActivityMgr.INST.topActivity

                if (!YDLavManager.isOnlineRtm) {
                    //异常退出或者账号被顶掉，重新登录并拨打
                    YDLavManager.instances.login(UserHelper.getUserInfo()?.uid) { isSuccess: Boolean, _ ->
                        if (isSuccess) {
                            findRouteService(IConfideService::class.java).confideDial(id, data, topActivity)
                        } else {
                            ToastUtil.toastShort("请重新拨打")
                        }
                    }
                } else {
                    findRouteService(IConfideService::class.java).confideDial(id, data, topActivity)
                }
                return true
            }
            "check_app_support" -> {
                val callback = param.getAsJsonPrimitive("callback").asString
                val type = param.getAsJsonPrimitive("type").asInt
                if (callback.isNullOrBlank()) return true
                webView?.post {
                    when (type) {
                        1 -> {//检查音频权限能力
                            webView.loadUrl("javascript:$callback(1)")
                        }
                        else -> {
                            webView.loadUrl("javascript:$callback(0)")
                        }
                    }
                }
                return true
            }
            else -> {
                return false
            }
        }
    }
}