package com.ydl.js

import android.app.Activity
import android.content.Context
import android.webkit.JavascriptInterface
import androidx.fragment.app.FragmentActivity
import com.google.gson.Gson
import com.tencent.smtt.sdk.WebView
import com.ydl.confide.api.ConfideRoute
import com.ydl.confide.api.IConfideService
import com.ydl.js_module.manager.WebViewRouterManager
import com.ydl.webview.H5JsBean
import com.ydl.webview.IJavascriptHandler
import com.ydl.ydl_router.manager.YDLRouterManager
import com.ydl.ydlcommon.base.BaseActivityMgr
import com.ydl.ydlcommon.base.config.HttpConfig
import com.ydl.ydlcommon.modular.findRouteService
import com.ydl.ydlcommon.utils.Utils
import com.ydl.ydlcommon.utils.actionutil.ActionCountUtils
import com.ydl.ydlcommon.utils.log.AliYunLogConfig
import com.ydl.ydlcommon.utils.log.AliYunRichLogsHelper
import com.ydl.ydlcommon.utils.log.LogHelper
import com.ydl.ydlcommon.view.dialog.CommonDialog
import com.yidianling.common.tools.LogUtil
import com.yidianling.user.api.service.IUserService

/**
 * update by harvie on 2017/7/04
 */

class NewH5_JavascriptHandler(private val webView: WebView?, private val wvEnventPro: NewH5_WebViewClientClickListener?) : IJavascriptHandler() {

    private val js = JsMethod(webView)

    override fun getUriAppendSuffix(): String {
        return "platform_main_theme=00C9E2&platform_main_theme_light=00D4DF&platform_main_theme_bright=EAFAFC"
    }

    @JavascriptInterface
    fun sendDataToOC(params: String) {
        LogUtil.e("js", params)
        AliYunRichLogsHelper.getInstance().sendRichLog(AliYunLogConfig.WEB, "params:$params")
        //js交互路由 后期会去除掉这个路由 统一使用下面的路由
        //该路由只有测试记录h5页面在使用 - 测试题支付/测试题详情/测试题结果
        val webViewRouter = WebViewRouterManager()
        if (webViewRouter.toNative(params)) {
            //
            return
        }
        //壹点灵路由
        if (YDLRouterManager.router(params)) {
            return
        }
        if (js.handle(params)) return
        val jsData = Gson().fromJson(params, H5JsBean::class.java)
        //是否登录
        if (jsData.cmd?.action_name != null && jsData.cmd!!.action_name.equals("login")) {
            //跳转登陆页面
            wvEnventPro?.jumpLogin(jsData.cmd?.params)
            return
        }
        val userService = findRouteService(IUserService::class.java)
        if (jsData.url.equals("http")) {

            if (jsData.cmd?.params?.toUid != 0) {
                wvEnventPro?.chat(
                    userService.getUserInfo()?.uid?.toInt() ?: 0,
                    jsData.cmd?.params?.toUid ?: 0,
                    0,
                    userService.getUserInfo()?.accessToken,
                    jsData.cmd?.params?.isFromQingShu ?: 0,
                    jsData.cmd?.params?.closeReplaceChat ?: false
                )
            } else {
                wvEnventPro?.openH5(jsData.cmd?.params)
            }
        } else if (jsData.url.equals("ydl_app")) {
            wvEnventPro?.ydlNative(jsData.cmd)
            jumpAction(jsData, userService)
        }
    }

    private fun jumpAction(jsData: H5JsBean, userService: IUserService) {
        LogUtil.d("jumpAction")
        when (jsData.cmd!!.action_name) {
            "fm" -> if (jsData.cmd!!.params!!.id > 0) {
                //跳转fm详情页面
                if (wvEnventPro != null) {
                    wvEnventPro!!.openFmDetail(jsData.cmd!!.params!!.id)
                }
            } else if (wvEnventPro != null) {
                wvEnventPro!!.openFmList()
            }
            "search_service_doc" -> if (wvEnventPro != null) {
                wvEnventPro!!.searchServiceDoc(jsData.cmd!!.params!!.cate_id)
            }
            "article_list" ->
                //文章列表
                if (wvEnventPro != null) {
                    wvEnventPro!!.openArticle()
                }
            "fm_detail" ->
                //fm详情
                if (wvEnventPro != null) {
                    wvEnventPro!!.openFmDetail(jsData.cmd!!.params!!.id)
                }
            "pay" -> if (wvEnventPro != null) {
                //预约咨询
                wvEnventPro!!.pay(jsData.cmd?.params)
            }
            "pay_receipt" -> if (wvEnventPro != null) {
                //专家收款
                wvEnventPro!!.payReceipt(jsData.cmd?.params)
            }
            "pay_course" ->
                //购买课程
                if (wvEnventPro != null) {
                    wvEnventPro!!.payCourse(jsData.cmd?.params)
                }
            "pay_test" ->
                //付费测试
                if (wvEnventPro != null) {
                    wvEnventPro!!.payTest(jsData.cmd?.params)
                }
            "view_test_result" ->
                //查看测试结果
                if (wvEnventPro != null) {
                    wvEnventPro!!.viewTestResult(jsData.cmd?.params)
                }
            "chat" ->
                //私聊
                if (wvEnventPro != null) {
                    wvEnventPro.chat(userService.getUserResponse()?.uid?.toInt() ?: 0,
                        jsData.cmd!!.params!!.toUid, 0,
                        JsModularService.getIUserService().getUserInfo()?.accessToken,
                        jsData.cmd!!.params!!.isFromQingShu,
                        jsData.cmd!!.params!!.closeReplaceChat
                    )
                    // 埋点
                    ActionCountUtils.count("ydl_user_main_page|private_chat_click")
                }
            "chat_send_message" -> {
                //跳转私聊：并发送消息
                wvEnventPro?.chatSendMessage(
                    userService.getUserResponse()?.uid?.toInt() ?: 0,
                    jsData.cmd!!.params!!.toUid,
                    0, JsModularService.getIUserService().getUserInfo()?.accessToken,
                    jsData.cmd!!.params!!.isFromQingShu
                )
            }
            "chat_team" ->
                //群聊
                if (wvEnventPro != null) {
                    wvEnventPro!!.chatTeam(jsData.cmd!!.params!!.tid, jsData.cmd!!.params!!.doctor_id)
                }
            "sendResult" -> if (wvEnventPro != null) {
                wvEnventPro!!.sendInfo(jsData.cmd!!.params)
            }
            "active_send_share" -> {
                val cover1 = jsData.cmd!!.params!!.share!!.cover
                val title1 = jsData.cmd!!.params!!.share!!.title
                val purl1 = jsData.cmd!!.params!!.share!!.url
                val share_url1 = jsData.cmd!!.params!!.share!!.share_url
                if (wvEnventPro != null) {
                    wvEnventPro!!.sendResultTrend(cover1, title1, purl1, share_url1)
                }
            }
            "active_send" -> if (wvEnventPro != null) {
                wvEnventPro!!.sendTrend()
            }
            "topic_detail" -> if (wvEnventPro != null) {
                wvEnventPro!!.openTopicDetail(jsData.cmd?.params?.id.toString() + "")
            }
            "set_time_warn" ->
                //提醒专家设置时间
                if (wvEnventPro != null) {
                    wvEnventPro.sendSubscriptionTimeMessage("" + jsData.cmd?.params?.toUid)
                }
            "user_home" -> if (wvEnventPro != null) {
                wvEnventPro!!.openMember("" + jsData.cmd?.params?.uid)
            }
            "sq_topic" -> if (wvEnventPro != null) {
                wvEnventPro!!.openTopicDetail(jsData.cmd?.params?.id.toString() + "")
            }
            "good_expert"  //推荐专家
            -> if (wvEnventPro != null) {
                wvEnventPro!!.goodExpert()
            }
            "copywechat"//复制到微信
            -> if (wvEnventPro != null) {
                wvEnventPro!!.copyWechat(jsData.cmd?.params)
            }
            "gowechat"//打开微信
            -> if (wvEnventPro != null) {
                wvEnventPro!!.goWechat()
            }
            //课程播放--不区分音视频或者试听
            "course_play" -> {
                wvEnventPro!!.coursePlay(jsData.cmd?.params)
            }
            //h5播放时，需要关闭app中悬浮的播放窗
            "course_close_float_view" -> {
                wvEnventPro!!.closeFloatView()
            }
            //课程评论
            "course_write_comment" -> {
                wvEnventPro!!.courseWriteComment(jsData.cmd?.params)
            }
            "contact_yi" //联系小壹
            -> if (wvEnventPro != null) {
                wvEnventPro!!.contactYi()
            }
            "contact_course_customer_service" //联系课程专属客服
            -> if (wvEnventPro != null) {
                wvEnventPro!!.contactCourseCustomerService()
            }
            "course_comments"//课程评论
            -> if (wvEnventPro != null) {
                wvEnventPro!!.courseComment(jsData.cmd?.params)
            }
            "test_item" ->
                //开始测试
                if (wvEnventPro != null) {
                    wvEnventPro!!.openTest(jsData.cmd?.params)
                }
            "doctor_home"//专家主页
            -> if (wvEnventPro != null) {
                wvEnventPro!!.openExpertsHome(jsData.cmd?.params)
            }
            "search_list" -> if (wvEnventPro != null) {
                wvEnventPro!!.searchList(jsData.cmd?.params)
            }
            "order_detail"//我的订单详情
            -> if (wvEnventPro != null) {
                wvEnventPro!!.openOrderDetail(jsData.cmd?.params)
            }
            "expert_product"//专家商品详情
            -> if (wvEnventPro != null) {
                wvEnventPro!!.expertProduct(jsData.cmd?.params)
            }
            "order"//订单预约页面
            -> if (wvEnventPro != null) {
                wvEnventPro!!.order(jsData.cmd?.params)
            }
            "to_order_ct"//免费体验下单页面
            -> if (wvEnventPro != null) {
                wvEnventPro!!.toOrderCt(jsData.cmd?.params)
            }
            "show_doc"//搜索专家的列表
            -> if (wvEnventPro != null) {
                wvEnventPro!!.showDocList(jsData.cmd?.params)
            }
            "listen-order-detail"//倾诉订单详情
            -> if (wvEnventPro != null) {
                wvEnventPro!!.listenOrderDetail(jsData.cmd?.params)
            }
            "detail-sub"//预约订单子订单
            -> if (wvEnventPro != null) {
                wvEnventPro!!.detailSub(jsData.cmd?.params)
            }
            "agreement"//用户协议
            -> if (wvEnventPro != null) {
                wvEnventPro!!.openAgreement(jsData.cmd?.params)
            }
            "modify-eval" -> if (wvEnventPro != null) {
                wvEnventPro!!.modifyEval(jsData.cmd?.params)
            }
            "view-eval"//查看评价
            -> {
                wvEnventPro?.visitEval(jsData.cmd?.params)
            }
            "article" -> {
                wvEnventPro?.openH5(jsData.cmd?.params)
            }
            "test" -> {
                wvEnventPro?.openH5(jsData.cmd?.params)
            }
            "test_detail" -> {//测试详情页
                wvEnventPro?.openTestDetail(jsData.cmd?.params)
            }
            "test_list" -> {
                wvEnventPro?.openTestList()
            }
            "course_list" ->
                //课程列表
                wvEnventPro?.courseList()
            "active_detail" -> {
                //动态详情
                wvEnventPro?.activeDetail(jsData.cmd?.params?.id.toString() + "")
            }
            "listen_tel" -> {
                //倾诉，立即连接
                wvEnventPro?.listenTel(jsData.cmd?.params)
            }
            "listen_agora" -> {
                //声网
                wvEnventPro?.listenAgora(jsData.cmd?.params)
            }
            "confide_connect" -> {
                //倾诉链接 java接口，支持axb和声网
                wvEnventPro?.confideConnect(jsData.cmd?.params)
            }
            "voice_broadcast" -> {
                //语音直播
                LogHelper.getInstance().writeLogSync("课程详情页进入课程 " +
                        "replay_url = " + jsData.cmd?.params?.replay_url +
                        ", roomid = " + jsData.cmd?.params?.roomid +
                        ", roomname = " + jsData.cmd?.params?.roomname +
                        ", starttime = " + jsData.cmd?.params?.start_time)
                wvEnventPro?.voiceBroadcast(jsData.cmd?.params)
            }
            "tel" -> {
                wvEnventPro?.tel(jsData.cmd?.params)
            }
            "onorder_by_app" -> {
                //预约下单
                wvEnventPro?.onOrderByApp(jsData.cmd?.params)
            }
            "feedback" -> {
                wvEnventPro?.feedBack()
            }
            "order_set_time" -> {
                //预约下单--选择时间回调
                wvEnventPro?.orderSetTime(jsData.cmd?.params)
            }
            "listen_list" -> {
                wvEnventPro?.phoneCall()
            }
            "action_share" -> {
                LogUtil.d("action_share")
                wvEnventPro?.shareAction(jsData.cmd?.params)
            }
            "chat_schedule" -> {
                // 专家修改时间和用户确认时间跳转到私聊
                wvEnventPro?.chatSchedule(jsData.cmd?.params)
            }
            "action_invite" -> {
                wvEnventPro?.invite(jsData.cmd?.params)
            }
            "action_fund" -> {
                wvEnventPro?.balance(jsData.cmd?.params)
            }
            "down_refresh" -> {
                // 禁止下拉刷新
                wvEnventPro?.switchDownRefresh(jsData.cmd?.params)
            }
            //跳转充值界面
            "recharge" -> {
                wvEnventPro?.recharge()
            }
            //跳转绑定手机号
            "bind_phone" -> {
                wvEnventPro?.bindPhone()
            }
            "refresh" -> {
                wvEnventPro?.refresh()
            }
            "set_title" -> {
                wvEnventPro?.setTitle(jsData.cmd?.params)
            }
            "save_image" -> {
                wvEnventPro?.saveImage(jsData.cmd?.params)
            }
            "send_to_expert" -> {
                wvEnventPro?.sendToExpert(jsData.cmd?.params)
            }
            "confide_pay" -> {
                wvEnventPro?.confidePay(jsData.cmd?.params)
            }
            "back" -> {
                //用于h5页面返回上一级
                wvEnventPro?.back()
            }
            //购买系列课程
            "common_pay" -> {
                wvEnventPro?.commonPay(jsData.cmd?.params)
            }
            "hideStatusBar" -> {
                wvEnventPro?.hideStatusBar()
            }
            "showStatusBar" -> {
                wvEnventPro?.showStatusBar()
            }
            "openRightTopMenu" -> {
                wvEnventPro?.openRightTopMenu()
            }
            "openShareMenu" -> {
                wvEnventPro?.openShareMenu(jsData.cmd?.params)
            }
            "close" -> {
                wvEnventPro?.closeWebKit()
            }
            //关闭所有页面，返回首页
            "goHome" -> {
                wvEnventPro?.goHome(jsData.cmd?.params)
            }
            "chatUnread" -> {
                wvEnventPro?.sendUnReadNum(jsData.cmd!!.params?.callBack, jsData.cmd!!.params?.uid.toString())
            }
            "switch_push_status" -> {
                wvEnventPro?.switchPushStatus(jsData.cmd?.params)
            }
            "showTitleBar" -> {
                jsData.cmd!!.params?.let {
                    wvEnventPro?.shouldShowTitleBar(it.isShowTitleBar!!)
                }
            }
            "setSelfPageType" -> {
                jsData.cmd!!.params?.let {
                    wvEnventPro?.setSelfPageType(it.selfPageType)
                }
            }
            "setBootomFitViewColor" -> {
                wvEnventPro?.setBootomFitViewColor(jsData.cmd?.params?.bottomfitViewColor ?: "")
            }
            // 打开时间选择器
            "requestSelectTime"->{
                if (Utils.isFastClick()){
                    return
                }
                wvEnventPro?.openTimePicker(jsData.cmd?.params?.callBack,jsData.cmd?.params?.day,jsData.cmd?.params?.doctorId.toString(),jsData.cmd?.params?.orderId)
            }
            // 返回上一页并刷新
            "goBackAndReload"->{
                wvEnventPro?.goBackAndReload(jsData.cmd?.params?.url)
            }
            // 跳转到第三方app
            "toThirdApp" ->{
                wvEnventPro?.toThirdApp(jsData.cmd?.params?.url)
            }


            "meditation_play" -> {
                jsData.cmd!!.params?.let{
                    val mediaId = it.mediaId
                    val meditationId = it.meditationId
                    val meditationType = it.meditionType
                    val mediaCoverUrl = it.coverImageUrl
                    if (mediaId != null && meditationId!=null && meditationType!=null) {
                        wvEnventPro?.playMeditation(mediaId,meditationId.toLong(),
                            meditationType,mediaCoverUrl)
                    }
                }
            }

            "switch_sound" -> {
                jsData.cmd!!.params?.let{
                    val mediaId = it.mediaId
                    val meditationId = it.meditationId
                    val meditationType = it.meditionType
                    val businessType = it.businessType
                    val buried = it.buried
                    val mediaUrl = it.mediaUrl
                    val mediaCoverUrl = it.coverImageUrl
                    val title = it.title
                    val desc = it.desc
                    val status = it.status
                    if (mediaId != null && meditationId!=null && meditationType!=null) {
                        wvEnventPro?.switchSound(mediaId,meditationType.toLong(),businessType!!,
                            meditationId,buried,mediaUrl,mediaCoverUrl,title,desc,status)
                    }
                }
            }

            "loadUrl" -> {
                jsData.cmd?.params?.let{
                    wvEnventPro?.reloadUrl(jsData.cmd?.params?.url)
                }
            }

            "webViewBackgroundColor" -> {
                jsData.cmd?.params?.let{
                    val rgb = it.color
                    val alpha = it.alpha
                    wvEnventPro?.setBG(rgb,alpha)
                }
            }


            //再换一位
            "get_next_doctor"->{
                wvEnventPro?.getNextExpertStatus(jsData.cmd?.params?.doctorId.toString(),jsData.cmd?.params?.title,jsData.cmd?.params?.uid.toString(),jsData.cmd?.params?.linkUrl)
            }
            "show_popup_window" -> {
                val doctorId = jsData.cmd?.params?.doctorId?.toString()
                val confideId = jsData.cmd?.params?.confidedId
                val uid = jsData.cmd?.params?.uid?.toString()
                val topActivity = BaseActivityMgr.INST.getTopActivity()
                if (topActivity is FragmentActivity && doctorId != null && confideId != null) {
                    val url = HttpConfig.MH5_URL + ConfideRoute.h5ConfideIntro(confideId)
                    findRouteService(IConfideService::class.java).showExpertDetailDialog(topActivity, url, doctorId, uid ?: "")
                }
            }
            "chat_close_bottom_webview" -> {
                jsData.cmd!!.params?.let {
                    wvEnventPro?.chatCloseBottomWebView()
                }
            }

            "open_article_comment_dialog" -> {
                wvEnventPro?.showCommentArticleDialog(jsData.cmd?.params)
            }


            "resources_to_preview" -> {
                wvEnventPro?.resourceToPreview(jsData.cmd?.params)
            }

            "doctor_booking" -> {
                wvEnventPro?.showDocBooking(jsData.cmd?.params)
            }

        }
    }

}
