package com.zxhl.cms.pay.view

import android.content.Intent
import android.os.Build
import android.util.Log
import android.view.View
import com.paypal.checkout.PayPalCheckout
import com.zxhl.cms.R
import com.zxhl.cms.common.base.BaseActivity
import com.zxhl.cms.net.model.box.AppInEntity
import com.zxhl.cms.pay.PayContract
import com.zxhl.cms.pay.contract.PaymentPageContract
import com.zxhl.cms.pay.googlepay.GooglePayCallBack
import com.zxhl.cms.pay.googlepay.GooglePayHelper
import com.zxhl.cms.pay.googlepay.GooglePayResult
import com.zxhl.cms.pay.paypal.PayPalHelper
import com.zxhl.cms.pay.presenter.PaymentPagePresenter
import com.zxhl.cms.paypal.PayPalPayCallBack
import com.zxhl.cms.utils.EventUtils
import com.zxhl.cms.utils.Utils
import com.zxhl.cms.widget.CenterDialog
import com.zxhl.cms.widget.LoadingDialog
import kotlinx.android.synthetic.main.activity_layout_payment_page.*
import kotlinx.android.synthetic.main.activity_layout_payment_page.id_img_back
import kotlinx.android.synthetic.main.activity_member.*

/**
 * @author (wangXuewei)
 * @datetime 2022-04-13 15:56 GMT+8
 * @detail :
 */
class PaymentPageActivity : BaseActivity(), PaymentPageContract.View {

    companion object {
        const val GOOGLE_PAY = 4  //Google支付类型
        const val PAY_PAL_PAY = 5  //PayPal支付类型
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        init()
    }

    private var payType: Int? = GOOGLE_PAY

    private var googlePay: GooglePayHelper? = null
    private var payPalPay: PayPalHelper? = null
    private var mLoading: LoadingDialog? = null
    private var mPresenter: PaymentPageContract.Presenter? = null

    private var goodsType: String = "";
    private var goodsId: String = "";
    private var goodsName: String = "";
    private var goodsPrice: String = "";

    override fun init() {
        goodsType = intent?.data?.getQueryParameter("pay_goods_type") ?: ""
        goodsId = intent?.data?.getQueryParameter("pay_goods_id") ?: ""
        goodsName = intent?.data?.getQueryParameter("pay_goods_name") ?: ""
        goodsPrice = intent?.data?.getQueryParameter("pay_goods_price") ?: ""

        id_tv_goods_name.text = goodsName
        id_tv_goods_price.text = "Price:$${goodsPrice}"
        id_tv_pay_btn.text = "Pay $${goodsPrice}"

        id_img_back.setOnClickListener(this)
        id_img_google_btn.setOnClickListener(this)
        id_rl_paypal_pay.setOnClickListener(this)
        id_tv_pay_btn.setOnClickListener(this)

        mLoading = LoadingDialog.getLoadingDialog(
            this,
            getString(com.zxhl.cms.R.string.wait_ing),
            false,
            false
        )
        mPresenter = PaymentPagePresenter(this)

        googlePay = GooglePayHelper(this)
        googlePay?.init(object : GooglePayCallBack {
            override fun onPaySuccess(purchase: GooglePayResult, googleJson: String) {
                mPresenter?.verifyThePayment(googleJson, GOOGLE_PAY)
                //mLoading?.setResult(true, "Pay for success", 1000)
                EventUtils.onEvent("GooglePaySuccess_bd")
            }

            override fun onCancel() {
                EventUtils.onEvent("GooglePayCancel_bd")
            }

            override fun onError(error: String) {
                Log.d("wxw", "补单PayError:$error")
                EventUtils.onEvent("GooglePayError_bd", error)
            }
        })
        payPalPay = PayPalHelper(this)


    }

    override fun onClick(v: View?) {
        when (v) {
            id_img_back -> {
                finish()
            }
            id_img_google_btn -> {
                selectPayType(GOOGLE_PAY)
            }
            id_rl_paypal_pay -> {
                selectPayType(PAY_PAL_PAY)
            }
            id_tv_pay_btn -> {
                //CenterDialog.showPaySuccessDialog(this)
                if (payType == 0) {
                    Utils.showToast(this, "Please select payment type")
                    return
                }
                EventUtils.onEvent("pay_page_pay_btn", goodsPrice)
                Log.d("wxw","Payment${goodsId} price:${goodsPrice}")
                if (payType == GOOGLE_PAY) {
                    googlePay(goodsId)
                } else if (payType == PAY_PAL_PAY) {
                    payPalPay(goodsId, goodsPrice)
                } else {
                    EventUtils.onEvent("pay_type_error", "pay_type$payType")
                }
            }
        }
    }

    override fun layoutID(): Int {
        return R.layout.activity_layout_payment_page
    }

    private fun selectPayType(type: Int) {
        payType = type
        id_img_google_btn?.setImageResource(R.drawable.icon_check_weixuanzhong)
        id_img_paypal_btn?.setImageResource(R.drawable.icon_check_weixuanzhong)
        when (type) {
            GOOGLE_PAY -> {
                id_img_google_btn.setImageResource(R.drawable.icon_check_xuanzhong)
            }
            PAY_PAL_PAY -> {
                id_img_paypal_btn.setImageResource(R.drawable.icon_check_xuanzhong)
            }
        }
    }

    override fun orderVerificationSuccessful(status: String) {
        EventUtils.onEvent("pay_suc")
        mLoading?.setResult(true, "Pay for success", 1000)
    }

    override fun orderVerificationFailed(errorMsg: String) {
        EventUtils.onEvent("pay_fail")
        mLoading?.setResult(false, "Pay for failure", 1000)
    }

    override fun setAppInfo(result: AppInEntity?) {

    }


    private fun googlePay(goodsId: String) {
        if (goodsId == "") {
            EventUtils.onEvent("GooglePayGoodsIdNull")
            return
        }
        mLoading?.setLoading(getString(R.string.wait_ing))
        mLoading?.show()
        EventUtils.onEvent("GooglePayStart", "开始支付")
        googlePay?.googlePay(goodsId, "6", object : GooglePayCallBack {
            override fun onPaySuccess(purchase: GooglePayResult, googleJson: String) {
                mPresenter?.verifyThePayment(googleJson, GOOGLE_PAY)
                EventUtils.onEvent("GooglePaySuccess")
                EventUtils.onEvent("GooglePayEnd", "支付结束_成功")
            }

            override fun onCancel() {
                runOnUiThread {
                    mLoading?.setResult(false, "pay cancel", 1000)
                }
                EventUtils.onEvent("GooglePayCancel")
                EventUtils.onEvent("GooglePayEnd", "支付结束_取消")
            }

            override fun onError(error: String) {
                Log.d("wxw", "PayError:$error")
                runOnUiThread {
                    mLoading?.setResult(false, "pay error", 1000)
                }
                EventUtils.onEvent("GooglePayError", error)
                EventUtils.onEvent("GooglePayEnd", "支付结束_异常 msg:${error}")

            }
        })
    }


    private fun payPalPay(goodsId: String, goodsPrice: String) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            showToast("Sorry your device does not currently support this payment method")
            return
        }
        if (goodsId == "" || goodsPrice == "") {
            EventUtils.onEvent("PayPalPayGoodsIdNull")
            return
        }
        mLoading?.setLoading(getString(R.string.wait_ing))
        mLoading?.show()
        payPalPay?.payPalPay(goodsId, goodsPrice, "6", object : PayPalPayCallBack {
            override fun onPaySuccess(result: String) {
                EventUtils.onEvent("PayPalPaySuccess")
                mPresenter?.verifyThePayment(result, PAY_PAL_PAY)
//                runOnUiThread {
//                    mLoading?.setResult(false, "pay success", 1000)
//                }
            }

            override fun onCancel() {
                EventUtils.onEvent("PayPalPayCancel")
                runOnUiThread {
                    mLoading?.setResult(false, "pay cancel", 1000)
                }
            }

            override fun onError(error: String) {
                Log.d("wxw", "PayError:$error")
                EventUtils.onEvent("PayPalPayError", error)
                runOnUiThread {
                    mLoading?.setResult(false, "pay error", 1000)
                }
            }
        }, id_PayPal_btn)


    }


}