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

import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.animation.ValueAnimator
import android.annotation.SuppressLint
import android.os.Build
import android.text.TextUtils
import android.view.View
import android.view.ViewTreeObserver.OnGlobalLayoutListener
import android.widget.TextView
import android.window.OnBackInvokedDispatcher
import androidx.activity.addCallback
import androidx.core.animation.addListener
import androidx.core.content.ContextCompat
import androidx.core.os.BuildCompat
import androidx.core.view.isVisible
import androidx.recyclerview.widget.RecyclerView
import com.bytedance.ads.convert.event.ConvertReportHelper
import com.cheng.blzb.R
import com.cheng.blzb.bean.GuideTotalBidEntity
import com.cheng.blzb.bean.GuideUpdateEntity
import com.cheng.blzb.bean.HotWordEntity
import com.cheng.blzb.bean.OrderPayEntity
import com.cheng.blzb.bean.VipGoodsEntity
import com.cheng.blzb.common.Constants
import com.cheng.blzb.common.EventConstants
import com.cheng.blzb.databinding.FragmentGuideVipBinding
import com.cheng.blzb.event.OrderEvent
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.MainActivity
import com.cheng.blzb.ui.activity.PublicActivity
import com.cheng.blzb.ui.dialog.GuideSaleDialog
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.cheng.blzb.widget.BarChartView
import com.example.base.common.RxBus
import com.example.base.common.RxCountDown
import com.example.base.decoration.SpacesItemDecoration
import com.example.base.extensions.getColor
import com.example.base.extensions.getDD
import com.example.base.extensions.gone
import com.example.base.extensions.onClick
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.ScreenUtils
import com.example.base.utils.SpanUtils
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
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.onTouch
import org.jetbrains.anko.startActivity
import java.text.DecimalFormat
import java.util.Calendar
import java.util.concurrent.TimeUnit

class GuideVipFragment: BaseFragment<FragmentGuideVipBinding, GuideVipViewModel>() {
    private val userTipsAdapter by lazy { GuideVipUserAdapter(requireContext(), userTipsList) }
    private val industryAdapter by lazy { GuideVipIndustryAdapter(requireContext(), hotWordChildList) }

    private val userTipsList = mutableListOf<String>()
    private val hotWordChildList = mutableListOf<HotWordEntity.Child>()
    private var totalInfo: GuideTotalBidEntity? = null

    private val updateInfoList = mutableListOf<GuideUpdateEntity>()

    private var payType = 0 // 0 微信 1 支付宝 2 对公转账

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

    private val goodsAdapter by lazy { GuideVipAdapter() }

    private var goodsEntity: VipGoodsEntity? = null
    private var orderEntity: OrderPayEntity? = null

    private var totalSeconds = 0L
    private var countdownDisposable: Disposable? = null
    private var scrollTask: Disposable? = null

    override fun initView() {
        super.initView()
        setStatusBarLight(false)

        binding.tvTotalInfoCount1.typeface = Constants.dDIN_PRO_M
        binding.tvTotalInfoCount2.typeface = Constants.dDIN_PRO_M
        binding.tvTotalInfoCount3.typeface = Constants.dDIN_PRO_M
        binding.tvTotalInfoCount4.typeface = Constants.dDIN_PRO_M
        binding.tvPrice.typeface = Constants.dDIN_PRO_M
        binding.tvPay.typeface = Constants.almmsht

        binding.rvUser.adapter = userTipsAdapter

        binding.viewFlipper.adapter = industryAdapter

        binding.rvGoods.adapter = goodsAdapter
        binding.rvGoods.addItemDecoration(SpacesItemDecoration(DensityUtils.dp2px(10f), RecyclerView.HORIZONTAL))

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

        binding.tvChartTitle.text = "月份:${Calendar.getInstance().get(Calendar.MONTH) + 1}月    单位:条"

        binding.layoutContent.viewTreeObserver.addOnGlobalLayoutListener(object : OnGlobalLayoutListener {
            override fun onGlobalLayout() {
                mViewModel.getGoodsList()
                binding.layoutContent.viewTreeObserver.removeOnGlobalLayoutListener(this)
            }
        })
    }

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

        mViewModel.getPayUserTips()
        mViewModel.getUpdateNum()

        setData()
    }

    @SuppressLint("NotifyDataSetChanged")
    override fun initListener() {
        super.initListener()
        setBackPressed()

        binding.rvUser.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
            setPrice(goodsEntity!!.price.toFloat())
            releasePayType()
        }

        binding.ivClose.onClick {
            requireActivity().startActivity<MainActivity>()
        }

        binding.tvTab1.onClick {
            binding.layoutTotalInfo.visible()
            binding.layoutChart.gone()
            updateTabStyle(binding.tvTab1)
            setTotalData()
        }

        binding.tvTab2.onClick {
            binding.layoutTotalInfo.gone()
            binding.layoutChart.visible()
            updateTabStyle(binding.tvTab2)
            setDailyChartData()
        }

        binding.tvTab3.onClick {
            binding.layoutTotalInfo.gone()
            binding.layoutChart.visible()
            updateTabStyle(binding.tvTab3)
            setBidTypeChartData()
        }

        binding.tvTab4.onClick {
            binding.layoutTotalInfo.gone()
            binding.layoutChart.visible()
            updateTabStyle(binding.tvTab4)
            setCityChartData()
        }

        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")
                        } else {
                            mViewModel.payCreateOrder(goodsEntity!!.goods_id, "weixin")
                        }
                    } else if (payType == 1) {
                        mViewModel.payCreateOrder(goodsEntity!!.goods_id, "alipay")
                    } else if (payType == 2) {
                        mViewModel.payCreateOrder(goodsEntity!!.goods_id, "bank")
                    }
                }
                f.show(childFragmentManager, PayTipDialog::class.java.simpleName)
            } else {
                if (payType == 0) {
                    if (!TextUtils.isEmpty(goodsEntity!!.weixinMpOriId)) {
                        mViewModel.payCreateOrder(goodsEntity!!.goods_id, "combo")
                    } else {
                        mViewModel.payCreateOrder(goodsEntity!!.goods_id, "weixin")
                    }
                } else if (payType == 1) {
                    mViewModel.payCreateOrder(goodsEntity!!.goods_id, "alipay")
                } else if (payType == 2) {
                    mViewModel.payCreateOrder(goodsEntity!!.goods_id, "bank")
                }
            }
            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.goodsListLiveData.observe(this) { list ->
            goodsAdapter.setList(list)

            goodsEntity = list.find { it.checked }
            if (goodsEntity == null && list.isNotEmpty()) {
                goodsEntity = list[0]
            }
            if (goodsEntity != null) {
                setPrice(goodsEntity!!.price.toFloat())
                releasePayType()
            }
            initPrivacyTv()
            startAnim()
        }

        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("from", 1), 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",
                    "{isGuide: true, orderId:${orderEntity?.orderId}, meal:${Gson().toJson(goodsEntity)}}"
                )
                requireActivity().startActivity<MainActivity>()
            }
        }

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

        mViewModel.updateLiveData.observe(this) {
            updateInfoList.clear()
            updateInfoList.addAll(it)
        }

        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", "{isGuide: true, orderId:${orderEntity?.orderId}")
                }

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

        val orderEvent = RxBus.defaultInstance.toObservable(OrderEvent::class.java).subscribe {
            requireActivity().finish()
        }
        addDisposable(orderEvent)
    }

    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 setData() {
        totalInfo = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            arguments?.getSerializable("total", GuideTotalBidEntity::class.java)
        } else {
            arguments?.getSerializable("total") as? GuideTotalBidEntity
        }

        val hotWordListStr = arguments?.getString("hotWords")
        if (!TextUtils.isEmpty(hotWordListStr)) {
            hotWordChildList.addAll(Gson().fromJson<List<HotWordEntity.Child>>(hotWordListStr, object : TypeToken<List<HotWordEntity.Child>>() {}.type))
            industryAdapter.notifyDataSetChanged()
        }

        val countDownTime = UserConfigManager.getGuideCountdownTime()
        if (!TextUtils.isEmpty(countDownTime)) {
            totalSeconds = countDownTime!!.split(",")[0].toLong()
            startCountdown()
        }
    }

    private fun setTotalData() {
        totalInfo?.let {
            val valueAnim = ValueAnimator.ofFloat(0f, 1f)
            valueAnim.duration = 1000
            valueAnim.addUpdateListener { animator ->
                val percent = animator.animatedValue as Float
                SpanUtils.with(binding.tvTotalInfoCount1)
                    .append("${(it.bidCount * percent).toInt()}")
                    .append("条")
                    .setFontSize(10, true)
                    .create()
                SpanUtils.with(binding.tvTotalInfoCount2)
                    .append("${(it.hasContact * percent).toInt()}")
                    .append("条")
                    .setFontSize(10, true)
                    .create()
                SpanUtils.with(binding.tvTotalInfoCount3)
                    .append("${(it.maxMoney * percent).toInt()}")
                    .append("亿元")
                    .setFontSize(10, true)
                    .create()
                SpanUtils.with(binding.tvTotalInfoCount4)
                    .append("${(it.yesterdayCount * percent).toInt()}")
                    .append("条")
                    .setFontSize(10, true)
                    .create()
            }
            valueAnim.start()
        }
    }

    private fun setDailyChartData() {
        val dateList = getDateList(updateInfoList, System.currentTimeMillis())
        val dataList = mutableListOf<BarChartView.BarDataSet>()
        updateInfoList.forEachIndexed { index, item ->
            dataList.add(BarChartView.BarDataSet(dateList[index], listOf(item.count.toFloat())))
        }
        binding.barChart.setData(dataList)
        binding.tvLegend1.gone()
        binding.tvLegend2.gone()
    }

    private fun setBidTypeChartData() {
        totalInfo?.let {
            val percentArray = intArrayOf(4, 6, 34, 5, 28, 7, 45, 1)
            val bidTypeArray = arrayOf("竞争性磋商", "更正公告", "招标公告", "招标计划", "采购公告", "合同公告", "中标公告", "终止公告")
            val dataList = mutableListOf<BarChartView.BarDataSet>()
            bidTypeArray.forEachIndexed { index, item ->
                dataList.add(BarChartView.BarDataSet(item, listOf((it.bidCount * percentArray[index] / 100).toFloat())))
            }
            binding.barChart.setData(dataList)
            binding.tvLegend1.gone()
            binding.tvLegend2.gone()
        }
    }

    private fun setCityChartData() {
        val array1 = intArrayOf(
            134089, 93969, 69947, 186730, 103113, 60920, 32955, 156973, 43129, 232609, 84234, 72890, 44618, 48437, 43981,
            102764, 139170, 64218, 45001, 71689, 39366, 113385, 51259, 33253, 31930, 16348, 19388, 17568, 39384, 21928, 5853
        )
        val array2 = intArrayOf(
            14467, 9491, 7524, 6651, 6036, 5505, 4962, 4584, 4397, 3982, 3609, 3472, 3295, 3157, 3103,
            3078, 1907, 1803, 1690, 1555, 1421, 1128, 892, 758, 731, 708, 525, 525, 436, 328, 254
        )
        val dataList = mutableListOf<BarChartView.BarDataSet>()
        UserConfigManager.getCityList().forEachIndexed { index, item ->
            dataList.add(BarChartView.BarDataSet(item.name, listOf(array1[index].toFloat(), array2[index].toFloat())))
        }
        binding.barChart.setData(dataList)
        binding.tvLegend1.visible()
        binding.tvLegend2.visible()
    }

    private fun startAnim() {
        val closeAlphaAnim = ObjectAnimator.ofFloat(binding.ivClose, "alpha", 0f, 1f)
        closeAlphaAnim.duration = 1000
        closeAlphaAnim.startDelay = 1800
        closeAlphaAnim.addListener(onStart = {
            binding.ivClose.visible()
        })

        val userTransAnim = ObjectAnimator.ofFloat(binding.rvUser, "translationX", ScreenUtils.getScreenWidth().toFloat(), 0f)
        userTransAnim.duration = 2000
        userTransAnim.startDelay = 1800
        userTransAnim.addListener(onStart = {
            binding.rvUser.visible()
        }, onEnd = {
            startScroll()
        })

        val industryTransAnim = ObjectAnimator.ofFloat(binding.layoutIndustry, "translationY", ScreenUtils.getScreenHeight().toFloat(), 0f)
        industryTransAnim.duration = 1000
        industryTransAnim.addListener(onStart = {
            binding.layoutIndustry.visible()
        })

        val tabTransAnim = ObjectAnimator.ofFloat(binding.layoutTab, "translationY", ScreenUtils.getScreenHeight().toFloat(), 0f)
        tabTransAnim.duration = 1000
        tabTransAnim.addListener(onStart = {
            binding.layoutTab.visible()
        })

        val infoWidth = binding.layoutInfo.measuredWidth
        val lineWidth = binding.ivInfoLight1.measuredWidth
        val infoLine1TransAnim = ObjectAnimator.ofFloat(binding.ivInfoLight1, "translationX", 0f, -(infoWidth - lineWidth).toFloat()).setDuration(1000)
        val infoLine2TransAnim = ObjectAnimator.ofFloat(binding.ivInfoLight2, "translationX", 0f, (infoWidth - lineWidth).toFloat()).setDuration(1000)

        val infoRotateAnim = ObjectAnimator.ofFloat(binding.layoutInfo, "rotationX", 90f, -10f, 10f, 0f)
        infoRotateAnim.duration = 1000
        infoRotateAnim.startDelay = 800
        infoRotateAnim.addListener(onStart = {
            binding.layoutInfo.visible()
        }, onEnd = {
            setTotalData()
            infoLine1TransAnim.start()
            infoLine2TransAnim.start()
        })

        val timeTransAnim = ObjectAnimator.ofFloat(binding.layoutCountdown, "translationY", ScreenUtils.getScreenHeight().toFloat(), 0f)
        timeTransAnim.duration = 1000
        timeTransAnim.startDelay = 1000
        timeTransAnim.addListener(onStart = {
            binding.layoutCountdown.visible()
        })

        val goodsTransAnim = ObjectAnimator.ofFloat(binding.rvGoods, "translationY", ScreenUtils.getScreenHeight().toFloat(), 0f)
        goodsTransAnim.duration = 1000
        goodsTransAnim.startDelay = 1200
        goodsTransAnim.addListener(onStart = {
            binding.rvGoods.visible()
        })

        val payTypeTransAnim = ObjectAnimator.ofFloat(binding.layoutPay, "translationY", ScreenUtils.getScreenHeight().toFloat(), 0f)
        payTypeTransAnim.duration = 1000
        payTypeTransAnim.startDelay = 1400
        payTypeTransAnim.addListener(onStart = {
            binding.layoutPay.visible()
        })

        val payBtnTransAnim = ObjectAnimator.ofFloat(binding.layoutPayBtn, "translationY", ScreenUtils.getScreenHeight().toFloat(), 0f)
        payBtnTransAnim.duration = 1000
        payBtnTransAnim.startDelay = 1400
        payBtnTransAnim.addListener(onStart = {
            binding.layoutPayBtn.visible()
        })

        val animSet = AnimatorSet()
        animSet.playTogether(
            closeAlphaAnim,
            userTransAnim,
            industryTransAnim,
            tabTransAnim,
            infoRotateAnim,
            timeTransAnim,
            goodsTransAnim,
            payTypeTransAnim,
            payBtnTransAnim
        )
        animSet.start()
    }

    private fun updateTabStyle(textView: TextView) {
        binding.tvTab1.setTextColor(getColor(R.color.color_9bbbdf))
        binding.tvTab2.setTextColor(getColor(R.color.color_9bbbdf))
        binding.tvTab3.setTextColor(getColor(R.color.color_9bbbdf))
        binding.tvTab4.setTextColor(getColor(R.color.color_9bbbdf))

        binding.tvTab1.setBackgroundResource(R.mipmap.ic_guide_vip_tab_default)
        binding.tvTab2.setBackgroundResource(R.mipmap.ic_guide_vip_tab_default)
        binding.tvTab3.setBackgroundResource(R.mipmap.ic_guide_vip_tab_default)
        binding.tvTab4.setBackgroundResource(R.mipmap.ic_guide_vip_tab_default)

        textView.setTextColor(getColor(R.color.white))
        textView.setBackgroundResource(R.mipmap.ic_guide_vip_tab_checked)

        val infoRotateAnim = ObjectAnimator.ofFloat(binding.layoutInfo, "rotationX", 90f, -10f, 10f, 0f)
        infoRotateAnim.duration = 1000
        infoRotateAnim.start()
    }

    private fun checkPayType() {
        if (payType == 0) {
            val start1 = ContextCompat.getDrawable(requireContext(), R.mipmap.ic_wx_pay)
            val end1 = ContextCompat.getDrawable(requireContext(), R.mipmap.ic_guide_pay_checked)
            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_guide_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_guide_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(), R.mipmap.ic_guide_pay_checked)
            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_guide_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_guide_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(), R.mipmap.ic_guide_pay_checked)
            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_guide_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_guide_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()
            binding.viewLine1.visible()
        } else {
            binding.tvWxPay.gone()
            binding.viewLine1.gone()
        }
        if (list?.find { it == "alipay" } != null && globalPayType.find { it == "alipay" } != null) {
            binding.tvAliPay.visible()
            binding.viewLine2.visible()
        } else {
            binding.tvAliPay.gone()
            binding.viewLine2.gone()
        }
        if (list?.find { it == "bank" } != null && globalPayType.find { it == "bank" } != null) {
            binding.tvBankPay.visible()
            binding.viewLine3.visible()
        } else {
            binding.tvBankPay.gone()
            binding.viewLine3.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_a6e8f7), false) {
                UrlHelper.startUserAgreement(requireContext(), "会员服务协议规则")
            }
        if (!TextUtils.isEmpty(goodsEntity?.sign_value) && payType == 1) {
            spanUtils.append("和")
            spanUtils.append("《自动续费服务规则》")
            spanUtils.setClickSpan(getColor(R.color.color_a6e8f7), false) {
                UrlHelper.startRenewAgreement(requireContext())
            }
        }
        spanUtils.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(12, true)
                .append(DecimalFormat("0.##").format(animPrice))
                .append(formatPricePeriod(goodsEntity!!.value))
                .setFontSize(12, true)
                .create()
        }
        valueAnim.start()

        binding.tvSavedPrice.text = "已优惠${DecimalFormat("0.##").format(goodsEntity!!.origin_price.toFloat() - totalPrice)}"
    }

    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 getDateList(dataList: List<GuideUpdateEntity>, selectedWeekTime: Long): ArrayList<String> {
        val dateList = ArrayList<String>()
        for (i in dataList.indices) {
            dateList.add(DateUtils.getDayOfWeekTimeMillisByEndTime(selectedWeekTime, i + 1).getDD())
        }
        return dateList
    }

    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() {
        countdownDisposable = RxCountDown.countdown(totalSeconds)
            .subscribe {
                setCountdownTime(it)
                if (it == 0L && !isStateSaved) {
                    val f = GuideSaleDialog.newInstance()
                    f.setOnSelectListener { seconds ->
                        totalSeconds = seconds
                        startCountdown()
                    }
                    f.show(childFragmentManager, GuideSaleDialog::class.java.simpleName)
                }
            }
    }

    //格式化倒计时
    @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.rvUser.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()
    }

    @SuppressLint("UnsafeOptInUsageError")
    private fun setBackPressed() {
        if (BuildCompat.isAtLeastT()) {
            requireActivity().onBackInvokedDispatcher.registerOnBackInvokedCallback(OnBackInvokedDispatcher.PRIORITY_DEFAULT) {
                requireActivity().startActivity<MainActivity>()
            }
        } else {
            requireActivity().onBackPressedDispatcher.addCallback(this) {
                requireActivity().startActivity<MainActivity>()
            }
        }
    }
}