package com.adealink.weparty.share.qrcode.page.special

import com.adealink.frame.mvvm.view.viewBinding
import com.adealink.frame.util.onClick
import com.adealink.weparty.commonui.BaseFragment
import com.adealink.weparty.commonui.widget.NumberIncreaseView
import com.adealink.weparty.module.playmate.data.UserPlaymateCategoryData
import com.adealink.weparty.share.R
import com.adealink.weparty.share.databinding.FragmentSpecialQrCodeStep1Binding
import com.adealink.weparty.share.qrcode.QRCodeShareDialog
import com.adealink.weparty.share.qrcode.page.special.viewmodel.SpecialQRCodePage
import com.adealink.weparty.share.qrcode.page.special.viewmodel.SpecialQRCodeViewModel
import com.adealink.weparty.share.qrcode.viewmodel.QRCodeViewModel
import com.adealink.weparty.viewmodel.parentFragmentViewModels

class SpecialQRCodeStep1Fragment : BaseFragment(R.layout.fragment_special_qr_code_step_1) {


    private val binding by viewBinding(FragmentSpecialQrCodeStep1Binding::bind)

    private val specialQRCodeViewModel by parentFragmentViewModels<SpecialQRCodeViewModel, SpecialQRCodeFragment>(
        SpecialQRCodeFragment::class.java
    )
    private val qrCodeViewModel by parentFragmentViewModels<QRCodeViewModel, QRCodeShareDialog>(
        QRCodeShareDialog::class.java
    )

    private var data: UserPlaymateCategoryData? = null
    private var number: Int = 1

    override fun initViews() {
        super.initViews()
        binding.vNumber.setNumber(number)
        binding.vNumber.setListener(object : NumberIncreaseView.OnNumberChangedListener {
            override fun onNumberChanged(number: Int) {
                this@SpecialQRCodeStep1Fragment.number = number
                updatePanel()
            }
        })
        binding.btnGenerateQrcode.onClick {
            generateQRCode()
        }
    }

    override fun observeViewModel() {
        super.observeViewModel()
        qrCodeViewModel.currentCategoryLD.observe(this) { data ->
            if (this.data?.id == data?.id) {
                return@observe
            }
            this.data = data
            binding.vNumber.setNumber(1)
            updatePanel()
        }
    }

    private fun updatePanel() {
        binding.tvPrice.text = data?.price?.toString()
        binding.tvUnit.text = data?.unit
        binding.vPrice.setPrice(
            number * (data?.price ?: 0f),
            null
        )
    }

    private fun generateQRCode() {
        data ?: return
        specialQRCodeViewModel.setOrderNumber(binding.vNumber.getNumber())
        specialQRCodeViewModel.showPage(SpecialQRCodePage.STEP_2)
    }


}