package com.zxhl.cms.pay


import android.content.Intent
import android.os.Handler
import android.text.TextUtils
import android.util.Log
import android.view.View
import androidx.recyclerview.widget.GridLayoutManager
import com.paypal.checkout.PayPalCheckout
import com.paypal.checkout.approve.OnApprove
import com.paypal.checkout.cancel.OnCancel
import com.paypal.checkout.createorder.CreateOrder
import com.paypal.checkout.createorder.CurrencyCode
import com.paypal.checkout.createorder.OrderIntent
import com.paypal.checkout.createorder.UserAction
import com.paypal.checkout.error.OnError
import com.paypal.checkout.order.Amount
import com.paypal.checkout.order.AppContext
import com.paypal.checkout.order.Order
import com.paypal.checkout.order.PurchaseUnit
import com.zxhl.cms.R
import com.zxhl.cms.common.Constant
import com.zxhl.cms.common.NetConfig
import com.zxhl.cms.common.base.BaseActivity
import com.zxhl.cms.googlepay.GooglePayActivity
import com.zxhl.cms.net.SettingPreference
import com.zxhl.cms.net.model.box.AppInEntity
import com.zxhl.cms.net.model.video.MemberEntity
import com.zxhl.cms.utils.*
import com.zxhl.cms.utils.EventUtils.onEvent
import com.zxhl.cms.widget.LoadingDialog
import com.zxhl.cms.widget.RecyclerViewSpacesItemDecoration
import com.zxhl.novel.utils.server.PayResultEntity
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.functions.Consumer
import kotlinx.android.synthetic.main.activity_member.*
import java.util.*

/**
 * Created by gaoleichao on 2021/8/30
 */
class PayActivity : BaseActivity(), PayContract.View,
    OnRecycleItemClickListener<MemberEntity.ProductDetail>, AdCallback<String> {
    override fun onClick(p0: View?) {

    }

    override fun layoutID(): Int = R.layout.activity_member

    private var mPresenter: PayContract.Presenter? = null
    private var mAdapter: PayAdapter? = null
    private var needPrice: String? = ""
    private var mLoading: LoadingDialog? = null

    private var payResultObservable: Observable<PayResultEntity>? = null
    private var ifChooseNeedPrice: Boolean? = false
    private var userCoins: Double = 0.0
    private var type: String = ""
    private var boxid: String = ""
    private var itemlayout: Int = 0

    companion object {
        const val ALI_PAY = 1   //支付宝支付类型
        const val WECHAT_PAY = 2  //微信支付类型
        const val MINI_PROGRAM = 11  //微信支付类型
        const val MIN_PAY_PROGRAM = 12  //敏付
    }

    private var pay_type: Int? = 0
    override fun before() {
        super.before()
        setStatusBarBackground(resources.getColor(R.color.transparent))
    }


    override fun init() {

        mLoading = LoadingDialog.getLoadingDialog(
            this,
            getString(com.zxhl.cms.R.string.wait_ing),
            false,
            false
        )
        id_img_back?.setOnClickListener {
            finish()
        }
        id_activity_member_close?.setOnClickListener {
            finish()
        }
        id_rl_buy_bg?.setOnClickListener {
            chosseNeedPrice()
        }
        id_ll_service?.setOnClickListener {
            JumpUtils.webJump("增值服务协议", NetConfig.H5.WEB_URL_ZENGZHI_SERVICE)
        }
        id_rl_wechat_pay?.setOnClickListener {
            //pay_type = MIN_PAY_PROGRAM
            id_img_wechat?.setImageResource(R.drawable.icon_xuanzhong)
            id_img_ali?.setImageResource(R.drawable.icon_xuanzhong_default)
        }
        id_rl_zfb_pay?.setOnClickListener {
            pay_type = ALI_PAY
            id_img_wechat?.setImageResource(R.drawable.icon_xuanzhong_default)
            id_img_ali?.setImageResource(R.drawable.icon_xuanzhong)

        }
        EventUtils.onEvent("pay_page_show", "充值页展示")
        boxid = intent?.data?.getQueryParameter("boxid") ?: ""
        needPrice = intent?.data?.getQueryParameter("price") ?: "0"
        Log.e("MXL", "NeedPrice" + needPrice)
        if (!TextUtils.isEmpty(needPrice)) {
            if (needPrice?.toDouble()?.toString()?.contains(".") == true) {
                if (TextUtils.equals(needPrice?.toDouble()?.toString(), "9.9")) {
                    id_tv_need_price?.text = needPrice?.toDouble()?.toString()
                } else {
                    var priceStr = needPrice?.toDouble()?.toInt()
                    id_tv_need_price?.text = priceStr?.plus(1).toString()
                }

            } else {
                var priceStr = needPrice?.toDouble()?.toInt()
                id_tv_need_price?.text = priceStr?.toString()
            }

        }

        type = intent?.data?.getQueryParameter("type") ?: ""
        // setBootmPrice()
        id_tv_my_yu_e?.text = SettingPreference.getUserCoinNum()

        mPresenter = PayPresenter(this)
        // mAdapter = PayAdapter(this,itemlayout)

//        val data = VideoEntity()
//        data.img =
//            "https://cdn.zhangxingames.com/video/2021/8/31/e94f1586-0a29-11ec-95cd-8f334d14625a.mp4?x-oss-process=video/snapshot,t_1,f_jpg,w_0,h_0,m_fast"
//        data.url =
//            "https://cdn.zhangxingames.com/video/2021/8/31/e94f1586-0a29-11ec-95cd-8f334d14625a.mp4"


        id_ll_pay_bottom?.setOnClickListener {
            if (pay_type == 0) {
                Utils.showToast(this, "请选择支付类型")
                return@setOnClickListener
            }
            mLoading?.setLoading("请稍后")
            mLoading?.show()
            EventUtils.onEvent("pay_page_pay_btn", product?.cash + "")
            if (ifChooseNeedPrice!!) {
                if (pay_type == 1) {
                    mPresenter?.requestAliPay(
                        this,
                        id_tv_need_price.text.toString(),
                        pay_type.toString(),
                        "6"
                    )
                } else {
                    if (pay_type == 2) {
                        Log.e("MXL", "微信原生支付")
                        mPresenter?.requestWechatPayOrder("", pay_type.toString())
                    } else if (pay_type == 11) {
                        Log.e("MXL", "微信连连支付")
                        mPresenter?.requestWechatPayOrder("", pay_type.toString())
                    } else {
                        Log.e("MXL", "微信敏支付")
                        mPresenter?.requestMiniProgrom(
                            id_tv_need_price.text.toString(),
                            pay_type.toString(),
                            "6"
                        )
                    }

                }


            } else {
                if (pay_type == 1) {
                    mPresenter?.requestAliPay(
                        this,
                        product?.goodsId ?: "",
                        pay_type.toString(),
                        "6"
                    )
                } else {
                    if (pay_type == 2) {
                        Log.e("MXL", "2微信原生支付")
                        mPresenter?.requestWechatPayOrder(
                            product?.goodsId ?: "",
                            pay_type.toString()
                        )
                    } else if (pay_type == 11) {
                        Log.e("MXL", "2微信连连支付")
                        mPresenter?.requestWechatPayOrder(
                            product?.goodsId ?: "",
                            pay_type.toString()
                        )
                    } else {
                        Log.e("MXL", "2微信敏支付")
                        mPresenter?.requestMiniProgrom(
                            product?.goodsId ?: "",
                            pay_type.toString(),
                            "6"
                        )
                    }

                }

            }

        }

        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)
                Log.d("qqbs", "verifyPay:${obj.txt}")
                println("verifyPay payResultObservable------------------------------- order:${obj.txt}")
                if (obj.isPaySuc) {
                    if (boxid.equals("-3")) {
                        onEvent("9.9_pay_sucess", "9.9付款成功")
                    }
                    onEvent("pay_page_pay_query_order", "付款成功")
                    mPresenter?.verifyPay(obj.txt, obj.payType)
                } else {
                    if (boxid.equals("-3")) {
                        onEvent("9.9_pay_fail", "9.9付款失败")
                    }
                    showResultLoading(false)
                }
            }, Consumer<Throwable> { })

        id_activity_member_pri?.setOnClickListener {
            JumpUtils.webJump("隐私协议", NetConfig.H5.WEB_URL_PRIVACY)
        }

        id_activity_member_user?.setOnClickListener {
            JumpUtils.webJump("用户协议", NetConfig.H5.WEB_URL_USER)
        }

        EventUtils.onEvent("member_page_show")
           startActivity(Intent(this,GooglePayActivity::class.java))
        initPaypal()
//        payPalPay()
    }


    fun checkChoose() {
        if (needPrice.equals("0")) {
            id_rl_buy_bg?.visibility = View.GONE
            chooseOtherPrice()
        } else {
            id_rl_buy_bg?.visibility = View.VISIBLE
            chosseNeedPrice()
        }
    }

    override fun data() {
        super.data()
        mPresenter?.appInfo()
        mPresenter?.getPriceList()

    }


    override fun updatePriceList(data: List<MemberEntity.ProductDetail>) {
        if (!data.isNullOrEmpty()) {
            if (data.size >= 4 && !TextUtils.isEmpty(data[3].buttonText)) {
                itemlayout = 1
            } else {
                itemlayout = 0
            }
        }
        mAdapter = PayAdapter(this, itemlayout)
//        val widthScreen = windowManager?.defaultDisplay?.width
//        val widthDecoration = (widthScreen!! - Utils.dip2px(20 * 2) - Utils.dip2px(93 * 3)) / 6
        val gridLayoutManager: GridLayoutManager = object : GridLayoutManager(this, 3) {
            override fun canScrollVertically(): Boolean {
                return false
            }
        }
        id_activity_member_list?.layoutManager = gridLayoutManager
//        val stringIntegerHashMap: HashMap<String, Int> = HashMap()
//        stringIntegerHashMap[RecyclerViewSpacesItemDecoration.TOP_DECORATION] =
//            Utils.dip2px(7) //top间距
//        stringIntegerHashMap[RecyclerViewSpacesItemDecoration.BOTTOM_DECORATION] =
//            Utils.dip2px(7) //底部间距
//        stringIntegerHashMap[RecyclerViewSpacesItemDecoration.LEFT_DECORATION] =
//            widthDecoration //左间距
//        stringIntegerHashMap[RecyclerViewSpacesItemDecoration.RIGHT_DECORATION] =
//            widthDecoration //右间距
//        id_activity_member_list?.addItemDecoration(
//            RecyclerViewSpacesItemDecoration(
//                stringIntegerHashMap
//            )
//        )
        id_activity_member_list?.adapter = mAdapter

        mAdapter?.clear()
        mAdapter?.appendToList(data)
        checkChoose()

//        if (data.size >= 3) {
//            mAdapter?.setPosition(2)
//        }
        mAdapter?.notifyDataSetChanged()
    }


    private var product: MemberEntity.ProductDetail? = null


    override fun onItemClick(view: View?, position: Int, data: MemberEntity.ProductDetail?) {
        this.product = data
        ifChooseNeedPrice = false

        id_rl_buy_bg?.setBackgroundResource(R.drawable.shape_need_price_bg)
        EventUtils.onEvent("member_page_item_click", data?.cash + "")
    }

    private fun showResultLoading(isPaySuc: Boolean) {
        if (isPaySuc) {
            EventUtils.onEvent("pay_suc")
            mLoading?.setResult(true, "支付成功", 1000)
        } else {
            EventUtils.onEvent("pay_fail")
            mLoading?.setResult(false, "支付失败", 1000)
        }

    }

    fun setBootmPrice() {
        if (ifChooseNeedPrice!!) {
            id_activity_member_btn?.text = needPrice
        } else {
            id_activity_member_btn?.text = product?.title
        }
    }

    override fun verifyOrderFail() {
        showResultLoading(false)
    }

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

    override fun verifyOrderSuc(orsder: String) {
        Log.e("MXL", "充值成功，更新余额")
        RxBus.get().post(Constant.finish_activity, 1)
        UserDataUtils.updateUserInfo(this)
        showResultLoading(true)
    }

    override fun setCanInvest(boolean: Boolean?) {
        if (boolean == true) {

        } else {
            Utils.showToast(this, "充值上限，无法充值")
        }
    }

    override fun setOrderNo(order: String?) {

    }

    override fun setAppInfo(result: AppInEntity?) {
        if (result != null) {

            if (result.pay_ali.equals("1") && result.pay_wx.equals("0")) {
                pay_type = ALI_PAY
                id_rl_wechat_pay.visibility = View.GONE
                id_rl_zfb_pay.visibility = View.VISIBLE
                id_img_ali?.setImageResource(R.drawable.icon_xuanzhong)
            } else {
                if (result?.pay_ali.equals("0")) {
                    id_rl_zfb_pay.visibility = View.GONE
                } else {
                    id_rl_zfb_pay.visibility = View.VISIBLE

                }
                if (result?.pay_wx.equals("0")) {
                    id_rl_wechat_pay.visibility = View.GONE
                } else {
                    id_rl_wechat_pay.visibility = View.VISIBLE
                    pay_type = result?.pay_wx_type
                    id_img_wechat?.setImageResource(R.drawable.icon_xuanzhong)
                    id_img_ali?.setImageResource(R.drawable.icon_xuanzhong_default)

                }

            }


        }
    }

    override fun onDestroy() {
        super.onDestroy()
        if (payResultObservable != null)
            RxBus.get().unregister(Constant.PAY_RESULT, payResultObservable!!)
    }

    private var isPause = false
    override fun onResume() {
        super.onResume()
        if (isPause) {
            mHandler?.sendEmptyMessageDelayed(0, 2000)
        }
    }

    override fun onPause() {
        super.onPause()
        isPause = true
//        MobclickAgent.onPause(this)
    }

    fun chosseNeedPrice() {
        ifChooseNeedPrice = true
        id_rl_buy_bg?.setBackgroundResource(R.drawable.shape_need_price_bg_select)
        mAdapter?.setPosition(-1)
    }

    fun chooseOtherPrice() {
        mAdapter?.setPosition(0)
        ifChooseNeedPrice = false
        id_rl_buy_bg?.setBackgroundResource(R.drawable.shape_need_price_bg)

    }

    private val DELAY = 500
    private var lastClickTime: Long = 0
    override fun onResult(code: Int, result: String?) {
        id_tv_my_yu_e?.text = SettingPreference.getUserCoinNum()
        userCoins = SettingPreference.getUserCoinNum().toDoubleOrNull() ?: 0.00
        if (!TextUtils.isEmpty(needPrice) && !TextUtils.equals(needPrice, "0")) {
            var lotery = needPrice?.toDoubleOrNull() ?: 0.0
            if (userCoins.compareTo(lotery) >= 0) {
                //比较当前余额和要抽奖的余额 帮用户跳转到抽奖页面
                var currentTime = System.currentTimeMillis();
                if (currentTime - lastClickTime > DELAY) {
                    lastClickTime = currentTime;
                    finish()
                    //JumpUtils.lotteryBoxJump(boxid, type, needPrice)
                }
            }
        }
    }

    private var mHandler: Handler = Handler {
        when (it.what) {
            0 -> {
                if (mLoading != null) {
                    EventUtils?.onEvent("canle_pay", "取消支付")
                    mLoading?.setResult(false, "取消支付", 1000)
                }
            }
        }
        false
    }

    private fun initPaypal() {
        id_PayPal_btn.setup(
            createOrder =
            CreateOrder { createOrderActions ->
                val order =
                    Order(
                        intent = OrderIntent.CAPTURE,
                        appContext = AppContext(userAction = UserAction.PAY_NOW),
                        purchaseUnitList =
                        listOf(
                            PurchaseUnit(
                                amount =
                                Amount(currencyCode = CurrencyCode.USD, value = "0.01")
                            )
                        )
                    )
//                createOrderActions.set("")
                createOrderActions.create(order)
                Log.i("id_PayPal_btn", "createOrderActions order: ${order.purchaseUnitList.size}")
            },
            onApprove =
            OnApprove { approval ->
                approval.orderActions.capture { captureOrderResult ->
                    Log.i("id_PayPal_btn", "CaptureOrder CaptureOrderResult: $captureOrderResult")
                    approval.data.orderId

                }
            },
            onError = OnError { errorInfo ->
                Log.d("id_PayPal_btn", "Wid_PayPal_btn OnError Error: $errorInfo")
            },
            onCancel = OnCancel {
                Log.d("id_PayPal_btn", " OnCancel Buyer canceled the PayPal experience.")
            }
        )
    }

    fun payPalPay() {
//        PayPalCheckout.startCheckout()
        id_PayPal_btn.setup(
            createOrder =
            CreateOrder { createOrderActions ->
                var orderId: String = "111111111111111111111111";
//                val order =
//                    Order(
//                        intent = OrderIntent.CAPTURE,
//                        appContext = AppContext(userAction = UserAction.PAY_NOW),
//                        purchaseUnitList =
//                        listOf(
//                            PurchaseUnit(
//                                amount =
//                                Amount(currencyCode = CurrencyCode.USD, value = "0.01")
//                            )
//                        )
//                    )
                createOrderActions.set(orderId)
//                createOrderActions.create(order)
//                Log.i("id_PayPal_btn", "createOrderActions order: ${order.purchaseUnitList.size}")
            },
            onApprove =
            OnApprove { approval ->
                approval.orderActions.capture { captureOrderResult ->
                    Log.i("id_PayPal_btn", "CaptureOrder CaptureOrderResult: $captureOrderResult")
                    approval.data.orderId

                }
            },
            onError = OnError { errorInfo ->
                Log.d("id_PayPal_btn", "Wid_PayPal_btn OnError Error: $errorInfo")
            },
            onCancel = OnCancel {
                Log.d("id_PayPal_btn", " OnCancel Buyer canceled the PayPal experience.")
            }
        )
        id_PayPal_btn.callOnClick()
    }

}