package com.zxhl.cms.pay

import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.net.http.SslError
import android.text.TextUtils
import android.util.Log
import android.webkit.*
import com.pay.paytypelibrary.base.OnPayResultListener
import com.pay.paytypelibrary.base.OrderInfo
import com.pay.paytypelibrary.base.PayUtil
import com.zxhl.cms.common.NetConfig
import com.zxhl.cms.utils.AppUtils
import com.zxhl.cms.utils.EventUtils
import com.zxhl.cms.utils.encry.MD5Utils
import com.zxhl.cms.utils.encry.RSAUtils
import org.json.JSONObject
import java.util.*

/**
 * @author (wangXuewei)
 * @datetime 2022-06-02 10:53 GMT+8
 * @detail :
 */
class H5PayUtil {
    interface H5AppPayCallBack {
//        fun jumpAppSuc(payType: Int);
        fun jumpAppException(e: Exception);
    }

    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，表示拦截自定义链接，但不跳转，避免弹出上面的错误页面
                }
                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)
    }


    fun loadH5AppPay(mActivity: Activity, payType: Int, url: String, callBack: H5AppPayCallBack) {
        try {
            mActivity.startActivity(Intent(Intent.ACTION_VIEW,Uri.parse(url)))
//            callBack.jumpAppSuc(payType)
        } catch (e: Exception) {
            //防止crash (如果手机上没有安装处理某个scheme开头的url的APP, 会导致crash)
            callBack.jumpAppException(e)
        }
    }


    fun loadZfbPay(mActivity: Activity) {
//        cashierPay(mActivity, "MD5", "16938552", "02020006")
//        cashierPay(mActivity, "MD5", "16938552", "02020004")

        val intent = Intent(
            Intent.ACTION_VIEW,
            Uri.parse("alipays://platformapi/startapp?appId=20000067&url=https%3A%2F%2Fmtest.dinpay.com%2Fippapi%2Fgateway%2Fapi%2Fh5ToPay%3Ftoken%3DC4E166EC5C66D7A699EA7D9B2FCEC492")
        )
        mActivity.startActivity(intent)

    }

    private val privateKey =
        "MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBALQODAYfzOEdJzlhZronHFMuzJI3aUZgB6PYgmVjMxsxatfR1hRIB7z9lKASMd8eea2jEoOa0A7a7YssgUmShJNNUG7PM2hWqbFvsIzIusUecBUtCalV0//P42gLfRvs3ZYDomHL4oh/DRa4tv4lXX1rmNxHqYVK/h3f+ba6igQbAgMBAAECgYBbw+D66hAoFwyboPmTHEXCW1KlnpoH5P9f0QO8Go+8ZzY14lsCISfYeUDbSAqk1UpcZYUVD7zEJW31hWwrDAKGljR0LbXryYVciRK7ONG3NUfUMkQLYiKeftTiRxTnRGFpPCtrOBrCyx/iz5BZih1NkMWXofkjbVnEeIED6hJzkQJBAP9uc+Itf0izQ7foGtHcDyQpmVnpQdIFy+DqQ/WMn9skEM5O3iLXfj6hfK7ItDtNOEu9OLu076VPfgVOTfpmqgMCQQC0dKTcUFf2mapZFEB8dDiMkPSVvX9XnL8/IAGqOsfz47VYHibHU1L88e3gbTf/u21W1XNXN9g5dW8JiqP3IK4JAkAcRMgUbv6YOCa1cr2NHjKayPPMzJDZQoT2xlZxFXgXk508h+PzrS+ulMasvU+dBIXHdBCUTYj8HZkP00O0A6qrAkAhBzRhaocfCHMISM+gt7jd6W4KthtHktXiHN6RJJ8SQXwge6xHUTXgO/t41ySntstFWF36+aqmoZrIGUr3YVDZAkB4dIT3de3dhRN8y6VzzcqzCkzlLjHBkV6sRe5rQNTc8QPcQCqXjzXD3Y0rHa+BZ2rCRaThKOOK6jmdJ8XvzKau"

    private fun cashierPay(
        mActivity: Activity,
        signType: String,
        merNo: String,
        productCode: String
    ) {
        var amount = ""
        if (TextUtils.isEmpty(amount)) {
            amount = "0.01"
        }
        val orderJson = JSONObject()
        try {
            orderJson.put("version", "10")
            orderJson.put("sign_type", signType)
            orderJson.put("mer_no", merNo) // 商户编号
            if ("MD5" == signType) {
                if ("6888800012098" == merNo) {
                    orderJson.put(
                        "mer_key",
                        "CMyM6TtJ04b0TlYK88+EZiBCbxytUkqZ9oCmQUgN8k5hq4HibJZQ5GTq2I/UbX+7HPq2+Qk6jzc="
                    ) // 商户密钥
                } else {
                    orderJson.put(
                        "mer_key",
                        "Xx52CDtWRH1etGu4IfFEB4OeRrnbr+EUd5VO7cBQFCqxfDl5FJcJaUjKJbHapVsyxSODBEbssNk="
                    ) // 商户密钥
                }
            } else {
                orderJson.put("mer_key", "")
            }
            orderJson.put("mer_order_no", AppUtils.getOrderNumber()) // 商户订单号
            orderJson.put("create_time", AppUtils.getOrderTime()) // 订单创建时间
            orderJson.put("expire_time", AppUtils.getOrderExpireTime()) // 订单失效时间
            orderJson.put("order_amt", amount) // 订单金额
            orderJson.put("notify_url", "http://sandcash/notify") // 回调地址
//            orderJson.put("return_url", "imeituan://www.meituan.com/takeout/browser?inner_url=https%3A%2F%2Fclick.meituan.com%2Ft%3Ft%3D1%26c%3D2%26p%3D66jPUL5zVfjj&lch=cps:mtlmwm:1:growth:202108:0:0") // 支付完成后跳转到商户页面  一键快捷不能传空
            orderJson.put("return_url", "") // 支付完成后跳转到商户页面  一键快捷不能传空
//            orderJson.put("create_ip", "172_12_12_12") // 客户端的真实IP
            orderJson.put("create_ip", "192_168_64_37") // 客户端的真实IP
            orderJson.put("goods_name", "测试商品") // 商品名称
            orderJson.put("store_id", "100001") // 门店号
            orderJson.put("product_code", productCode) // 支付产品编码
            orderJson.put("clear_cycle", "0") // 清算模式
            val payExtraJson = JSONObject()
            orderJson.put("pay_extra", payExtraJson.toString())
            orderJson.put("accsplit_flag", "NO") // 分账标识 NO无分账，YES有分账
//            orderJson.put(
//                "jump_scheme",
//                "sandcash://scpay"
//            ) //参数值可以自定义，和android:scheme、android:host保持一致
            orderJson.put(
                "jump_scheme",
                "xxsqshop://rights_detail"
            )
//            orderJson.put(
//                "jump_scheme",
//                "imeituan://www.meituan.com"
//            )
            orderJson.put("activity_no", "") //营销活动编码
            orderJson.put("benefit_amount", "") //优惠金额
            orderJson.put("extend", "123") //扩展字段，非必传
            orderJson.put(
                "limit_pay",
                "5"
            ) //微信传1屏蔽信用卡，支付宝传5屏蔽部分信用卡以及花呗，支付宝传4屏蔽花呗，支付宝传1屏蔽部分信用卡，银联不支持屏蔽   不参与签名
            //            orderJson.put("channel_mid", ""); //非必传
            val extendParamJson = JSONObject()
            val payerVerificationInfoJson = JSONObject()
            payerVerificationInfoJson.put("needCheckFlag", "0")
            payerVerificationInfoJson.put("name", "123") //姓名
            payerVerificationInfoJson.put("certNo", "12321321312312321") //证件号
            payerVerificationInfoJson.put("certType", "01")
            extendParamJson.put("payerVerificationInfo", payerVerificationInfoJson.toString())
//            orderJson.put("extend_params", extendParamJson.toString()) //支付宝实名信息字段，非必传，不参与签名
            val signKey: String
            signKey = if ("6888800012098" == merNo) {
                "PZdBctMl2c0ma9b9+25FBgH2twQBTmhzn/qNSS6xANEGMqBi/S9IhyhDi1aBb1H9gxmcvjxmMk305pcUaISEmjm6gacvTBPHj0zSgRk//7ZYF0Go/X03BZt5mTdcmslgH81l03NMtaRixuz+UKFTiw=="
            } else {
                "UZfTHiut04dIJSOqwT2KVn6Bf4OBGBrUvjaUibKc5UFinTz/EY8j/5P1nOAZxsgRJKC6qKPhB7NJAPxc7RyrM8BDgM+UhiKrzR/MvvQhFMgTDfQFoDZYEYW2z+pi4zany5c0bz6FNidixuz+UKFTiw=="
            }

            //计算签名
            val signMap: MutableMap<String, String> = HashMap()
            signMap["version"] = orderJson.getString("version")
            signMap["mer_no"] = orderJson.getString("mer_no")
            if ("MD5" == signType) {
                signMap["mer_key"] = orderJson.getString("mer_key")
            }
            signMap["mer_order_no"] = orderJson.getString("mer_order_no")
            signMap["create_time"] = orderJson.getString("create_time")
            signMap["order_amt"] = orderJson.getString("order_amt")
            signMap["notify_url"] = orderJson.getString("notify_url")
//            signMap["return_url"] = orderJson.getString("return_url")
            signMap["create_ip"] = orderJson.getString("create_ip")
            signMap["store_id"] = orderJson.getString("store_id")
            signMap["pay_extra"] = orderJson.getString("pay_extra")
            signMap["accsplit_flag"] = orderJson.getString("accsplit_flag")
            signMap["sign_type"] = orderJson.getString("sign_type")
            if (!TextUtils.isEmpty(orderJson.optString("activity_no"))) {
                signMap["activity_no"] = orderJson.getString("activity_no")
            }
            if (!TextUtils.isEmpty(orderJson.optString("benefit_amount"))) {
                signMap["benefit_amount"] = orderJson.getString("benefit_amount")
            }
            if (!TextUtils.isEmpty(orderJson.optString("extend"))) {
                signMap["extend"] = orderJson.getString("extend")
            }
            if (!TextUtils.isEmpty(orderJson.optString("channel_mid"))) {
                signMap["channel_mid"] = orderJson.getString("channel_mid")
            }

            val list: List<Map.Entry<String, String>> = MD5Utils.sortMap(signMap)
            val signBuilder = StringBuilder()
            for ((key, value) in list) {
                signBuilder.append(key)
                signBuilder.append("=")
                signBuilder.append(value)
                signBuilder.append("&")
            }

            if ("RSA" == signType) {
                var signData = signBuilder.toString()
                signData = signData.substring(0, signData.length - 1)
                orderJson.put("sign", RSAUtils.sign(signData, privateKey)) // RSA签名结果
            } else {
                signBuilder.append("key")
                signBuilder.append("=")
                signBuilder.append(signKey)
                Log.d("wxw", "signBuilder.toString():${signBuilder.toString()}")
                orderJson.put(
                    "sign",
                    MD5Utils.getMD5(signBuilder.toString()).toUpperCase()
                ) // MD5签名结果
            }

        } catch (e: Exception) {

        }
        Log.d("PayUtil", "orderJson:${orderJson.toString()}")

        PayUtil.CashierPaySingle(mActivity, orderJson.toString(), object : OnPayResultListener {
            override fun onSuccess(p0: OrderInfo?) {

            }

            override fun onError(p0: String?) {
                Log.e("PayUtil", "payError:${p0}")
            }

        })
    }

//    fun sdPayUtil(mActivity: Activity, orderJson: String, callBack: SdPayCallBack) {
//        Log.e("PayUtil", "orderJson:${orderJson}")
//        PayUtil.CashierPaySingle(mActivity, orderJson, object : OnPayResultListener {
//            override fun onSuccess(p0: OrderInfo?) {
//
//            }
//
//            override fun onError(p0: String?) {
//                Log.e("PayUtil", "payError:${p0}")
//            }
//
//        })
//    }
}