package com.zxhl.cms.pay

import android.app.Activity
import android.app.Dialog
import android.content.Intent
import android.net.Uri
import android.net.http.SslError
import android.os.Handler
import android.util.Log
import android.view.Gravity
import android.view.View
import android.webkit.*
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.zxhl.cms.R
import com.zxhl.cms.common.Constant
import com.zxhl.cms.common.NetConfig
import com.zxhl.cms.net.SettingPreference
import com.zxhl.cms.net.model.box.AppInEntity
import com.zxhl.cms.net.model.uc.PayResultEntity
import com.zxhl.cms.net.model.video.MemberEntity
import com.zxhl.cms.utils.*
import com.zxhl.cms.widget.CenterDialog
import com.zxhl.cms.widget.LoadingDialog
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.functions.Consumer

/**
 * @author (wangXuewei)
 * @datetime 2022-04-25 13:47 GMT+8
 * @detail :
 */
object PayDialog : PayContract.View {

    private var payResultObservable: Observable<PayResultEntity>? = null
    private var mLoading: LoadingDialog? = null
    private var mPresenter: PayContract.Presenter? = null
    private var pay_type: Int? = 0

    private var id_pay_web_view: WebView? = null;
    private var id_rl_zfb_pay: RelativeLayout? = null;
    private var id_img_ali: ImageView? = null;
    private var id_img_min_choose: ImageView? = null;
    private var id_tv_zfb_1: TextView? = null;
    private var id_rl_min_pay: RelativeLayout? = null;
    private var id_tv_zfb_2: TextView? = null;
    private var mDialog: Dialog? = null;

    private var mPayFunAdapter: PaymentFunAdapter? = null;
    private var mActivity: Activity? = null
    private var mHandler: Handler = Handler {
        when (it.what) {
            0 -> {
                if (mLoading != null) {
                    mLoading?.setResult(false, "取消支付", 1000)
                }
            }
        }
        false
    }

    private var mPayCallBack: AdCallback<Int>? = null
    fun showPayDialog(
        context: Activity,
        goodsImg: String,
        goodsName: String,
        goodsPrice: String,
        payPrice: String,
        goodsNum: String, payCallBack: AdCallback<Int>
    ) {
        if (mDialog == null) {
            mDialog = Dialog(context, R.style.CenterCompatDialogTheme)
        }
        mActivity = context
        mPayCallBack = payCallBack
        val mDialogView =
            CenterDialog.showBottomDialog(
                R.layout.dialog_pay_view,
                context,
                mDialog!!,
                0,
                Gravity.BOTTOM
            )

        mLoading = LoadingDialog.getLoadingDialog(
            context,
            context.getString(R.string.wait_ing),
            false,
            false
        )

        val tv_goodsMainImg = mDialogView.findViewById<ImageView>(R.id.id_goods_main_img)
        val tv_goodsName = mDialogView.findViewById<TextView>(R.id.id_tv_box_goods_name)
        val tv_goodsPrice = mDialogView.findViewById<TextView>(R.id.id_tv_box_goods_price)
        val tv_goodsNum = mDialogView.findViewById<TextView>(R.id.id_tv_box_goods_num)
        val tv_goods_pay_btn_price = mDialogView.findViewById<TextView>(R.id.id_activity_member_btn)
        val id_rcl_payment_list = mDialogView.findViewById<RecyclerView>(R.id.id_rcl_payment_list)

        id_pay_web_view = mDialogView.findViewById<WebView>(R.id.id_pay_web_view)
        id_rl_zfb_pay = mDialogView.findViewById<RelativeLayout>(R.id.id_rl_zfb_pay)
        id_img_ali = mDialogView.findViewById<ImageView>(R.id.id_img_ali)
        id_img_min_choose = mDialogView.findViewById<ImageView>(R.id.id_img_min_choose)
        id_tv_zfb_1 = mDialogView.findViewById<TextView>(R.id.id_tv_zfb_1)
        id_rl_min_pay = mDialogView.findViewById<RelativeLayout>(R.id.id_rl_min_pay)
        id_tv_zfb_2 = mDialogView.findViewById<TextView>(R.id.id_tv_zfb_2)


        if (!context.isFinishing) {
            Glide.with(context).load(goodsImg).into(tv_goodsMainImg)
        }

        tv_goodsName.text = goodsName
        tv_goodsPrice.text = "¥${goodsPrice}"
        tv_goods_pay_btn_price.text = "${payPrice}"
        tv_goodsNum.text = "x${goodsNum}"
        mDialogView.findViewById<LinearLayout>(R.id.id_ll_pay_bottom).setOnClickListener {
            if (pay_type == 0) {
                Utils.showToast(context, "请选择支付类型")
                return@setOnClickListener
            }
            mLoading?.setLoading("请稍后")
            mLoading?.show()
            if (pay_type == 1) {
                mPresenter?.requestAliPay(
                    context,
                    payPrice,
                    pay_type.toString(),
                    "6"
                )
            } else if (pay_type == 13 || pay_type == 21) {
                mPresenter?.requestMiniProgrom(
                    payPrice,
                    pay_type.toString(),
                    "6"
                )
            } else {
                Utils.showToast(context, "暂不支持")
            }
        }

        mPayFunAdapter = PaymentFunAdapter(
            context
        ) { view, position, data ->
            pay_type = data.type
            mPayFunAdapter?.setPosition(position)
        }
        id_rcl_payment_list.layoutManager = LinearLayoutManager(context)
        id_rcl_payment_list.adapter = mPayFunAdapter


        mDialogView.findViewById<LinearLayout>(R.id.id_ll_service).setOnClickListener {
            JumpUtils.webJump("增值服务协议", NetConfig.H5.WEB_URL_ZENGZHI_SERVICE)
        }
        mDialogView.findViewById<ImageView>(R.id.id_pay_dialog_close_btn).setOnClickListener {
            mDialog?.dismiss()
        }

        mDialog?.setOnDismissListener {
            resetPay()
            mDialog = null
            mLoading = null
        }
        mPresenter = PayPresenter(this)
        mPresenter?.appInfo()
        initPay()
        mDialog?.setCancelable(false)
        mDialog?.setCanceledOnTouchOutside(false)
        if (!context.isFinishing) {
            mDialog?.show()
        }
    }

    fun initPay() {
        payResultObservable = RxBus.get().register(Constant.PAY_RESULT, PayResultEntity::class.java)
        payResultObservable?.observeOn(AndroidSchedulers.mainThread())
            ?.subscribe(Consumer<PayResultEntity> { obj ->
                MainLooper?.get()?.postDelayed(Runnable {
                    mHandler?.removeCallbacksAndMessages(null)
                }, 1000)
                //println("verifyPay payResultObservable------------------------------- order:${obj.txt}")
                if (obj.isPaySuc) {
                    EventUtils.onEvent("pay_page_pay_query_order", "付款成功")
                    mPresenter?.verifyPay(obj.txt, obj.payType)
                } else {
                    //支付宝支付
                    if (obj.payType == 1) {
                        if (obj.payStatus == "6001") {
                            EventUtils.onEvent("zfb_pay_cancel")
                        } else {
                            EventUtils.onEvent("zfb_pay_error", obj.payStatus + " msg:" + obj.txt)
                        }
                    } else {
                        EventUtils.onEvent("wx_pay_error", obj.txt)
                    }
                    showResultLoading(false)
                }
            }, Consumer<Throwable> { })
    }

    private fun resetPay() {
        if (payResultObservable != null)
            RxBus.get().unregister(Constant.PAY_RESULT, payResultObservable!!)
    }

    private fun showResultLoading(isPaySuc: Boolean) {
        if (isPaySuc) {
            mLoading?.setResult(true, "支付成功", 1000)
            mDialog?.dismiss()
            mPayCallBack?.onResult(200, 0)
        } else {
            mLoading?.setResult(false, "支付失败", 1000)
            mPayCallBack?.onResult(200, -1)
        }
    }

    override fun updatePriceList(data: List<MemberEntity.ProductDetail>) {

    }

    override fun verifyOrderFail(errorMsg: String) {
        showResultLoading(false)
    }

    override fun requestOrderSuc() {
        mLoading?.setLoading("正在支付")
    }

    override fun requestH5OrderSuc(form: String) {
        if (form.isEmpty()) {
            EventUtils.onEvent("h5_pay_error")
            showResultLoading(false)
        } else {
            loadH5Pay(form)
        }
    }

    override fun verifyOrderSuc(orsder: String) {
        UserDataUtils.updateUserInfo { _, _ ->
            showResultLoading(true)
        }
    }

    override fun setCanInvest(boolean: Boolean?) {

    }

    override fun setOrderNo(order: String?) {

    }

    override fun setAppInfo(result: AppInEntity?) {
        if (result != null && !result.pay_config_v2.isNullOrEmpty()) {
            mPayFunAdapter?.clear()
            mPayFunAdapter?.appendToList(result.pay_config_v2)
            for (i in result.pay_config_v2!!.indices) {
                if (result?.pay_config_v2!![i].open == 1) {
                    pay_type = result?.pay_config_v2!![i].type
                    mPayFunAdapter?.setPosition(i)
                    break
                }
            }
        }
    }

    fun OnResumeCheck() {
        if (mDialog == null) {
            mLoading?.setResult(false, "取消支付", 1000)
        } else {
            if (mDialog?.isShowing == true) {
                if (pay_type == PayActivity.MIN_PAY_PROGRAM || pay_type == PayActivity.H5_PAY) {
                    //如果是敏支付
                    mPresenter?.verifyPay(
                        SettingPreference.getOutTradeNo(),
                        pay_type!!
                    )
                } else {
                    mLoading?.setResult(false, "取消支付", 1000)
                }
            } else {
                mLoading?.setResult(false, "取消支付", 1000)
            }
        }
    }

    private fun loadH5Pay(form: String) {
//        id_pay_web_view?.visibility = View.VISIBLE
        Log.d("wxw", "startTime" + System.currentTimeMillis())
        val webSettings = id_pay_web_view?.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;

        id_pay_web_view?.webViewClient = object : WebViewClient() {
            override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
                Log.e("WXW", "dURL" + url.toString())
                if (url == null) return false
                try {
                    if (url.startsWith("alipays://") //支付宝
                    ) {
                        val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
                        mActivity?.startActivity(intent)
                        return true
                    }
                } catch (e: Exception) { //防止crash (如果手机上没有安装处理某个scheme开头的url的APP, 会导致crash)
                    EventUtils.onEvent("h5_open_zfb_error", e.toString())
                    showResultLoading(false)
                    return true //没有安装该app时，返回true，表示拦截自定义链接，但不跳转，避免弹出上面的错误页面
                }
                //处理http和https开头的url
                view?.loadUrl(url)
                return false
            }

            override fun onPageFinished(view: WebView?, url: String?) {
                Log.e("WXW", "cURL" + url.toString())
                Log.d("wxw", "EndTime" + System.currentTimeMillis())
                super.onPageFinished(view, url)
                if (url?.contains(NetConfig.H5.WEB_URL_H5_PAY) == true) {
                    id_pay_web_view?.loadUrl("javascript:loadPayHtml('$form')");
                }
            }

            override fun onReceivedSslError(
                view: WebView?,
                handler: SslErrorHandler?,
                error: SslError?
            ) {
                super.onReceivedSslError(view, handler, error)
                EventUtils.onEvent("h5_pay_error0", error.toString())
                showResultLoading(false)
            }

            override fun onReceivedError(
                view: WebView?,
                request: WebResourceRequest?,
                error: WebResourceError?
            ) {
                super.onReceivedError(view, request, error)
                EventUtils.onEvent("h5_pay_error1", error.toString())
                showResultLoading(false)
            }

            override fun onReceivedHttpError(
                view: WebView?,
                request: WebResourceRequest?,
                errorResponse: WebResourceResponse?
            ) {
                super.onReceivedHttpError(view, request, errorResponse)
                EventUtils.onEvent("h5_pay_error2", errorResponse?.statusCode.toString())
                showResultLoading(false)
            }
        }
        id_pay_web_view?.loadUrl(NetConfig.H5.WEB_URL_H5_PAY)

    }

}