package com.yidianling.muse.activity

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.content.res.Resources
import android.net.Uri
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.webkit.WebResourceRequest
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import com.ydl.utils.WebUrlParamsUtils
import com.ydl.webview.H5Params
import com.ydl.webview.IJavascriptHandler
import com.ydl.webview.TellData
import com.ydl.webview.WebModularServiceUtils.Companion.getWebService
import com.ydl.ydlcommon.base.BaseActivity
import com.ydl.ydlcommon.event.MeditationEvent
import com.yidianling.common.tools.LogUtil
import com.yidianling.muse.R
import de.greenrobot.event.EventBus
import kotlinx.android.synthetic.main.dialog_choose_music.*
import org.json.JSONException
import org.json.JSONObject

/**
 * Created by Ykai on 2022/5/26.
 */
class ChooseMusicActivity : BaseActivity()  {
    private val TAG = ChooseMusicActivity::class.java.simpleName
    protected var jtoJHandle: IJavascriptHandler? = null

    /*** 路由传递过来的参数 */
    val ROUTER_PARAMS = "routerParam"
    companion object{
        const val PARAMS = "h5Params"
        /***接收参数 */
        private var h5Params: H5Params? = null

        fun launch(context: Context, h5Params:H5Params) {
            Intent(context, ChooseMusicActivity::class.java).apply {
                putExtra(PARAMS, h5Params)
                context.startActivity(this)
            }
        }
    }

    override fun initDataAndEvent() {
        //正常获取入参
    }

    override fun layoutResId(): Int {
        return R.layout.dialog_choose_music
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        getParam()
        var tellData = TellData()
        jtoJHandle = getWebService().getJavascripHandler(this, null, tellData.also { tellData = it })

        initView()
    }

    @SuppressLint("SetJavaScriptEnabled", "JavascriptInterface")
    private fun initView() {
        // 移除有漏洞的系统接口
        wv_choose_music.removeJavascriptInterface("searchBoxJavaBridge_")
        wv_choose_music.removeJavascriptInterface("accessibility")
        wv_choose_music.removeJavascriptInterface("accessibilityTraversal")
        val mWebSettings: WebSettings = wv_choose_music.settings


        mWebSettings.javaScriptEnabled = true //支持js
        mWebSettings.defaultTextEncodingName = "GBK" //设置字符编码
        mWebSettings.domStorageEnabled = true
        mWebSettings.textZoom = 100 //设置字体不跟随字体变化而变化
        mWebSettings.allowFileAccessFromFileURLs = true
        mWebSettings.blockNetworkImage = false // 解决图片不显示
        mWebSettings.mixedContentMode = WebSettings.LOAD_DEFAULT
        wv_choose_music.scrollBarStyle = View.SCROLLBARS_INSIDE_OVERLAY //滚动条风格，为0指滚动条不占用空间，直接覆盖在网页上
        wv_choose_music.addJavascriptInterface(jtoJHandle, "javascriptHandler")

        val url = setUrlHeightParams(h5Params?.url)
        LogUtil.e(url)
        loadUrl(url,wv_choose_music)


        wv_choose_music.webViewClient=object : WebViewClient(){
            override fun onPageFinished(view: WebView?, url: String?) {
                super.onPageFinished(view, url)
            }
            override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean {
                loadUrl(request.url.toString(), view)
                return true
            }
        }

        ll_close.setOnClickListener {
            finish()
        }
    }
    private fun getParam() {
        if (null != intent) {
            //正常获取入参
            h5Params = intent.getSerializableExtra(PARAMS) as H5Params
            //路由传递的入参
            if (intent.hasExtra(ROUTER_PARAMS)) {
                val json = intent.getStringExtra(ROUTER_PARAMS)
                try {
                    val jsonObject = JSONObject(json)
                    h5Params = H5Params(jsonObject.getString("url"), "")
                } catch (e: JSONException) {
                    e.printStackTrace()
                }
            }
        }
    }

    fun switchSound(
        mediaId: Int, meditationId: Long, meditationType: Int, businessType: Int,
        buried: String?, mediaUrl: String?, mediaCoverUrl: String?,
        title: String?, desc: String?, status: Int
    ) {
        val event = MeditationEvent(
            mediaId, meditationId, meditationType, businessType,
            status, buried!!, mediaUrl!!, mediaCoverUrl!!, title!!, desc!!
        )
        EventBus.getDefault().post(event)
    }

    fun loadUrl(url: String?,web:WebView) {
        if (TextUtils.isEmpty(url)) {
            return
        }
        val resultUrl = if (h5Params?.suffix == true) WebUrlParamsUtils.getSuffix(
            url,
            jtoJHandle?.getUriAppendSuffix()
        ) else url

        Log.e(TAG, resultUrl)
        web.loadUrl(resultUrl)
    }

    /**
     * 专家详情页改版 需要url后面拼接状态栏高度 并且隐藏导航栏
     *
     * @param url
     * @return
     */
    private fun setUrlHeightParams(url: String?): String {
        var resultUrl: String? = url
        try {
            val uri = Uri.parse(url)
            val host = uri.host
            if (!TextUtils.isEmpty(host) && host.contains("nodeapi.ydl")) {
                //马亮的需求，在nodeapi.ydl.com 地址后面拼上公共参数，用于判断是否为app

                //马亮的需求，在nodeapi.ydl.com 地址后面拼上公共参数，用于判断是否为app
                val uriAppendSuffix = jtoJHandle?.getUriAppendSuffix()
                resultUrl = WebUrlParamsUtils.getSuffix(url, uriAppendSuffix)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return pinjie(resultUrl)
    }

    private fun pinjie(jumpUrl: String?): String {
        var useUrl = StringBuffer().append(jumpUrl).toString()
        val res: Resources = resources
        val doctorUrlArray = res.getStringArray(R.array.platform_doctorUrls)
        for (url in doctorUrlArray) {
            if (useUrl.contains(url)) {
                var lastUrl = useUrl.replace(url.toRegex(), "")
                if (lastUrl.contains("?")) {
                    lastUrl = lastUrl.substring(0, lastUrl.indexOf("?"))
                }
                try {
                    //不报错就说明可以转成long，就说明是专家详情页地址
                    lastUrl.toLong()
                    if (!lastUrl.contains("/")) {
                        if (useUrl.endsWith("?")) {
                            useUrl = useUrl.substring(0, useUrl.indexOf("?"))
                        }
                    }
                } catch (e: NumberFormatException) {
                    e.printStackTrace()
                }
            }
        }
        return useUrl
    }
}