package com.yidianling.uikit.custom.widget.expertConsultService.view

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.view.View
import android.widget.RelativeLayout
import com.tencent.smtt.export.external.interfaces.JsResult
import com.tencent.smtt.sdk.*
import com.ydl.utils.WebUrlParamsUtils
import com.ydl.webview.ProgressWebView
import com.ydl.webview.TellData
import com.ydl.webview.WebModularServiceUtils
import com.ydl.ydlcommon.base.config.HttpConfig
import com.yidianling.common.tools.RxDeviceTool
import com.yidianling.common.tools.ToastUtil
import com.yidianling.im.R
import com.yidianling.uikit.custom.http.response.ServiceItemBean
import com.yidianling.uikit.custom.widget.expertConsultService.callback.ConsultServiceViewCallback

class ExpertConsultWebview : RelativeLayout {
    private var doctorID: String
    private lateinit var productBean: ServiceItemBean.ProductsBean
    private  var cateID: Int = 0
    private var jumpUrl = ""
    private lateinit var wv_content:ProgressWebView
    constructor(context: Context, doctorID: String) : super(context) {
        mContext = context
        this.doctorID = doctorID
        initView()
    }

    private var mContext: Context? = null
    private fun initView() {
        val mWidth: Int = RxDeviceTool.getScreenWidth(mContext)
        val mHeight: Int = LayoutParams.MATCH_PARENT
        val params = LayoutParams(
            mWidth,
            mHeight
        )
        params.height = mHeight
        layoutParams = params
        var view = View.inflate(mContext, R.layout.im_expert_consult_webview_view, this)
        wv_content= view.findViewById<ProgressWebView>(R.id.wv_content)
        webViewInit(wv_content, doctorID)
    }

    fun setData(productBean: ServiceItemBean.ProductsBean) {
        this.productBean = productBean
//        this.cateID=cateid
        jumpUrl =
            HttpConfig.MH5_URL + "wb/product/chat/template?doctorId=${doctorID}&cateId=${productBean.getcatenewId()}&productId=${productBean.productDto.id}"
        val jtoJHandle = WebModularServiceUtils.getWebService()
            .getJavascripHandler(mContext as Activity, tellData = TellData())
        val url = WebUrlParamsUtils.getSuffix(jumpUrl, jtoJHandle.getUriAppendSuffix())
        wv_content.loadUrl(url)
    }

    private fun shouldOverridePayUrl(view: WebView, url: String): Boolean {
        if (url.startsWith("weixin://")) {
            return try {
                mContext?.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url)))
                true
            } catch (e: java.lang.Exception) {
                // 防止手机没有安装处理某个 scheme 开头的 url 的 APP 导致 crash
                ToastUtil.toastShort("该手机没有安装微信")
                true
            }
        } else if (url.startsWith("alipays://") || url.startsWith("alipay")) {
            return try {
                mContext?.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url)))
                true
            } catch (e: java.lang.Exception) {
                // 防止手机没有安装处理某个 scheme 开头的 url 的 APP 导致 crash
                // 启动支付宝 App 失败，会自行跳转支付宝网页支付
                true
            }
        }

        // 处理普通 http 请求跳转
//        if (!(url.startsWith("http") || url.startsWith("https"))) {
//            return true;
//        }

        // 处理微信 H5 支付跳转时验证请求头 referer 失效
        // 验证不通过会出现“商家参数格式有误，请联系商家解决”
        if (url.contains("wx.tenpay.com")) {

            // 申请微信 H5 支付时填写的域名
            // 比如经常用来测试网络连通性的 http://www.baidu.com
            val parse = Uri.parse(url)
            //从url 中获取 域名信息
            val redirectUrlStr = parse.getQueryParameter("redirect_url")
            val redirectUrl = Uri.parse(redirectUrlStr)
            // 申请微信 H5 支付时填写的域名
            val referer = redirectUrl.scheme + "://" + redirectUrl.host

            // 兼容 Android 4.4.3 和 4.4.4 两个系统版本设置 referer 无效的问题
            return if ("4.4.3" == Build.VERSION.RELEASE
                || "4.4.4" == Build.VERSION.RELEASE
            ) {
                // 返回 false 由系统 WebView 自己处理该 url
                false
            } else {
                // HashMap 指定容量初始化，避免不必要的内存消耗
                val map = HashMap<String, String>(1)
                map["Referer"] = referer
                view.loadUrl(url, map)
                true
            }
        } else if (url.contains("alipay")) {
            return false
        }
        return false
    }

    fun webViewInit(wv_content: ProgressWebView, doctorID: String) {
        val setting: WebSettings = wv_content?.settings!!
        //支持js
        //支持js
        setting.setJavaScriptEnabled(true)
        //设置字符编码
        //设置字符编码
        setting.setDefaultTextEncodingName("GBK")
        setting.setDomStorageEnabled(true)
        val appCachePath: String = mContext?.getCacheDir()?.getAbsolutePath().toString()
        setting.setAppCachePath(appCachePath)
        setting.setAllowFileAccessFromFileURLs(true)
        setting.setAppCacheEnabled(true)
        setting.setAllowFileAccess(true)
        setting.setBlockNetworkImage(false)

        wv_content!!.scrollBarStyle = View.SCROLLBARS_INSIDE_OVERLAY //滚动条风格，为0指滚动条不占用空间，直接覆盖在网页上
        val jtoJHandle = WebModularServiceUtils.getWebService()
            .getJavascripHandler(mContext as Activity, tellData = TellData())

        wv_content!!.addJavascriptInterface(jtoJHandle, "javascriptHandler")
        val url = WebUrlParamsUtils.getSuffix(jumpUrl, jtoJHandle.getUriAppendSuffix())
        wv_content.loadUrl(url)

        wv_content.webViewClient = object : WebViewClient() {
            override fun shouldOverrideUrlLoading(webview: WebView, url: String?): Boolean {
                if (url.isNullOrBlank()) return false
                return shouldOverridePayUrl(webview, url)
            }
        }
        wv_content.webChromeClient = object : WebChromeClient() {
            override fun onJsAlert(
                webView: WebView,
                s: String,
                s1: String,
                jsResult: JsResult
            ): Boolean {
                return super.onJsAlert(webView, s, s1, jsResult)
            }

            override fun onProgressChanged(view: WebView, newProgress: Int) {
                super.onProgressChanged(view, newProgress)
            }

            override fun onReceivedTitle(view: WebView, title: String) {
                super.onReceivedTitle(view, title)
            }

            // For Android < 3.0
            fun openFileChooser(valueCallback: ValueCallback<Uri?>) {
            }

            // For Android  >= 3.0
            fun openFileChooser(valueCallback: ValueCallback<*>, acceptType: String?) {
            }

            //For Android  >= 4.1
            override fun openFileChooser(
                valueCallback: ValueCallback<Uri>,
                acceptType: String,
                capture: String
            ) {
            }

            // For Android >= 5.0
            override fun onShowFileChooser(
                webView: WebView,
                filePathCallback: ValueCallback<Array<Uri>>,
                fileChooserParams: FileChooserParams
            ): Boolean {
                return true
            }
        }
    }
}