package com.ydl.js

import android.Manifest
import android.content.Intent
import android.net.Uri
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.api.IAudioImService
import com.ydl.confide.api.IConfideService
import com.ydl.confide.event.ConfideDialogEvent
import com.ydl.webview.H5Params
import com.ydl.webview.NewH5Activity
import com.ydl.ydl_router.manager.YDLRouterManager
import com.ydl.ydl_router.manager.YDLRouterParams
import com.ydl.ydlcommon.base.BaseActivityMgr
import com.ydl.ydlcommon.modular.findRouteService
import com.ydl.ydlcommon.router.IYDLRouterConstant
import com.ydl.ydlcommon.utils.Utils
import com.yidianling.common.tools.ToastUtil
import com.yidianling.common.tools.asFragmentActivity
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 (!findRouteService(IAudioImService::class.java).getIsOnlineRtm()) {
                    //异常退出或者账号被顶掉，重新登录并拨打
                    findRouteService(IAudioImService::class.java).loginRtm(JsModularService.getIUserService().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,2 -> {//检查音频权限能力
                            webView.loadUrl("javascript:$callback(1)")
                        }
                        else -> {
                            webView.loadUrl("javascript:$callback(0)")
                        }
                    }
                }
                return true
            }
            "startCms" ->{
                if (Utils.isFastClick()) {
                    return true
                }
                val activity = BaseActivityMgr.INST.topActivity
                if (JsModularService.getIUserService().loginByOneKeyLogin(activity, true)) {
                    val location = param.getAsJsonPrimitive("location").asInt
                    JsModularService.getImService().startP2PSession(activity, location, null)
                }
                return true
            }

            "to_search_list" ->{
                if (Utils.isFastClick()) {
                    return true
                }
                val cateId = param.getAsJsonPrimitive("cateId").asString
                val cateTitle = param.getAsJsonPrimitive("cateTitle").asString
                YDLRouterManager.router(
                    IYDLRouterConstant.ROUTER_CONSULT_LIST,
                    YDLRouterParams().putExtra(IYDLRouterConstant.EXTRA_CATEID, cateId)
                        .putExtra(IYDLRouterConstant.EXTRA_CATETITLE, cateTitle)
                        .putExtra(IYDLRouterConstant.EXTRA_SHOWTYPE, "0")
                )
                return true
            }
            "call_telPhone" -> {
                val phoneNumber = param.getAsJsonPrimitive("phonenumber").asString
                phoneNumber?.let {
                    val phoneIntent = Intent(Intent.ACTION_DIAL, Uri.parse("tel:$phoneNumber"))
                    BaseActivityMgr.INST.topActivity?.startActivity(phoneIntent)
                }
                return true
            }
            else -> {
                return false
            }
        }
    }
}