package com.zxbw.modulemain.activity

import android.graphics.Paint
import android.os.Handler
import android.util.Log
import android.view.View
import com.zxbw.modulemain.R
import com.zxbw.modulemain.contract.CardDetailContract
import com.zxbw.modulemain.presenter.CardDetailPresenter
import com.zxbw.modulemain.presenter.RightsPayPresenter
import com.zxhl.cms.AppContext
import com.zxhl.cms.common.Constant
import com.zxhl.cms.common.base.BaseActivity
import com.zxhl.cms.net.model.qy.RightsDetailEntity
import com.zxhl.cms.net.model.uc.AliPayEntity
import com.zxhl.cms.net.model.uc.PayResultEntity
import com.zxhl.cms.pay.alipay.AlipayServer
import com.zxhl.cms.utils.EventUtils
import com.zxhl.cms.utils.MainLooper
import com.zxhl.cms.utils.RxBus
import com.zxhl.cms.widget.LoadingDialog
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.functions.Consumer
import kotlinx.android.synthetic.main.activity_layout_card_detail.*

class CardDetailActivity : BaseActivity(), CardDetailContract.View {
    private var mPayPresenter: CardDetailPresenter? = null
    private var mLoading: LoadingDialog? = null
    private var pay_type: Int? = RightsDetailActivity.ALI_PAY
    private var payResultObservable: Observable<PayResultEntity>? = null
    var goodsID:String?=""
    override fun onClick(v: View?) {

    }

    override fun before() {
        super.before()
        setStatusBarBackground(AppContext.get().resources.getColor(R.color.transparent))
    }

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

    override fun init() {
        val cardbean: RightsDetailEntity =
            intent.getSerializableExtra("cardbean") as RightsDetailEntity
        initPay()
        goodsID=cardbean.id
        id_img_back?.setOnClickListener {
            finish()
        }
        id_ll_pay?.setOnClickListener {
            toPay()
        }
        setView(cardbean)
    }
    fun setView(bean: RightsDetailEntity) {
        id_tv_card_name?.text="${bean.brand}${bean.goodsName}${bean.category}"
        id_tv_cards_name?.text = "${bean.brand}${bean.goodsName}${bean.category}"
        id_tv_cagte_name?.text = bean.category
        id_tv_card_discount?.text = "会员专享${bean.costDiscount}折"
        id_tv_card_price?.text = "${bean.salePrice}"
        id_tv_guanfang_price?.text = "官方价 ¥${bean.originPrice}元"
        id_tv_guanfang_price?.getPaint()?.setFlags(Paint.STRIKE_THRU_TEXT_FLAG) //中划线
        id_tv_pay_price?.text = "${bean.salePrice}"
        id_tv_jiesheng_price?.text = "立省${bean.costPrice}元"
    }
    fun initPay(){
        mPayPresenter= CardDetailPresenter(this)
        mLoading = LoadingDialog.getLoadingDialog(
            this,
            getString(com.zxhl.cms.R.string.wait_ing),
            false,
            false
        )
        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) {
                    EventUtils.onEvent("pay_page_pay_query_order", "付款成功")
                    mPayPresenter?.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 var mHandler: Handler = Handler {
        when (it.what) {
            0 -> {
                if (mLoading != null) {
                    mLoading?.setResult(false, "取消支付", 1000)
                }
            }
        }
        false
    }
    fun toPay(){
        mLoading?.setLoading("请稍后...")
        mLoading?.show()
        mPayPresenter?.requestRightsAliPay(goodsID.toString(), pay_type.toString(), "")
    }
    override fun requestOrderSuc(result: AliPayEntity) {
        AlipayServer.payV2(this, result.wakeup!!)
    }

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

    override fun verifyOrderSuc(order: String) {
        showResultLoading(true)
    }

    override fun verifyOrderFail(errorMsg: String) {
        showResultLoading(false)
    }
    private fun showResultLoading(isPaySuc: Boolean) {
        if (isPaySuc) {
            mLoading?.setResult(true, "支付成功", 1000)
        } else {
            mLoading?.setResult(false, "支付失败", 1000)
        }
    }
    override fun onDestroy() {
        super.onDestroy()
        if (payResultObservable != null)
            RxBus.get().unregister(Constant.PAY_RESULT, payResultObservable!!)
    }



}