package com.game.gamecenter.alipay

import android.app.Activity
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.webkit.CookieManager
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.LinearLayout
import com.alipay.sdk.app.PayTask

class H5PayActivity : Activity() {

    private var _webView: WebView? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val layout = LinearLayout(applicationContext)
        val params =
            LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT)
        layout.orientation = LinearLayout.VERTICAL
        setContentView(layout)

        _webView = WebView(applicationContext)
        params.weight = 1F
        _webView?.let {
            it.visibility = View.VISIBLE
            layout.addView(it, params)

            initWebView(it)
        }
    }

    private fun initWebView(webView: WebView) {
        with(webView.settings) {
            javaScriptEnabled = true
            javaScriptCanOpenWindowsAutomatically = true
            CookieManager.getInstance().setAcceptThirdPartyCookies(webView, true)
            domStorageEnabled = true
        }
        with(webView) {
            webViewClient = MyWebViewClient()
            loadUrl("url")
        }
    }

    private inner class MyWebViewClient : WebViewClient() {
        override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
            if (!(url.startsWith("http") || url.startsWith("https"))) {
                return true
            }

            /**
             * 推荐采用的新的二合一接口(payInterceptorWithUrl),只需调用一次
             */
            val task = PayTask(this@H5PayActivity)
            val isIntercepted = task.payInterceptorWithUrl(url, true) { result ->
                val url = result.getReturnUrl()
                if (!TextUtils.isEmpty(url)) {
                    this@H5PayActivity.runOnUiThread {
                        view.loadUrl(url)
                    }
                }
            }

            /**
             * 判断是否成功拦截
             * 若成功拦截，则无需继续加载该URL；否则继续加载
             */
            if (!isIntercepted) {
                view.loadUrl(url)
            }
            return true
        }
    }
}