package com.duben.heliapp.ui.activitys

import android.animation.ValueAnimator
import android.app.Dialog
import android.content.Intent
import android.graphics.Color
import android.net.Uri
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.text.TextUtils
import android.util.Log
import android.view.KeyEvent
import android.view.View
import android.widget.CompoundButton
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.alipay.sdk.app.OpenAuthTask
import com.daimajia.androidanimations.library.Techniques
import com.daimajia.androidanimations.library.YoYo
import com.duben.heliapp.BuildConfig
import com.duben.heliapp.R
import com.duben.heliapp.common.AppConfig
import com.duben.heliapp.common.Constant
import com.duben.heliapp.manager.ActivityPageManager
import com.duben.heliapp.manager.UserManager
import com.duben.heliapp.mvp.model.*
import com.duben.heliapp.mvp.presenters.VipPresenter
import com.duben.heliapp.mvp.views.VipView
import com.duben.heliapp.ui.activitys.base.BaseActivity
import com.duben.heliapp.ui.adapter.VipAdapter
import com.duben.heliapp.ui.adapter.VipBannerAdapter
import com.duben.heliapp.ui.widgets.*
import com.duben.heliapp.ui.widgets.countdowntimer.CountDownTimerSupport
import com.duben.heliapp.ui.widgets.countdowntimer.OnCountDownTimerListener
import com.duben.library.utils.GlideUtils
import com.duben.library.utils.nodoubleclick.AntiShake
import com.duben.heliapp.utils.SpanUtils
import com.jobo.alipay.AliPay
import com.jobo.alipay.AlipayInfoImpl
import com.jobo.rxpay.RxPay
import com.jobo.rxpay.callback.IPayCallback
import com.jobo.wxpay.WXPay
import com.jobo.wxpay.WXPayInfoImpl
import com.tencent.mm.opensdk.modelbiz.WXLaunchMiniProgram
import com.tencent.mm.opensdk.openapi.IWXAPI
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import com.youth.banner.listener.OnPageChangeListener
import kotlinx.android.synthetic.main.activity_new_vip.*
import java.net.URLDecoder
import java.net.URLEncoder


/**
 * 描述：支付
 * 作者：孟崔广
 * 时间：2022/12/22 14:48
 */
class VipActivity : BaseActivity(), VipView, View.OnClickListener,
    VipAdapter.OnItemClickListener,
    CompoundButton.OnCheckedChangeListener {

    companion object {
        const val IS_DETAIL = "IS_DETAIL"//是否从剧集详情页进入
        const val IS_MAIN = "IS_MAIN"//是否从首页进入
        const val IS_RECOMMEND = "IS_RECOMMEND"//是否从推荐页进入
        const val wxAppId = BuildConfig.WEIXIN_APP_PAY_ID
        const val WEIXIN_PAY = "WEIXIN_PAY"
        const val ALIPAY = "ALIPAY"
        const val THIRD_ID = "THIRD_ID"
        const val VEDIO_ID = "VEDIO_ID"
        const val ENTER_TYPE_DIALOG = "ENTER_TYPE_DIALOG"
        const val ENTER_TYPE_ACTIVITY = "ENTER_TYPE_ACTIVITY"
    }

    var timer: CountDownTimerSupport? = null

    private var breathAnim: YoYo.YoYoString? = null
    private var payAgreementDialog: PayAgreementDialog? = null
    private var payYesDialog: PayYesDialog? = null
    private var ruleAgreementDialog: RuleAgreementDialog? = null

    private val vipPresenter by lazy { VipPresenter() }
    private lateinit var vipAdapter: VipAdapter
    private var vipList: MutableList<VipBean.ListBean>? = null
    private var isCheckAgreeFlag: Boolean = true
    private var isDetail: Boolean = false
    private var isMain: Boolean = false
    private var isRecommend: Boolean = false
    private var payType = WEIXIN_PAY// 支付类型
    private var vedioId = ""
    private var thirdId = ""

    private val mainHandler = Handler(Looper.getMainLooper())

    override fun getContentViewLayoutID() = R.layout.activity_new_vip

    override fun toggleOverridePendingTransition() = true

    override fun getOverridePendingTransitionMode() = TransitionMode.BOTTOM

    override fun isApplyKitKatTranslucency() = false

    override fun getBundleExtras(extras: Bundle?) {
        super.getBundleExtras(extras)
        extras?.let {
            isDetail = it.getBoolean(IS_DETAIL, false)
            isMain = it.getBoolean(IS_MAIN, false)
            isRecommend = it.getBoolean(IS_RECOMMEND, false)
            thirdId = it.getString(THIRD_ID, "")
            vedioId = it.getString(VEDIO_ID, "")
        }
    }

    override fun initViewsAndEvents() {
        vipPresenter.attachView(this)
        if (!TextUtils.isEmpty(UserManager.getInstance().userID)) {
            vipPresenter.getVipProducts(isAliPayInstalled())
        } else {
            vipPresenter.userLogin(isAliPayInstalled())
        }
        if (isDetail && UserManager.getInstance().newFlag) {
            AppConfig.showVipAdDialog = true
        }

        vipPresenter.orders()

        AppConfig.enterVipAct = true

        initListener()
    }

    override fun finish() {
        super.finish()
        //关闭窗体动画显示
        overridePendingTransition(0, R.anim.push_bottom_out)
    }

    override fun onResume() {
        super.onResume()
        if (AppConfig.enterAlipay) {
            AppConfig.enterAlipay = false
            showLoading("查询支付结果...")
            startTimer()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        if (!isMain) {
            AppConfig.enterVipAct = false
        }
        breathAnim?.stop()

        if (timer != null) { //防止计时器重复
            timer!!.stop()
            timer = null
        }

        vipPresenter.detachView()
    }

    override fun getVipProductSuc(data: VipBean) {
        if (!isFinishing) {
            if (data.list != null && data.list.size > 0) {
                vipList = data.list

                //设置content样式
                if (vipList != null && vipList!!.size > 0) {
                    setVipContent(vipList!![0])
                    cbVipAgreement.isChecked = data.isNeedClick
                }
                initRvView()
            }
        }
    }

    /**
     * 设置content样式
     */
    private fun setVipContent(bean: VipBean.ListBean) {
//        if (bean.isAlipay && bean.isWeixin) {
//            ll_vip_alipay.visibility = View.VISIBLE
//            ll_vip_wx.visibility = View.VISIBLE
//            payType = WEIXIN_PAY
//            iv_vip_wx.setImageResource(R.mipmap.ic_vip_enable_blue)
//            iv_vip_alipay.setImageResource(R.mipmap.ic_vip_none)
//        } else if (bean.isAlipay && !bean.isWeixin) {
//            ll_vip_alipay.visibility = View.VISIBLE
//            ll_vip_wx.visibility = View.GONE
//            payType = ALIPAY
//            iv_vip_alipay.setImageResource(R.mipmap.ic_vip_enable_blue)
//            iv_vip_wx.setImageResource(R.mipmap.ic_vip_none)
//        } else if (!bean.isAlipay && bean.isWeixin) {
//            ll_vip_alipay.visibility = View.GONE
//            ll_vip_wx.visibility = View.VISIBLE
//            payType = WEIXIN_PAY
//            iv_vip_wx.setImageResource(R.mipmap.ic_vip_enable_blue)
//            iv_vip_alipay.setImageResource(R.mipmap.ic_vip_none)
//        }

        ll_vip_alipay.visibility = View.VISIBLE
        ll_vip_wx.visibility = View.GONE
        payType = ALIPAY
        iv_vip_alipay.setImageResource(R.mipmap.ic_vip_enable_blue)
        iv_vip_wx.setImageResource(R.mipmap.ic_vip_none)


        if (!TextUtils.isEmpty(bean.remarks)) {
            tv_vip_hint.text = bean.remarks
            tv_vip_hint.visibility = View.VISIBLE
            if (bean.isShowCycTips) {
                tv_vip_hint.setTextColor(Color.parseColor("#FFAC5E"))
                tv_vip_hint.textSize = 12f
            } else {
                tv_vip_hint.setTextColor(Color.parseColor("#97ffffff"))
                tv_vip_hint.textSize = 10f
            }
        } else {
            tv_vip_hint.visibility = View.INVISIBLE
        }

        if (!TextUtils.isEmpty(bean.buttonText)) {
            if (bean.isShowCycTips) {
                tvVipPay.text = SpanUtils()
                    .append(bean.buttonText + "\n")
                    .setFontSize(20, true)
                    .append(bean.remarks)
                    .setFontSize(10, true)
                    .setForegroundColor(Color.parseColor("#A24240"))
                    .create()
            } else {
                tvVipPay.text = bean.buttonText
            }

            tvVipAgreement.text = "点击购买即表示您同意《自动续费协议》"
        } else {
            tvVipPay.text = "立即开通"
            tvVipAgreement.text = "点击购买即表示您同意《会员付费协议》"
        }
    }

    override fun getVipPayParamsSuc(payChannel: String, paramsBean: WxPayParamBean, enter: String) {
        if (!isFinishing) {
            if (TextUtils.equals(payChannel, "WEIXIN")) {
                if (paramsBean.params == null) {
                    showToast("微信支付维护中")
                    return
                }

                wxPay(paramsBean)
            } else {
                if (paramsBean.params == null) {
                    showToast("支付宝支付维护中")
                    return
                }

                if (vipList != null && vipList!!.size > 0) {
                    val vipBean = vipList!![vipAdapter.getPosition()]
                    val payToModel = vipBean.payToModel
                    //0 app内部，1.只签约转支付宝浏览器支付 2.带uid转支付宝小程序(暂定只有一个小程序)
                    when (payToModel) {
                        0 -> {
                            alipay(paramsBean)
                        }
                        1 -> {
                            openAutoAlipay(paramsBean.params.params)
                        }
                        2 -> {
                            if (TextUtils.equals(ENTER_TYPE_ACTIVITY, enter)) {
                                openAlipayApp(vipBean.payToModel2FirstAlipayAppid)
                            } else {
                                openAlipayApp(vipBean.payToModel2SecondAlipayAppid)
                            }
                        }
                        4 -> {
                            goAlipaySignExecute(paramsBean.params.params)
                        }
                    }
                }
            }
        }
    }

    override fun queryVipOrderSuc(isPay: Boolean) {
        if (isFinishing) return

        if (isPay) {
            showToast("支付成功")

//            if (isRecommend) {
//                finish()
//            } else {
//                if (!UserManager.getInstance().userIsLogin()) {
//                    val b = Bundle()
//                    b.putString(MobileLoginActivity.TYPE, "vip")
//                    readyGoThenKill(MobileLoginActivity::class.java, b)
//                } else {
//                    readyGoThenKill(MainActivity::class.java)
//                }
//            }
            if (!UserManager.getInstance().userIsLogin()) {
                val b = Bundle()
                b.putString(MobileLoginActivity.TYPE, "vip")
                readyGoThenKill(MobileLoginActivity::class.java, b)
            } else {
                readyGoThenKill(MainActivity::class.java)
            }
        }
    }

    override fun getUserSuc(data: UserBean) {
        if (data.expireTime > 0) {
            readyGo(MainActivity::class.java)
            val activity =
                ActivityPageManager.getInstance().getActivity(MainActivity::class.java)
            if (activity != null && activity is MainActivity) {
                activity.clickTab4Layout()
            }
        }
    }

    override fun ordersSuc(data: BannerList?) {
        data?.let {
            setBanner(it.list)
        }
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        when (keyCode) {
            KeyEvent.KEYCODE_BACK -> {
                if (UserManager.getInstance().newFlag
                    && vipList != null && vipList!!.size > 0
                ) {

                    vipAdapter.setPosition(0)
                    vipAdapter.notifyDataSetChanged()
                    val vipBean = vipList!![0]
                    if (vipBean.trial == 1) {
                        ll_vip_alipay.visibility = View.VISIBLE
                        ll_vip_wx.visibility = View.GONE
                        payType = ALIPAY
                        iv_vip_alipay.setImageResource(R.mipmap.ic_vip_enable_blue)
                        iv_vip_wx.setImageResource(R.mipmap.ic_vip_none)
                    }
                    backPayYesDialog(vipBean)
                    return true
                }

                finish()
            }
        }
        return true
    }

    override fun onClick(v: View?) {
        if (AntiShake.check(v?.id)) return

        when (v?.id) {
            R.id.ic_vip_quit -> {
                if (UserManager.getInstance().newFlag &&
                    vipList != null && vipList!!.size > 0
                ) {
                    vipAdapter.setPosition(0)
                    vipAdapter.notifyDataSetChanged()
                    val vipBean = vipList!![0]
                    if (vipBean.trial == 1) {
                        ll_vip_alipay.visibility = View.VISIBLE
                        ll_vip_wx.visibility = View.GONE
                        payType = ALIPAY
                        iv_vip_alipay.setImageResource(R.mipmap.ic_vip_enable_blue)
                        iv_vip_wx.setImageResource(R.mipmap.ic_vip_none)
                    } else {
                        payType = ALIPAY
                    }
                    backPayYesDialog(vipBean)
                } else {
                    finish()
                }
            }
            R.id.tvVipPay -> {
                if (vipList != null && vipList!!.size > 0) {
                    val vipBean = vipList!![vipAdapter.getPosition()]

                    if (!isCheckAgreeFlag) {
                        vipAgreementDialog(vipBean)
                        return
                    }

                    if (vipBean.isShowCycTips) {
                        agreementPayDialog()
                    } else {
                        vipPresenter.getVipPayParams(
                            payType,
                            vipBean.pid, isAliPayInstalled(),
                            ENTER_TYPE_ACTIVITY
                        )
                    }
                } else {
                    showToast("产品未配置")
                }
            }
            R.id.tvVipAgreement -> {
                val bundle = Bundle()
                bundle.putString(WebActivity.WEB_TITLE, getString(R.string.members_name))
                bundle.putString(WebActivity.WEB_URL, Constant.MEMBERS_URL)
                readyGo(WebActivity::class.java, bundle)
            }
            R.id.ll_vip_alipay -> {
                payType = ALIPAY
                iv_vip_alipay.setImageResource(R.mipmap.ic_vip_enable_blue)
                iv_vip_wx.setImageResource(R.mipmap.ic_vip_none)
            }
            R.id.ll_vip_wx -> {
                payType = WEIXIN_PAY
                iv_vip_wx.setImageResource(R.mipmap.ic_vip_enable_blue)
                iv_vip_alipay.setImageResource(R.mipmap.ic_vip_none)
            }
        }
    }

    private fun initRvView() {
        if (vipList != null && vipList!!.size > 0) {
            val gridLayoutManager = LinearLayoutManager(this)
            rvVip.layoutManager = gridLayoutManager
            vipAdapter = VipAdapter(vipList!!)
            rvVip.adapter = vipAdapter
            vipAdapter.setOnItemClickListener(this)
        }
    }

    private fun initListener() {
        shimmer_text?.postDelayed({
            shimmer_text?.startShimmerAnimation()
            breathAnim =
                YoYo.with(Techniques.Pulse).duration(700).repeat(-1).playOn(shimmer_text)
        }, 200)

        ic_vip_quit.setOnClickListener(this)
        tvVipPay.setOnClickListener(this)
        tvVipAgreement.setOnClickListener(this)
        ll_vip_alipay.setOnClickListener(this)
        ll_vip_wx.setOnClickListener(this)
        cbVipAgreement.setOnCheckedChangeListener(this)

    }

    override fun onItemClick(position: Int) {
        vipAdapter.setPosition(position)
        vipAdapter.notifyDataSetChanged()

        //设置content样式
        if (vipList != null && vipList!!.size > 0) {
            setVipContent(vipList!![position])
        }
    }

    fun wxPay(wxParanBean: WxPayParamBean) {
        val data = wxParanBean.params
        //实例化微信支付策略
        val wxPay: WXPay = WXPay.getInstance()
        //构造微信订单实体。一般都是由服务端直接返回。
        val wxPayInfoImpl = WXPayInfoImpl()
        wxPayInfoImpl.timestamp = data.timestamp
        wxPayInfoImpl.sign = data.sign
        wxPayInfoImpl.prepayId = data.prepayid
        wxPayInfoImpl.partnerid = data.partnerid
        wxPayInfoImpl.appid = wxAppId
        wxPayInfoImpl.nonceStr = data.noncestr
        wxPayInfoImpl.packageValue = data.packageX
        //策略场景类调起支付方法开始支付，以及接收回调。
        RxPay.pay(wxPay, this, wxPayInfoImpl, object : IPayCallback {
            override fun success() {
                AppConfig.showVipAdDialog = false
                UserManager.getInstance().vipFlag = true
                vipPresenter.queryVipOrder(wxParanBean.tid.toString(), true)
            }

            override fun failed(code: Int, message: String?) {
                vipPresenter.queryVipOrder(wxParanBean.tid.toString(), false)

            }

            override fun cancel() {
                vipPresenter.queryVipOrder(wxParanBean.tid.toString(), false)

            }
        })
    }

    fun alipay(wxParanBean: WxPayParamBean) {
        //实例化支付宝支付策略
        val aliPay = AliPay()
        //构造支付宝订单实体。一般都是由服务端直接返回。
        val alipayInfoImpl = AlipayInfoImpl()
        alipayInfoImpl.setOrderInfo(wxParanBean.params.params)
        //策略场景类调起支付方法开始支付，以及接收回调。
        RxPay.pay(aliPay, this, alipayInfoImpl, object : IPayCallback {
            override fun success() {
                AppConfig.showVipAdDialog = false
                UserManager.getInstance().vipFlag = true
                vipPresenter.queryVipOrder(wxParanBean.tid.toString(), true)
            }

            override fun failed(code: Int, message: String?) {
                vipPresenter.payError(code)
                if (!TextUtils.isEmpty(message)) {
                    showToast(message)
                }
            }

            override fun cancel() {
                vipPresenter.queryVipOrder(wxParanBean.tid.toString(), false)
            }
        })
    }

    /**
     * 检测是否安装支付宝
     *
     * true-安装支付宝
     */
    fun isAliPayInstalled(): Boolean {
        try {
            val uri: Uri = Uri.parse("alipays://platformapi/startApp")
            val intent = Intent(Intent.ACTION_VIEW, uri)
            val componentName = intent.resolveActivity(context.getPackageManager())
            return componentName != null
        } catch (e: Exception) {
            e.printStackTrace()
            return false
        }
    }

    /**
     * 自动续费
     */
    fun openAutoAlipay(url: String) {
        AppConfig.enterAlipay = true
        val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
        startActivity(intent)
    }

    override fun onCheckedChanged(buttonView: CompoundButton?, isChecked: Boolean) {
        isCheckAgreeFlag = isChecked
    }

    /**
     * 返回支付弹窗-签约
     */
    private fun backPayYesDialog(vipBean: VipBean.ListBean) {
        payYesDialog = PayYesDialog(context, vipBean, object : DialogListener() {
            override fun onClick(v: View) {
                if (!isFinishing() && payYesDialog != null && payYesDialog!!.isShowing()) {
                    payYesDialog!!.dismiss()
                }
                when (v.id) {
                    R.id.iv_dialog_vip_quit -> {
                        finish()
//                        payYesDialog!!.dismiss()
                    }
                    R.id.tv_dialog_vip_next -> {
                        cbVipAgreement.isChecked = true

                        if (vipList != null && vipList!!.size > 0) {
                            val vipBean = vipList!![vipAdapter.getPosition()]
                            vipPresenter.getVipPayParams(
                                payType,
                                vipBean.pid, isAliPayInstalled(),
                                ENTER_TYPE_DIALOG

                            )
                        } else {
                            showToast("产品未配置")
                        }
                    }
                }
            }
        })
        payYesDialog!!.show()
    }

    /**
     * 自动续费协议弹窗-支付宝
     */
    private fun agreementPayDialog() {
        payAgreementDialog = PayAgreementDialog(context, object : DialogListener() {
            override fun onClick(v: View) {
                if (!isFinishing() && payAgreementDialog != null && payAgreementDialog!!.isShowing()) {
                    payAgreementDialog!!.dismiss()
                }
                when (v.id) {
                    R.id.tv_agreement_next -> {
                        ruleAgreementPayDialog()
                    }
                }
            }
        })
        payAgreementDialog!!.show()
    }

    /**
     * 试用订阅规则说明-仿支付宝
     */
    private fun ruleAgreementPayDialog() {
        if (vipList != null && vipList!!.size > 0) {
            val vipBean = vipList!![vipAdapter.getPosition()]
            ruleAgreementDialog = RuleAgreementDialog(context, object : DialogListener() {
                override fun onClick(v: View) {
                    if (!isFinishing() && ruleAgreementDialog != null && ruleAgreementDialog!!.isShowing()) {
                        ruleAgreementDialog!!.dismiss()
                    }
                    when (v.id) {
                        R.id.tv_agreement_next -> {
                            vipPresenter.getVipPayParams(
                                payType,
                                vipBean.pid, isAliPayInstalled(),
                                ENTER_TYPE_ACTIVITY
                            )
                        }
                    }
                }
            })
            ruleAgreementDialog!!.setText(
                vipBean.remarks,
                vipBean.trialFirstDay,
                vipBean.price,
                vipBean.title
            )
            ruleAgreementDialog!!.show()
        } else {
            showToast("产品未配置")
        }
    }

    /**
     * 未勾选协议弹窗
     */
    private fun vipAgreementDialog(bean: VipBean.ListBean) {
        var agreeStr = "会员付费协议"
        if (bean.isShowCycTips) {
            agreeStr = "自动续费协议"
        }
        val cdaa = CustomDialogAgreement(context, object : DialogListener() {
            override fun onClick(dialog: Dialog?, v: View?) {
                dialog?.dismiss()
                when (v?.id) {
                    R.id.dialog_btn_right -> {
                        cbVipAgreement.isChecked = true


                        if (vipList != null && vipList!!.size > 0) {
                            val vipBean = vipList!![vipAdapter.getPosition()]
                            if (vipBean.isShowCycTips) {
                                agreementPayDialog()
                            } else {
                                vipPresenter.getVipPayParams(
                                    payType,
                                    vipBean.pid, isAliPayInstalled(),
                                    ENTER_TYPE_ACTIVITY
                                )
                            }
                        } else {
                            showToast("产品未配置")
                        }
                    }
                }
            }
        })
        cdaa.setTitle(agreeStr)
        cdaa.setContent(agreeStr)
        cdaa.setLeft("不同意")
        cdaa.setLeftColor(R.color.gray)
        cdaa.setRight("同意")
        cdaa.setRightColor(R.color.main_mints)
        cdaa.show()
    }

    private fun setBanner(data: List<VedioBean>) {
        mainHandler.postDelayed({
            val scrollToBottomAnimator =
                ValueAnimator.ofInt(0, nsv.getChildAt(0).height - nsv.height)
            scrollToBottomAnimator.addUpdateListener { animator ->
                val value = animator.animatedValue as Int
                nsv.scrollTo(0, value)
            }
            scrollToBottomAnimator.duration = 2000
            scrollToBottomAnimator.start()
        }, 500)

        mainHandler.postDelayed({
            val scrollToTopAnimator = ValueAnimator.ofInt(nsv.scrollY, 0)
            scrollToTopAnimator.addUpdateListener { animator ->
                val value = animator.animatedValue as Int
                nsv.scrollTo(0, value)
            }
            scrollToTopAnimator.duration = 1500
            scrollToTopAnimator.start()
        }, 3000)

        val adapter = VipBannerAdapter(data)
        // 绑定生命周期
        vip_banner.addBannerLifecycleObserver(this)
            .setBannerGalleryEffect(80, 15, 0.8f)
            .setAdapter(adapter)
            .addOnPageChangeListener(object : OnPageChangeListener {
                override fun onPageScrolled(
                    position: Int,
                    positionOffset: Float,
                    positionOffsetPixels: Int
                ) {
                }

                override fun onPageSelected(position: Int) {
                    GlideUtils.loadBlurImageView(mContext, data[position].coverImage, iv_blur)
                    tv_banner_title.text = String.format("《%1s》", data[position].title)
                }

                override fun onPageScrollStateChanged(state: Int) {}
            })
        GlideUtils.loadBlurImageView(mContext, data[0].coverImage, iv_blur)
        tv_banner_title.text = String.format("《%1s》", data[0].title)
    }

    fun startTimer() {
        if (timer != null) { //防止计时器重复
            timer!!.stop()
            timer = null
        }
        timer = CountDownTimerSupport(9000, 1000)
        timer!!.setOnCountDownTimerListener(object : OnCountDownTimerListener {
            override fun onTick(millisUntilFinished: Long) {
                if (!isFinishing) {
                    if (millisUntilFinished == 4000L) {
                        vipPresenter.getMyInfo()
                    }
                }
            }

            override fun onFinish() {
                if (!isFinishing) {
                    hideLoading()
                    vipPresenter.getMyInfo()
                }
            }
        })
        timer!!.start()
    }

    /**
     * 跳转支付宝小程序
     */
    private fun openAlipayApp(alipayAppId: String) {
        AppConfig.enterAlipay = true
        try {
//            val alipayAppId = "2021004157617228"
            val path =
                "app_uid=" + UserManager.getInstance().userID + "&package_app=" + Constant.MINTS_PKG_NAME//这里是传的参数
            val link = URLEncoder.encode(path, "UTF-8")//这里是encode传的参数
            val url =
//                "alipays://platformapi/startapp?appId=2021004129666486&page=pages/loading&query=" + link
                "alipays://platformapi/startapp?appId=" + alipayAppId + "&page=pages/loading&query=" + link
            val uri = Uri.parse(url) // url为你要链接的地址
            val intent = Intent(Intent.ACTION_VIEW, uri)
            startActivity(intent)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    private fun openWxApp() {
        //        AppConfig.enterAlipay = true
        try {
            val appId = "wx263e5304a9a67d7c" // 填移动应用(App)的 AppId，非小程序的 AppID
            val api: IWXAPI = WXAPIFactory.createWXAPI(context, appId)
            val req = WXLaunchMiniProgram.Req()
            req.userName = "gh_439c32026e1b" // 填小程序原始id
            req.path =
                "/pages/loading?testApp1=mcg1&testApp2=mcg2" ////拉起小程序页面的可带参路径，不填默认拉起小程序首页，对于小游戏，可以只传入 query 部分，来实现传参效果，如：传入 "?foo=bar"。
            req.miniprogramType =
                WXLaunchMiniProgram.Req.MINIPTOGRAM_TYPE_RELEASE // 可选打开 开发版，体验版和正式版
            api.sendReq(req)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 唤起独立签约-拿到结果
     *
     * @param signParams
     */
    private fun goAlipaySignExecute(signParams: String) {
        AppConfig.enterAlipay = true
        try {
            val openAuthTask = OpenAuthTask(this)
            val map: MutableMap<String, String> = HashMap()
            map["sign_params"] = signParams
            openAuthTask.execute(
                "com.duben.heliapp.ui.activitys.VipActivity",
                OpenAuthTask.BizType.Deduct,
                map,
                { resultCode: Int, memo: String?, bundle: Bundle ->
                    if (resultCode == OpenAuthTask.OK) {
                        // 对业务完成的结果做后续处理

                    } else {
                        // 对业务失败的结果做后续处理
                        showToast("支付失败")
                    }
                },
                true
            )
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
}