package com.zxbw.modulemain.activity

import android.content.Intent
import android.graphics.Paint
import android.net.Uri
import android.os.Handler
import android.text.TextUtils
import android.util.Log
import android.view.KeyEvent
import android.view.View
import android.webkit.*
import com.pay.paytypelibrary.base.OnPayResultListener
import com.pay.paytypelibrary.base.OrderInfo
import com.pay.paytypelibrary.base.PayUtil
import com.zxbw.modulemain.R
import com.zxbw.modulemain.box.activity.ReceiveAddressActivity
import com.zxbw.modulemain.contract.CardDetailContract
import com.zxbw.modulemain.presenter.CardDetailPresenter
import com.zxbw.modulemain.view.DialogUtils
import com.zxhl.cms.AppContext
import com.zxhl.cms.common.Constant
import com.zxhl.cms.common.NetConfig
import com.zxhl.cms.common.base.BaseActivity
import com.zxhl.cms.net.ApiClient
import com.zxhl.cms.net.RxSchedulers
import com.zxhl.cms.net.SettingPreference
import com.zxhl.cms.net.callback.BaseObserver
import com.zxhl.cms.net.model.box.AddressEntity
import com.zxhl.cms.net.model.box.GoodList
import com.zxhl.cms.net.model.uc.AliPayEntity
import com.zxhl.cms.net.model.uc.PayResultEntity
import com.zxhl.cms.pay.H5PayUtil
import com.zxhl.cms.pay.PaymentConfig
import com.zxhl.cms.pay.alipay.AlipayServer
import com.zxhl.cms.utils.EventUtils
import com.zxhl.cms.utils.JumpUtils
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_skill_shop.*
import kotlinx.android.synthetic.main.activity_layout_skill_shop.id_img_back
import kotlinx.android.synthetic.main.activity_layout_skill_shop.id_img_close_pay_web
import kotlinx.android.synthetic.main.activity_layout_skill_shop.id_rights_pay_web_view
import kotlinx.android.synthetic.main.activity_layout_skill_shop.id_rl_h5_pay_view
import kotlinx.android.synthetic.main.activity_layout_skill_shop.id_rl_hava_address
import kotlinx.android.synthetic.main.activity_layout_skill_shop.id_rl_no_address
import kotlinx.android.synthetic.main.activity_layout_skill_shop.id_tv_pay_money
import kotlinx.android.synthetic.main.activity_layout_skill_shop.id_tv_to_pay
import kotlinx.android.synthetic.main.activity_layout_skill_shop.id_tv_user_address
import kotlinx.android.synthetic.main.activity_layout_skill_shop.id_tv_user_name_phone
import kotlinx.android.synthetic.main.activity_layout_to_pay_skill_goods.*

class XymhSkillShopActivity : BaseActivity(), CardDetailContract.View {
    private var mPayPresenter: CardDetailPresenter? = null
    private var mLoading: LoadingDialog? = null
    private var pay_type: Int? = PaymentConfig.H5_PAY
    private var payResultObservable: Observable<PayResultEntity>? = null
    private var updateAddress: Observable<Int>? = null
    var goodsID: String? = ""
    var type: String? = "0"
    var skill: Boolean? = false
    var outTradeNo: String? = ""
    private var addressId: String? = ""
    var addrees: AddressEntity? = null
    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_skill_shop
    }

    override fun init() {
        val goodList: GoodList =
            intent.getSerializableExtra("goodsbean") as GoodList
        type = intent.getStringExtra("type")
        outTradeNo = intent.getStringExtra("outTradeNo")
        skill = intent.getBooleanExtra("skill", false)
        Log.e("MXL", "skill" + skill)
        initPay()
        goodsID = goodList.id
        id_img_back?.setOnClickListener {
            if (TextUtils.equals(type, "1")) {
                // 在这里，拦截或者监听Android系统的返回键事件。
                DialogUtils.showExitSkillBuy(this, View.OnClickListener {
                    finish()
                })
            } else {
                finish()
            }
        }
        id_tv_to_pay?.setOnClickListener {
            toPay()
        }
        id_img_close_pay_web?.setOnClickListener {
            id_rl_h5_pay_view.visibility = View.GONE
        }
        id_rl_no_address?.setOnClickListener {
            val intent = Intent(mActivity, ReceiveAddressActivity::class.java)
            intent.putExtra("order", "order")
            startActivityForResult(intent, 1001)

            // JumpUtils.ReceiveAddressReslutJump("0")
        }
        id_rl_hava_address?.setOnClickListener {
            val intent = Intent(mActivity, ReceiveAddressActivity::class.java)
            intent.putExtra("order", "order")
            intent.putExtra("id", addressId)

            startActivityForResult(intent, 1001)

        }
        setView(goodList)
        getAddress()
        updateAddress = RxBus.get().register(Constant.CHOSSEE_ADDRESS_RESULT, Int::class.java)
        updateAddress?.observeOn(AndroidSchedulers.mainThread())
            ?.subscribe(Consumer<Int?> { s ->
                if (s == 1) {
                    updateAddreeInfo(null)
                }

            }, Consumer<Throwable?> { })
    }

    fun getAddress() {
        ApiClient.homeApi.getAddress("0")
            .compose(RxSchedulers.observableIO2Main())
            .subscribe(object : BaseObserver<List<AddressEntity>>() {
                override fun onSuccess(result: List<AddressEntity>?) {
                    if (result != null) {
                        if (!result.isNullOrEmpty()) {
                            for (i in result) {
                                if (TextUtils.equals(i.defaultAddress, "1")) {
                                    updateAddreeInfo(i)
                                } else {
                                    updateAddreeInfo(result[0])
                                }
                            }
                        }else{
                            updateAddreeInfo(null)
                        }
                    }else{
                        updateAddreeInfo(null)
                    }
                }

                override fun onFailure(e: Throwable?, code: String?, errorMsg: String?) {

                }
            })
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == 1001) {
            addrees = data?.getSerializableExtra("address") as AddressEntity?
            Log.e("MXL", "选了地址回来" + addrees?.address)
            updateAddreeInfo(addrees)

        }

    }

    fun updateAddreeInfo(result: AddressEntity?) {
        if (result == null) {
            id_rl_hava_address?.visibility = View.GONE
            id_rl_no_address?.visibility = View.VISIBLE
            addressId = ""
        } else {
            id_rl_hava_address?.visibility = View.VISIBLE
            id_rl_no_address?.visibility = View.GONE
            addressId = result?.id
            synocAddress()
            id_tv_user_name_phone?.text =
                result?.username + result?.mobile
            id_tv_user_address?.text =
                "${result?.region}-${result?.address}"
        }


    }

    fun synocAddress() {
        ApiClient.homeApi.updateAddress(addressId,outTradeNo)
            .compose(RxSchedulers.observableIO2Main())
            .subscribe(object : BaseObserver<Any>() {
                override fun onSuccess(result: Any?) {

                }

                override fun onFailure(e: Throwable?, code: String?, errorMsg: String?) {

                }
            })
    }

    fun setView(bean: GoodList) {
        id_img_order_goods?.setLoadImageUrl("${bean.mainImage}", false)
        id_tv_order_name?.text = "${bean.productName}"
        id_tv_sale_price?.text = "¥${bean.salePriceStr}"
        id_tv_pay_money?.text = "${bean.skillPrice}"
    }

    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> { })

        var result = SettingPreference.getConfig()
        if (result != null) {
            if (result != null && !result.pay_config_v2.isNullOrEmpty()) {
                for (i in result.pay_config_v2!!.indices) {
                    if (result?.pay_config_v2!![i].open == 1) {
                        pay_type = result?.pay_config_v2!![i].type
                        break
                    }
                }
            }
        }
    }

    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
    }

    fun toPay() {
        isClickPayBtn = true
        mLoading?.setLoading("请稍后...")
        mLoading?.show()
        mPayPresenter?.requestRightsAliPay("xxsqshop://skillshop",
            goodsID.toString(),
            pay_type.toString(),
            "",
            "99",
            skill,
            outTradeNo
        )
    }

    override fun requestOrderSuc(result: AliPayEntity) {
        if (pay_type == PaymentConfig.MIN_PAY_PROGRAM) {
            SettingPreference.setOutTradeNo(result?.outTradeNo)
            JumpUtils.h5Jump("https://api.minpayment.com/pay.do?sendMsg=" + result.wakeup)
        } else if (pay_type == PaymentConfig.H5_PAY) {
            SettingPreference.setOutTradeNo(result?.outTradeNo)
            if (result.outTradeNo.isNullOrEmpty()) {
                EventUtils.onEvent("h5_pay_error")
                showResultLoading(false)
            } else {
                mHandler.sendEmptyMessageDelayed(1, 8000)
                H5PayUtil().loadH5PayWeb(
                    this,
                    id_rights_pay_web_view,
                    result.outTradeNo ?: "",
                    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 if (pay_type == PaymentConfig.ALI_PAY) {
            AlipayServer.payV2(this, result.wakeup!!)
        } else if (pay_type == PaymentConfig.SD_PAY) {
            SettingPreference.setOutTradeNo(result.outTradeNo)
            PayUtil.CashierPaySingle(this, result.wakeup, object : OnPayResultListener {
                override fun onSuccess(p0: OrderInfo?) {

                }

                override fun onError(p0: String?) {
                    EventUtils.onEvent("SdPayError", "error:${p0}")
                    mLoading?.setResult(false, "支付异常", 1000)
                }
            });
        }else if (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) {
            if (result.outTradeNo.isNullOrEmpty()) {
                EventUtils.onEvent("H5AppPayError","error:outTradeNo null")
                showResultLoading(false)
            } else {
                SettingPreference.setOutTradeNo(result.outTradeNo)
                H5PayUtil().loadH5AppPay(
                    this,
                    pay_type!!,
                    result.wakeup ?: "",
                    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)
                            }
                        }
                    })
            }
        } else {
            showToast("暂不支持")
            EventUtils.onEvent("payment_error", "$pay_type")
        }
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        val data = intent?.data
        if (data != null) {
            if (pay_type == PaymentConfig.SD_PAY) {
                val payCode = data.getQueryParameter("payCode")
                if (payCode == "2") {
                    isPause = false
                    mPayPresenter?.verifyPay(SettingPreference.getOutTradeNo(), pay_type!!)
                } else {
                    showResultLoading(false)
                }
            }
        }
    }

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

    override fun verifyOrderSuc(order: String) {
        isClickPayBtn = false
        SettingPreference.setOutTradeNo("")
        showResultLoading(true)
        finish()
        JumpUtils.PaySuceessJump()

    }

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

    private fun showResultLoading(isPaySuc: Boolean) {
        if (isPaySuc) {
            mLoading?.setResult(true, "支付成功", 1000)

        } else {
            mLoading?.setResult(false, "支付失败", 1000)
        }
    }


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

    private var isPause = false
    private var isClickPayBtn = false
    override fun onResume() {
        super.onResume()
        if (isPause && isClickPayBtn) {
            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) {
                //如果是敏支付或者H5支付
                mPayPresenter?.verifyPay(SettingPreference.getOutTradeNo(), pay_type!!)
            } else {
                mHandler?.sendEmptyMessageDelayed(0, 2000)
            }
        }
    }

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

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (TextUtils.equals(type, "1")) {
                // 在这里，拦截或者监听Android系统的返回键事件。
                DialogUtils.showExitSkillBuy(this, View.OnClickListener {
                    finish()
                })

            } else {
                finish()
            }

        }

        return false
    }
}