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_rl_h5_pay_view: RelativeLayout? = null;
    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)
                }
            }
            1 -> {
                if (mLoading != null) {
                    mLoading?.setResult(false, "支付异常", 0)
                }
                id_rl_h5_pay_view?.visibility = View.VISIBLE
                EventUtils.onEvent("h5_pay_end")
            }
            2 -> {
                if (mLoading != null) {
                    mLoading?.setResult(false, "支付异常", 0)
                }
                id_rl_h5_pay_view?.visibility = View.VISIBLE
            }
        }
        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_rl_h5_pay_view = mDialogView.findViewById<RelativeLayout>(R.id.id_rl_h5_pay_view)
        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)
        mDialogView.findViewById<ImageView>(R.id.id_img_close_pay_web).setOnClickListener {
            id_rl_h5_pay_view?.visibility = View.GONE
        }

        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 == PaymentConfig.MIN_PAY_PROGRAM || pay_type == PaymentConfig.H5_PAY || pay_type == PaymentConfig.ZFB_H5_PAY || pay_type == PaymentConfig.WX_H5_PAY|| pay_type == PaymentConfig.HUI_FU_H5_PAY1|| pay_type == PaymentConfig.HUI_FU_H5_PAY2) {
                mPresenter?.requestMiniProgrom(
                    payPrice,
                    pay_type.toString(),
                    "6"
                )
            } else if (pay_type == PaymentConfig.SD_PAY) {
                mPresenter?.requestSdPay(
                    "xxsqshop://goodsdetail",
                    context,
                    payPrice,
                    pay_type.toString(),
                    "6"
                )
            } else {
                Utils.showToast(context, "暂不支持")
                mLoading?.setLoading("支付取消")
            }
        }

        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 {
            if (mActivity == null) {
                return
            }
            if (mActivity?.isDestroyed == true) {
                return
            }
            if (pay_type == PaymentConfig.H5_PAY) {
                mHandler.sendEmptyMessageDelayed(1, 8000)
                H5PayUtil().loadH5PayWeb(
                    mActivity!!,
                    id_pay_web_view!!,
                    form,
                    object : H5PayUtil.H5PayCallBack {
                        override fun jumpZfbAppSuc() {
                            id_rl_h5_pay_view?.visibility = View.GONE
                            EventUtils.onEvent("h5_open_zfb_suc")
                            mHandler.removeMessages(1)
                        }

                        override fun jumpZfbAppException(e: Exception) {
                            EventUtils.onEvent("h5_open_zfb_error", e.toString())
                            mHandler.removeMessages(1)
                            mHandler.sendEmptyMessage(2)
                        }

                        override fun loadH5Error1(errorStr: String) {
                            EventUtils.onEvent("h5_pay_error1", errorStr)
                        }

                        override fun loadH5Error2(errorStr: String) {
                            EventUtils.onEvent("h5_pay_error2", errorStr)
                        }
                    })
            } else {
                H5PayUtil().loadH5AppPay(
                    mActivity!!,
                    pay_type!!,
                    form ?: "",
                    object : H5PayUtil.H5AppPayCallBack {
                        override fun jumpAppException(e: Exception) {
                            EventUtils.onEvent("H5AppPayError", "error:${pay_type}")
                            if (pay_type == PaymentConfig.ZFB_H5_PAY||pay_type == PaymentConfig.HUI_FU_H5_PAY1) {
                                mLoading?.setResult(false, "支付失败,请安装支付宝后重试", 1000)
                            } else {
                                mLoading?.setResult(false, "支付失败,请安装微信后重试", 1000)
                            }
                        }
                    })
            }

        }
    }

    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 onNewIntent(intent: Intent?) {
        val data = intent?.data
        if (data != null) {
            if (pay_type == PaymentConfig.SD_PAY) {
                val payCode = data.getQueryParameter("payCode")
                if (payCode == "2") {
                    mPresenter?.verifyPay(SettingPreference.getOutTradeNo(), pay_type!!)
                } else {
                    showResultLoading(false)
                }
            }
        }
    }

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

}