package com.zxbw.modulemain.activity

import android.content.Intent
import android.os.Handler
import android.util.Log
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.zxbw.modulemain.R
import com.zxhl.cms.AppContext
import com.zxhl.cms.common.Constant
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.AppInEntity
import com.zxhl.cms.net.model.uc.PayResultEntity
import com.zxhl.cms.net.model.video.MemberEntity
import com.zxhl.cms.pay.*
import com.zxhl.cms.utils.*
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_member_order.*
import java.util.*

/**
 * @author (wangXuewei)
 * @datetime 2022-05-30 14:12 GMT+8
 * @detail :
 */
class OpenMemberOrderActivity : BaseActivity(), PayContract.View {
    private var mPresenter: PayContract.Presenter? = null
    private var payResultObservable: Observable<PayResultEntity>? = null
    private var mPayFunAdapter: PaymentFunAdapter? = null;
    private var mLoading: LoadingDialog? = null

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

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

    override fun onClick(v: View?) {

    }

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

    override fun init() {
        mLoading = LoadingDialog.getLoadingDialog(
            this,
            getString(R.string.wait_ing),
            false,
            false
        )
        mPresenter = PayPresenter(this)
        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) {
                    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> { })

        val userInfoData = SettingPreference.getUserInfoData()
        if (userInfoData != null) {
            id_tv_user_vip_phone.text = userInfoData.nickname
        }

        vipTime()

        mPayFunAdapter = PaymentFunAdapter(
            this
        ) { view, position, data ->
            pay_type = data.type
            mPayFunAdapter?.setPosition(position)
        }
        id_rcl_vip_payment_list.layoutManager = LinearLayoutManager(this)
        id_rcl_vip_payment_list.adapter = mPayFunAdapter
        id_tv_open_vip_btn_pay?.setOnClickListener {
            gotoPay()
        }
        id_img_back?.setOnClickListener {
            finish()
        }
        id_img_close_pay_web?.setOnClickListener {
            id_rl_h5_pay_view?.visibility = View.GONE
        }
    }

    override fun data() {
        super.data()
        mPresenter?.appInfo()
        getPayList()
    }

    private fun gotoPay() {
        if (pay_type == 0) {
            Utils.showToast(this, "请选择支付类型")
            return
        }
        if (payData == null) {
            Utils.showToast(this, "订单获取异常")
            return
        }
        mLoading?.setLoading("请稍后")
        mLoading?.show()

        if (pay_type == PaymentConfig.ALI_PAY) {
            mPresenter?.requestAliPay(
                this,
                payData?.goodsId ?: "",
                pay_type.toString(),
                "5"
            )
        } else if (pay_type == PaymentConfig.WECHAT_PAY) {
            Log.e("MXL", "2微信原生支付")
            mPresenter?.requestWechatPayOrder(
                payData?.goodsId ?: "",
                pay_type.toString()
            )
        } else if (pay_type == PaymentConfig.MINI_PROGRAM) {
            Log.e("MXL", "2微信连连支付")
            mPresenter?.requestWechatPayOrder(
                payData?.goodsId ?: "",
                pay_type.toString()
            )
        }  else if (pay_type == PaymentConfig.SD_PAY) {
            mPresenter?.requestSdPay("xxsqshop://member_order",
                this,
                payData?.goodsId ?: "",
                pay_type.toString(),
                "5"
            )
        } else {
            Log.e("MXL", "2支付宝敏支付")
            mPresenter?.requestMiniProgrom(
                payData?.goodsId ?: "",
                pay_type.toString(),
                "5"
            )
        }

    }

    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
                    mPresenter?.verifyPay(SettingPreference.getOutTradeNo(), pay_type!!)
                } else {
                    showResultLoading(false)
                }
            }
        }
    }

    override fun updatePriceList(data: List<MemberEntity.ProductDetail>) {

    }

    override fun verifyOrderFail(errorMsg: String) {
        EventUtils.onEvent("pay_fail", errorMsg)
        showResultLoading(false)
    }

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

    override fun requestH5OrderSuc(form: String) {
        if (form.isEmpty()) {
            EventUtils.onEvent("h5_pay_error")
            showResultLoading(false)
        } else {
            if (pay_type==PaymentConfig.H5_PAY){
                mHandler.sendEmptyMessageDelayed(1, 8000)
                H5PayUtil().loadH5PayWeb(
                    this,
                    id_member_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(
                    this,
                    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) {
        EventUtils.onEvent("pay_suc")
        UserDataUtils.updateUserInfo { code, result ->
            Constant.Switch.isOpenVip = true
            val userInfoData = SettingPreference.getUserInfoData()
            if (userInfoData != null) {
                Constant.Switch.isOpenVip = userInfoData.member ?: false
            }
            showResultLoading(true)
            finish()
        }

    }

    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
//                    pay_type = PaymentConfig.SD_PAY
                    mPayFunAdapter?.setPosition(i)
                    break
                }
            }
        }
    }


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

    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 isPause = false
    override fun onResume() {
        super.onResume()
        if (isPause) {
            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支付
                mPresenter?.verifyPay(SettingPreference.getOutTradeNo(), pay_type!!)
            } else {
                mHandler?.sendEmptyMessageDelayed(0, 2000)
            }
        }
    }

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

    override fun onDestroy() {
        super.onDestroy()
        timer?.cancel()
        timer = null
    }

    var timer: Timer? = null
    private fun vipTime() {
        var timeCount = 15 * 60
        // 创建计时器对象
        timer = Timer()
        // 创建计时器任务
        var timerTask: TimerTask = object : TimerTask() {
            override fun run() {
                timeCount--;
                runOnUiThread {
                    id_tv_vip_lock_time.text = Utils.timeConversion2(timeCount)
                    if (timeCount == 0) {
                        timer?.cancel()
                        //mDialog.dismiss()
                    }
                }
            }
        }
// 添加任务，设定开始计时器时间，第2个参数为时间单位毫秒，如果是0，立即执行
        timer?.schedule(timerTask, 0, 1000)
    }

    private var payData: MemberEntity.ProductDetail? = null;
    private fun getPayList() {
        ApiClient.videoInfoApi.getPayConfig("vip").compose(RxSchedulers.observableIO2Main())
            .subscribe(object : BaseObserver<MemberEntity>() {
                override fun onSuccess(result: MemberEntity?) {
                    if (!result?.goodsList.isNullOrEmpty()) {
                        if (result?.goodsList?.size!! >= 1) {
                            payData = result.goodsList!![0]
                            id_tv_vip_price.text = "${payData?.cash}元"
                            id_tv_vip_price2.text = payData?.cash
                            id_tv_vip_price3.text = "原价¥${payData?.originalPrice}"
                        }
                    }
                }

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