package com.cheng.blzb.ui.fragment.mine.vip

import android.animation.ValueAnimator
import android.annotation.SuppressLint
import android.text.TextUtils
import android.view.View
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.content.ContextCompat
import androidx.core.view.isVisible
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bytedance.ads.convert.event.ConvertReportHelper
import com.cheng.blzb.R
import com.cheng.blzb.bean.CorpEntity
import com.cheng.blzb.bean.OrderPayEntity
import com.cheng.blzb.bean.UserEntity
import com.cheng.blzb.bean.VipGoodsEntity
import com.cheng.blzb.common.Constants
import com.cheng.blzb.common.EventConstants
import com.cheng.blzb.databinding.FragmentVipBinding
import com.cheng.blzb.event.PayStatusEnum
import com.cheng.blzb.event.PayStatusEvent
import com.cheng.blzb.event.PaySuccessEvent
import com.cheng.blzb.manager.DialogEnum
import com.cheng.blzb.manager.EventReportManager
import com.cheng.blzb.manager.LoginManager
import com.cheng.blzb.manager.UserConfigManager
import com.cheng.blzb.ui.activity.PublicActivity
import com.cheng.blzb.ui.dialog.PayTipDialog
import com.cheng.blzb.ui.dialog.TipDialog
import com.cheng.blzb.ui.fragment.mine.order.cert.CertificateFragment
import com.cheng.blzb.utils.DateUtils
import com.cheng.blzb.utils.UrlHelper
import com.cheng.blzb.utils.pay.PayUtils
import com.example.base.common.RxBus
import com.example.base.common.RxCountDown
import com.example.base.decoration.GridSpaceItemDecoration
import com.example.base.decoration.SpacesItemDecoration
import com.example.base.extensions.getColor
import com.example.base.extensions.gone
import com.example.base.extensions.setStatusBarLight
import com.example.base.extensions.toast
import com.example.base.extensions.visible
import com.example.base.ui.BaseFragment
import com.example.base.utils.DensityUtils
import com.example.base.utils.SpanUtils
import com.google.gson.Gson
import com.tencent.mm.opensdk.openapi.IWXAPI
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.disposables.Disposable
import org.jetbrains.anko.sdk27.listeners.onCheckedChange
import org.jetbrains.anko.sdk27.listeners.onClick
import org.jetbrains.anko.sdk27.listeners.onTouch
import java.text.DecimalFormat
import java.util.concurrent.TimeUnit

class VipFragment : BaseFragment<FragmentVipBinding, VipViewModel>() {
    private val origin by lazy { arguments?.getString("origin") ?: "center" }

    private var vipType = 0 // 0 个人版 1 企业版

    private lateinit var api: IWXAPI
    private var isAgree = false
    //是否显示订单支付结果查询提示
    private var showQueryTip = false
    private var payType = 0 //0微信支付 1支付宝支付
    private var totalPrice = 0f
    private var lastGoodsPrice = 0f

    private var seatPrice = 0f
    private var seatCount = 0
    private var seatCountLimit = 3

    private var goodsAdapter =  VipGoodsAdapter(vipType)

    private val userTipsList = mutableListOf<String>()
    private val userTipsAdapter by lazy { VipUserTipsAdapter(requireContext(), userTipsList) }

    private var userInfo: UserEntity? = null
    private var goodsEntity: VipGoodsEntity? = null
    private var orderEntity: OrderPayEntity? = null
    private var corpInfo: CorpEntity? = null

    private var payTypeCheckedRes = R.mipmap.ic_pay_checked1

    private var countdownDisposable: Disposable? = null
    private var scrollTask: Disposable? = null

    override fun initView() {
        super.initView()
        setBackColor(R.color.white)
        setStatusBarLight(false)
        updatePageStyle()
        checkPayType()

        binding.rvUserTips.adapter = userTipsAdapter

        binding.rvGoods.adapter = goodsAdapter

        binding.cbAgree.visibility = if (UserConfigManager.isPayAgreementEnable()) View.VISIBLE else View.GONE
        binding.tvAgree.visibility = if (UserConfigManager.isPayAgreementEnable()) View.VISIBLE else View.GONE

        binding.tvPrice.typeface = Constants.dDIN_PRO_M
    }

    override fun initData() {
        super.initData()
        api = WXAPIFactory.createWXAPI(requireContext(), Constants.WechatAppId)

        mViewModel.userInfo()
        mViewModel.getPayUserTips()
        mViewModel.getGoodsList(if (vipType == 0) "member" else "corp")
        mViewModel.getCorpInfo()
    }

    @SuppressLint("NotifyDataSetChanged", "SetTextI18n")
    override fun initListener() {
        super.initListener()
        binding.rvUserTips.onTouch { _, _ -> true }

        goodsAdapter.setOnItemClickListener { _, _, i ->
            val item = goodsAdapter.getItem(i)
            if (item.goods_id == goodsEntity?.goods_id) return@setOnItemClickListener
            goodsAdapter.data.forEach { it.checked = it.goods_id == item.goods_id }
            goodsAdapter.notifyDataSetChanged()

            goodsEntity = item
            if (vipType == 1) {
                seatCountLimit = goodsEntity!!.member_limit.toInt()
                if (seatCount < seatCountLimit) seatCount = seatCountLimit
                binding.tvSeatPrice.text = "+￥${DecimalFormat("0.##").format(goodsEntity!!.member_price.toFloat())}"
                SpanUtils.with(binding.tvSeatOriginPrice)
                    .append("(原￥${DecimalFormat("0.##").format(goodsEntity!!.origin_member_price.toFloat())})")
                    .setStrikethrough()
                    .create()
                setSeatCount()

                seatPrice = (seatCount - seatCountLimit) * (goodsEntity?.member_price?.toFloat() ?: 0f)
                setPrice(goodsEntity!!.price.toFloat() + seatPrice)
            } else {
                setPrice(goodsEntity!!.price.toFloat())
            }
            releasePayType()
        }

        binding.btnTab1.onClick {
            if (vipType != 0) {
                vipType = 0
                updatePageStyle()
            }
        }

        binding.btnTab2.onClick {
            if (vipType != 1) {
                vipType = 1
                updatePageStyle()
            }
        }

        binding.ivAdd.onClick {
            seatCount++
            setSeatCount()

            seatPrice = (seatCount - seatCountLimit) * goodsEntity!!.member_price.toFloat()
            setPrice(goodsEntity!!.price.toFloat() + seatPrice)

            binding.ivSubtract.setImageResource(R.mipmap.ic_subtract_count_enable)
        }

        binding.ivSubtract.onClick {
            if (seatCount > seatCountLimit) {
                seatCount--
                setSeatCount()

                seatPrice = (seatCount - seatCountLimit) * goodsEntity!!.member_price.toFloat()
                setPrice(goodsEntity!!.price.toFloat() + seatPrice)

                binding.ivSubtract.setImageResource(if (seatCount > seatCountLimit) R.mipmap.ic_subtract_count_enable else R.mipmap.ic_subtract_count_disable)
            }
        }

        binding.tvAliPay.onClick {
            payType = 1
            checkPayType()
        }

        binding.tvWxPay.onClick {
            payType = 0
            checkPayType()
        }

        binding.tvBankPay.onClick {
            payType = 2
            checkPayType()
        }

        binding.cbAgree.onCheckedChange { _, isChecked ->
            isAgree = isChecked
        }

        binding.tvAgree.onClick {
            binding.cbAgree.isChecked = !binding.cbAgree.isChecked
        }

        binding.tvPay.onClick {
            if (goodsEntity == null) return@onClick
            if (!UserConfigManager.getNoLoginPay() && !LoginManager.isLogin()) {
                toast("请登录后支付")
                return@onClick
            }
            if (payType == 0 && !api.isWXAppInstalled) {
                toast("您没有安装微信客户端,请先下载安装")
                return@onClick
            }
            if (UserConfigManager.isPayAgreementEnable() && !isAgree) {
                val f = PayTipDialog.newInstance(showAgreement = true, showRenew = !TextUtils.isEmpty(goodsEntity?.sign_value) && payType == 1)
                f.setOnSelectListener {
                    binding.cbAgree.isChecked = true
                    if (payType == 0) {
                        if (!TextUtils.isEmpty(goodsEntity!!.weixinMpOriId)) {
                            mViewModel.payCreateOrder(goodsEntity!!.goods_id, "combo", origin, "${seatCount - seatCountLimit}")
                        } else {
                            mViewModel.payCreateOrder(goodsEntity!!.goods_id, "weixin", origin, "${seatCount - seatCountLimit}")
                        }
                    } else if (payType == 1) {
                        mViewModel.payCreateOrder(goodsEntity!!.goods_id, "alipay", origin, "${seatCount - seatCountLimit}")
                    } else if (payType == 2) {
                        mViewModel.payCreateOrder(goodsEntity!!.goods_id, "bank", origin, "${seatCount - seatCountLimit}")
                    }
                }
                f.show(childFragmentManager, PayTipDialog::class.java.simpleName)
            } else {
                if (payType == 0) {
                    if (!TextUtils.isEmpty(goodsEntity!!.weixinMpOriId)) {
                        mViewModel.payCreateOrder(goodsEntity!!.goods_id, "combo", origin, "${seatCount - seatCountLimit}")
                    } else {
                        mViewModel.payCreateOrder(goodsEntity!!.goods_id, "weixin", origin, "${seatCount - seatCountLimit}")
                    }
                } else if (payType == 1) {
                    mViewModel.payCreateOrder(goodsEntity!!.goods_id, "alipay", origin, "${seatCount - seatCountLimit}")
                } else if (payType == 2) {
                    mViewModel.payCreateOrder(goodsEntity!!.goods_id, "bank", origin, "${seatCount - seatCountLimit}")
                }
            }
            EventReportManager.eventReport(
                EventConstants.PAY_PAY,
                if (payType == 0) "weixin" else if (payType == 1) "alipay" else "bank",
                Gson().toJson(goodsEntity)
            )
        }
    }

    @SuppressLint("NotifyDataSetChanged", "SetTextI18n")
    override fun initObserve() {
        super.initObserve()
        mViewModel.userInfoLiveData.observe(this) {
            userInfo = it
            if (TextUtils.isEmpty(it.vip_expire)) {
                binding.layoutCountdown.visible()
                startCountdown(DateUtils.getDayEndTime() - System.currentTimeMillis() / 1000)
            } else {
                binding.layoutCountdown.gone()
            }
        }

        mViewModel.goodsListLiveData.observe(this) { list ->
            goodsAdapter.data.forEach { _ ->
                if (binding.rvGoods.itemDecorationCount > 0) {
                    binding.rvGoods.removeItemDecorationAt(0)
                }
            }
            if (list.size <= 3) {
                binding.rvGoods.layoutManager = GridLayoutManager(requireContext(), 3)
                binding.rvGoods.addItemDecoration(GridSpaceItemDecoration(3, 0, DensityUtils.dp2px(6f)))
            } else {
                binding.rvGoods.layoutManager = LinearLayoutManager(requireContext(), RecyclerView.HORIZONTAL, false)
                binding.rvGoods.addItemDecoration(SpacesItemDecoration(DensityUtils.dp2px(12f), RecyclerView.HORIZONTAL))
            }
            goodsAdapter.type = vipType
            goodsAdapter.setList(list)

            goodsEntity = list.find { it.checked }
            if (goodsEntity == null && list.isNotEmpty()) {
                goodsEntity = list[0]
            }
            if (goodsEntity != null) {
                if (vipType == 1) {
                    seatCountLimit = goodsEntity!!.member_limit.toInt()
                    if (seatCount < seatCountLimit) seatCount = seatCountLimit
                    binding.tvSeatPrice.text = "+￥${DecimalFormat("0.##").format(goodsEntity!!.member_price.toFloat())}"
                    SpanUtils.with(binding.tvSeatOriginPrice)
                        .append("(原￥${DecimalFormat("0.##").format(goodsEntity!!.origin_member_price.toFloat())})")
                        .setStrikethrough()
                        .create()
                    setSeatCount()

                    seatPrice = (seatCount - seatCountLimit) * (goodsEntity?.member_price?.toFloat() ?: 0f)
                    setPrice(goodsEntity!!.price.toFloat() + seatPrice)
                } else {
                    setPrice(goodsEntity!!.price.toFloat())
                }
                releasePayType()
            }
            initPrivacyTv()
        }

        mViewModel.corpInfoLiveData.observe(this) {
            corpInfo = it
            if (!TextUtils.isEmpty(it.sub_user_limit)) {
                seatCount = corpInfo!!.sub_user_limit.toInt()
            }
            setSeatCount()
        }

        mViewModel.createOrderLiveData.observe(this) {
            orderEntity = it
            if (payType == 0) {
                if (!TextUtils.isEmpty(goodsEntity?.weixinMpOriId)) {
                    PayUtils.toWXMPPay(requireActivity(), it.outTradeNo, goodsEntity!!.weixinMpOriId)
                    showQueryTip = true
                } else {
                    PayUtils.toWXPay(requireActivity(), it)
                }
            } else if (payType == 1) {
                PayUtils.toAliPay(requireActivity(), it.payParam, "")
            } else {
                PublicActivity.start(requireContext(), CertificateFragment::class.java, Pair("orderId", orderEntity!!.orderId))
            }
        }

        mViewModel.orderInfoLiveData.observe(this) {
            if (it.status == "2") {
                toast("支付成功")
                sendBDReport(true)
                EventReportManager.eventReport(
                    EventConstants.PAY_SUCCESS,
                    if (payType == 0) "weixin" else "alipay",
                    "{orderId:${orderEntity?.orderId}, meal:${Gson().toJson(goodsEntity)}}"
                )
                RxBus.defaultInstance.post(PaySuccessEvent())
                requireActivity().finish()
            }
        }

        mViewModel.payTipsLiveData.observe(this) {
            userTipsList.addAll(it)
            userTipsAdapter.notifyDataSetChanged()
            startScroll()
        }

        val payStatusDisposable = RxBus.defaultInstance.toObservable(PayStatusEvent::class.java).subscribe {
            when (it.payStatus) {
                PayStatusEnum.PAY_SUCCESS -> {
                    mViewModel.getOrderInfo(orderEntity!!.orderId)
                }

                PayStatusEnum.PAY_CANCEL -> {
                    toast("已取消支付")
                    sendBDReport(false)
                    EventReportManager.eventReport(EventConstants.PAY_CANCEL, if (payType == 0) "weixin" else "alipay", "{orderId:${orderEntity?.orderId}")
                }

                else -> {
                    toast("已取消支付")
                    sendBDReport(false)
                    EventReportManager.eventReport(if (payType == 0) EventConstants.ERROR_CLIENT_WXPAY_ERR else EventConstants.ERROR_CLIENT_ALIPAY_ERR, "{orderId:${orderEntity?.orderId}", it.message)
                }
            }
        }
        addDisposable(payStatusDisposable)
    }

    private fun showQueryTipDialog() {
        if (showQueryTip) {
            val f = TipDialog.newInstance("温馨提示", "是否已完成支付", "未支付", "已支付", false)
            f.setOnSelectListener {
                if (it == DialogEnum.CLICK_OK) {
                    mViewModel.getOrderInfo(orderEntity!!.orderId)
                }
            }
            f.show(childFragmentManager, TipDialog::class.java.simpleName)
            showQueryTip = false
        }
    }

    private fun checkPayType() {
        if (payType == 0) {
            val start1 = ContextCompat.getDrawable(requireContext(), R.mipmap.ic_wx_pay)
            val end1 = ContextCompat.getDrawable(requireContext(), payTypeCheckedRes)
            binding.tvWxPay.setCompoundDrawablesRelativeWithIntrinsicBounds(start1, null, end1, null)

            val start2 = ContextCompat.getDrawable(requireContext(), R.mipmap.ic_ali_pay)
            val end2 = ContextCompat.getDrawable(requireContext(), R.mipmap.ic_pay_default)
            binding.tvAliPay.setCompoundDrawablesRelativeWithIntrinsicBounds(start2, null, end2, null)

            val start3 = ContextCompat.getDrawable(requireContext(), R.mipmap.ic_transfer_pay)
            val end3 = ContextCompat.getDrawable(requireContext(), R.mipmap.ic_pay_default)
            binding.tvBankPay.setCompoundDrawablesRelativeWithIntrinsicBounds(start3, null, end3, null)
        } else if (payType == 1) {
            val start1 = ContextCompat.getDrawable(requireContext(), R.mipmap.ic_ali_pay)
            val end1 = ContextCompat.getDrawable(requireContext(), payTypeCheckedRes)
            binding.tvAliPay.setCompoundDrawablesRelativeWithIntrinsicBounds(start1, null, end1, null)

            val start2 = ContextCompat.getDrawable(requireContext(), R.mipmap.ic_wx_pay)
            val end2 = ContextCompat.getDrawable(requireContext(), R.mipmap.ic_pay_default)
            binding.tvWxPay.setCompoundDrawablesRelativeWithIntrinsicBounds(start2, null, end2, null)

            val start3 = ContextCompat.getDrawable(requireContext(), R.mipmap.ic_transfer_pay)
            val end3 = ContextCompat.getDrawable(requireContext(), R.mipmap.ic_pay_default)
            binding.tvBankPay.setCompoundDrawablesRelativeWithIntrinsicBounds(start3, null, end3, null)
        } else {
            val start1 = ContextCompat.getDrawable(requireContext(), R.mipmap.ic_transfer_pay)
            val end1 = ContextCompat.getDrawable(requireContext(), payTypeCheckedRes)
            binding.tvBankPay.setCompoundDrawablesRelativeWithIntrinsicBounds(start1, null, end1, null)

            val start2 = ContextCompat.getDrawable(requireContext(), R.mipmap.ic_ali_pay)
            val end2 = ContextCompat.getDrawable(requireContext(), R.mipmap.ic_pay_default)
            binding.tvAliPay.setCompoundDrawablesRelativeWithIntrinsicBounds(start2, null, end2, null)

            val start3 = ContextCompat.getDrawable(requireContext(), R.mipmap.ic_wx_pay)
            val end3 = ContextCompat.getDrawable(requireContext(), R.mipmap.ic_pay_default)
            binding.tvWxPay.setCompoundDrawablesRelativeWithIntrinsicBounds(start3, null, end3, null)
        }
        initPrivacyTv()
    }

    private fun releasePayType() {
        val list = goodsEntity?.pay_type?.split(",")?.map { it.trim() }?.toList()
        val globalPayType = UserConfigManager.getPayType()
        if (list?.find { it == "weixin" } != null && globalPayType.find { it == "weixin" } != null) {
            binding.tvWxPay.visible()
        } else {
            binding.tvWxPay.gone()
        }
        if (list?.find { it == "alipay" } != null && globalPayType.find { it == "alipay" } != null) {
            binding.tvAliPay.visible()
        } else {
            binding.tvAliPay.gone()
        }
        if (list?.find { it == "bank" } != null && globalPayType.find { it == "bank" } != null) {
            binding.tvBankPay.visible()
        } else {
            binding.tvBankPay.gone()
        }

        if (goodsEntity?.pay_type!!.startsWith("weixin") && binding.tvWxPay.isVisible) {
            payType = 0
        }
        if (goodsEntity?.pay_type!!.startsWith("alipay") && binding.tvAliPay.isVisible) {
            payType = 1
        }
        if (goodsEntity?.pay_type!!.startsWith("bank") && binding.tvBankPay.isVisible) {
            payType = 2
        }

        checkPayType()
    }

    private fun initPrivacyTv() {
        val spanUtils = SpanUtils.with(binding.tvAgree)
            .append("我已阅读并同意")
            .append("《会员服务协议规则》")
            .setClickSpan(getColor(R.color.color_ff493c), false) {
                UrlHelper.startUserAgreement(requireContext(), "会员服务协议规则")
            }
        if (!TextUtils.isEmpty(goodsEntity?.sign_value?.trim()) && payType == 1) {
            spanUtils.append("和")
            spanUtils.append("《自动续费服务规则》")
            spanUtils.setClickSpan(getColor(R.color.color_ff493c), false) {
                UrlHelper.startRenewAgreement(requireContext())
            }
        }
        spanUtils.create()
    }

    private fun setSeatCount() {
        binding.tvCount.text = "$seatCount"
        SpanUtils.with(binding.tvSeatTip2)
            .append("当前")
            .append("1个")
            .setForegroundColor(getColor(R.color.color_146847))
            .append("主号+")
            .append("${seatCount}个")
            .setForegroundColor(getColor(R.color.color_146847))
            .append("席位")
            .create()
    }

    @SuppressLint("SetTextI18n")
    private fun setPrice(price: Float) {
        lastGoodsPrice = totalPrice
        totalPrice = if (price < 0) 0f else price

        val valueAnim = ValueAnimator.ofFloat(0f, 1f).setDuration(500)
        valueAnim.addUpdateListener {
            val percent = it.animatedValue as Float
            val diffPrice = totalPrice - lastGoodsPrice
            val animPrice = if (percent == 1f) totalPrice * percent else (lastGoodsPrice + diffPrice * percent).toInt()
            SpanUtils.with(binding.tvPrice)
                .append("￥")
                .setFontSize(13, true)
                .append(DecimalFormat("0.##").format(animPrice))
                .append(formatPricePeriod(goodsEntity!!.value))
                .setFontSize(13, true)
                .create()
        }
        valueAnim.start()
    }

    private fun formatPricePeriod(value: String): String {
        if (value == "#") {
            return "/终生"
        } else if (value.endsWith("m")) {
            val monthStr = value.replace("m", "")
            if (!TextUtils.isEmpty(monthStr)) {
                val month = monthStr.toInt()
                return if (month >= 12) {
                    "/${if (month / 12 > 1) "${month / 12}" else ""}年"
                } else if (month % 3 == 0) {
                    "/${if (month / 3 > 1) "${month / 3}" else ""}季"
                } else {
                    "/${if (month > 1) "$month" else ""}月"
                }
            }
        }
        return ""
    }

    private fun updatePageStyle() {
        mViewModel.getGoodsList(if (vipType == 0) "member" else "corp")
        if (vipType == 0) {
            payTypeCheckedRes = R.mipmap.ic_pay_checked1

            binding.btnTab1.setTextColor(getColor(R.color.color_fff5e6))
            binding.btnTab1.setCompoundDrawablesWithIntrinsicBounds(R.drawable.shape_vip_tab_checked1, 0, 0, 0)
            binding.btnTab2.setTextColor(getColor(R.color.color_1b6648))
            binding.btnTab2.setCompoundDrawablesWithIntrinsicBounds(R.drawable.shape_vip_tab_default2, 0, 0, 0)

            binding.ivTopBg.setImageResource(R.mipmap.ic_vip_top_bg1)
            binding.layoutPay.setBackgroundResource(R.mipmap.ic_vip_pay_bg1)
            binding.layoutPayBtn.setBackgroundResource(R.mipmap.ic_vip_pay_btn_bg1)

            val tipsLp = binding.ivTips.layoutParams as ConstraintLayout.LayoutParams
            tipsLp.dimensionRatio = "h,1030:1010"
            binding.ivTips.layoutParams = tipsLp
            binding.ivTips.setImageResource(R.mipmap.ic_vip_tips1)

            binding.tvDay.setBackgroundResource(R.drawable.shape_vip_countdown_bg1)
            binding.tvHour.setBackgroundResource(R.drawable.shape_vip_countdown_bg1)
            binding.tvMinute.setBackgroundResource(R.drawable.shape_vip_countdown_bg1)
            binding.tvSecond.setBackgroundResource(R.drawable.shape_vip_countdown_bg1)
            binding.tvDay.setTextColor(getColor(R.color.color_7e4024))
            binding.tvHour.setTextColor(getColor(R.color.color_7e4024))
            binding.tvMinute.setTextColor(getColor(R.color.color_7e4024))
            binding.tvSecond.setTextColor(getColor(R.color.color_7e4024))

            binding.tvPrice.setTextColor(getColor(R.color.color_fff4e6))
            binding.tvInvoice.setTextColor(getColor(R.color.color_ecc9ae))
            binding.tvPay.setTextColor(getColor(R.color.color_703d27))

            binding.layoutSeat.gone()
        } else {
            payTypeCheckedRes = R.mipmap.ic_pay_checked2

            binding.btnTab1.setTextColor(getColor(R.color.color_8a7570))
            binding.btnTab1.setCompoundDrawablesWithIntrinsicBounds(R.drawable.shape_vip_tab_default1, 0, 0, 0)
            binding.btnTab2.setTextColor(getColor(R.color.color_c5ffe1))
            binding.btnTab2.setCompoundDrawablesWithIntrinsicBounds(R.drawable.shape_vip_tab_checked2, 0, 0, 0)

            binding.ivTopBg.setImageResource(R.mipmap.ic_vip_top_bg2)
            binding.layoutPay.setBackgroundResource(R.mipmap.ic_vip_pay_bg2)
            binding.layoutPayBtn.setBackgroundResource(R.mipmap.ic_vip_pay_btn_bg2)

            val tipsLp = binding.ivTips.layoutParams as ConstraintLayout.LayoutParams
            tipsLp.dimensionRatio = "h,1030:1301"
            binding.ivTips.layoutParams = tipsLp
            binding.ivTips.setImageResource(R.mipmap.ic_vip_tips2)

            SpanUtils.with(binding.tvSeatTip1)
                .append("增加")
                .append("1个")
                .setForegroundColor(getColor(R.color.color_146847))
                .append("席位")
                .create()

            binding.tvDay.setBackgroundResource(R.drawable.shape_vip_countdown_bg2)
            binding.tvHour.setBackgroundResource(R.drawable.shape_vip_countdown_bg2)
            binding.tvMinute.setBackgroundResource(R.drawable.shape_vip_countdown_bg2)
            binding.tvSecond.setBackgroundResource(R.drawable.shape_vip_countdown_bg2)
            binding.tvDay.setTextColor(getColor(R.color.color_09321d))
            binding.tvHour.setTextColor(getColor(R.color.color_09321d))
            binding.tvMinute.setTextColor(getColor(R.color.color_09321d))
            binding.tvSecond.setTextColor(getColor(R.color.color_09321d))

            binding.tvPrice.setTextColor(getColor(R.color.color_f6fbd0))
            binding.tvInvoice.setTextColor(getColor(R.color.color_7ead99))
            binding.tvPay.setTextColor(getColor(R.color.color_753906))

            binding.layoutSeat.visible()
        }
    }

    private fun sendBDReport(isSuccess: Boolean) {
        ConvertReportHelper.onEventPurchase(
            "member",
            goodsEntity!!.goods_name,
            goodsEntity!!.goods_id,
            1,
            if (payType == 0) "weixin" else "alipay",
            "¥",
            isSuccess,
            totalPrice.toInt()
        )
    }

    private fun startCountdown(time: Long) {
        countdownDisposable = RxCountDown.countdown(time)
            .subscribe {
                setCountdownTime(it)
            }
    }

    //格式化倒计时
    @SuppressLint("DefaultLocale")
    private fun setCountdownTime(seconds: Long) {
        val minutes = seconds / 60
        val hours = minutes / 60
        val day = hours / 24
        binding.tvDay.text = String.format("%02d", day)
        binding.tvHour.text = if (day > 0) String.format("%02d", hours % 24) else String.format("%02d", hours)
        binding.tvMinute.text = String.format("%02d", minutes % 60)
        binding.tvSecond.text = String.format("%02d", seconds % 60)
    }

    private fun startScroll() {
        if (userTipsList.isEmpty() || scrollTask != null) return
        scrollTask = Observable.interval(300, 9, TimeUnit.MILLISECONDS)
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe {
                if (activity != null) {
                    binding.rvUserTips.scrollBy(3, 0)
                }
            }
    }

    private fun stopScroll() {
        scrollTask?.dispose()
        scrollTask = null
    }

    override fun onStart() {
        startScroll()
        showQueryTipDialog()
        super.onStart()
    }

    override fun onStop() {
        stopScroll()
        super.onStop()
    }

    override fun onDestroyView() {
        countdownDisposable?.dispose()
        super.onDestroyView()
    }
}