package com.zxhl.cms.pay

import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.net.http.SslError
import android.util.Log
import android.view.View
import android.webkit.*
import com.zxhl.cms.common.NetConfig
import com.zxhl.cms.utils.EventUtils
import kotlinx.android.synthetic.main.activity_member.*

/**
 * @author (wangXuewei)
 * @datetime 2022-06-02 10:53 GMT+8
 * @detail :
 */
class H5PayUtil {

    interface H5PayCallBack {
        fun jumpZfbAppSuc();
        fun jumpZfbAppException(e: Exception);
        fun loadH5Error1(errorStr: String);
        fun loadH5Error2(errorStr: String);
    }

    fun loadH5PayWeb(
        mActivity: Activity,
        h5WebVIew: WebView,
        order: String,
        callBack: H5PayCallBack
    ) {
        val webSettings = h5WebVIew.settings
        //如果访问的页面中要与Javascript交互，则webview必须设置支持Javascript
        webSettings.javaScriptEnabled = true
        //设置自适应屏幕，两者合用
        webSettings.useWideViewPort = true //将图片调整到适合webview的大小
        webSettings.loadWithOverviewMode = true // 缩放至屏幕的大小
        //其他细节操作
        webSettings.cacheMode = WebSettings.LOAD_NO_CACHE //关闭webview中缓存
        webSettings.allowFileAccess = true //设置可以访问文件
        webSettings.javaScriptCanOpenWindowsAutomatically = true //支持通过JS打开新窗口
        webSettings.loadsImagesAutomatically = true //支持自动加载图片
        webSettings.defaultTextEncodingName = "utf-8" //设置编码格式
        webSettings.domStorageEnabled = true
        webSettings.allowFileAccessFromFileURLs = true;
        webSettings.allowUniversalAccessFromFileURLs = true;
        h5WebVIew?.setDownloadListener { url, userAgent, contentDisposition, mimetype, contentLength ->
            var intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
            mActivity.startActivity(intent);
        }
        h5WebVIew?.webViewClient = object : WebViewClient() {
            override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
                if (url == null) return false
                try {
                    if (url.startsWith("alipays://") //支付宝
                    ) {
                        val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
                        mActivity.startActivity(intent)
                        callBack.jumpZfbAppSuc()
                        return true
                    }
                } catch (e: Exception) {
                    //防止crash (如果手机上没有安装处理某个scheme开头的url的APP, 会导致crash)
                    callBack.jumpZfbAppException(e)
                    return true //没有安装该app时，返回true，表示拦截自定义链接，但不跳转，避免弹出上面的错误页面
                }
                view?.loadUrl(url)
                return false;
            }

            override fun onPageFinished(view: WebView?, url: String?) {
                EventUtils.onEvent("url_update", "url: ${url}")
                super.onPageFinished(view, url)
                if (url?.contains(NetConfig.H5.WEB_URL_H5_PAY) == true) {
                    h5WebVIew?.loadUrl("javascript:loadPayHtml('$order')");
                }
            }

            override fun onReceivedSslError(
                view: WebView?,
                handler: SslErrorHandler?,
                error: SslError?
            ) {
                // 接受所有网站的证书，忽略SSL错误，执行访问网页
                handler?.proceed();
            }

            override fun onReceivedError(
                view: WebView?,
                request: WebResourceRequest?,
                error: WebResourceError?
            ) {
                super.onReceivedError(view, request, error)
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
                    callBack.loadH5Error1("code: ${error?.errorCode} desc: ${error?.description}")
                } else {
                    callBack.loadH5Error1(error.toString())
                }
            }

            override fun onReceivedHttpError(
                view: WebView?,
                request: WebResourceRequest?,
                errorResponse: WebResourceResponse?
            ) {

                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
                    if (request?.url?.path?.endsWith("/favicon.ico") == true) {

                    } else {
                        callBack.loadH5Error2("code:" + errorResponse?.statusCode.toString() + " url:${request?.url}")
                    }
                } else {
                    callBack.loadH5Error2(errorResponse.toString())
                }
                super.onReceivedHttpError(view, request, errorResponse)
            }
        }
        h5WebVIew.loadUrl(NetConfig.H5.WEB_URL_H5_PAY)
    }

}