package com.miya.fastcashier.ui

import android.content.Intent
import android.os.Bundle
import android.view.KeyEvent
import android.widget.Toast
import androidx.lifecycle.ViewModelProvider
import com.fastcashier.lib_common.base.BaseActivity
import com.fastcashier.lib_common.config.IntentExtra
import com.fastcashier.lib_common.function.pay.OrderRecordManageKit
import com.fastcashier.lib_common.util.clickWithTrigger
import com.miya.fastcashier.databinding.ActivityPayBinding
import com.miya.fastcashier.utils.CenterToasty
import com.miya.fastcashier.utils.ScanGunKeyEventHelper
import com.miya.fastcashier.viewmodel.PayViewModel
import java.util.*

class PayActivity : BaseActivity() {
    private lateinit var viewModel: PayViewModel
    private lateinit var binding: ActivityPayBinding
    private var scanGunKeyEventHelper: ScanGunKeyEventHelper = ScanGunKeyEventHelper()

    private lateinit var price: String

    companion object {
        fun start(context: BaseActivity, price: String) {
            val intent = Intent()
            intent.setClass(context, PayActivity::class.java)
            intent.putExtra(IntentExtra.KEY_EXTRA_PRICE, price)
            context.startActivity(intent)
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityPayBinding.inflate(layoutInflater)
        setContentView(binding.root)
        viewModel = ViewModelProvider(this).get(PayViewModel::class.java)

        price = intent.getStringExtra(IntentExtra.KEY_EXTRA_PRICE).toString()
        val tvPayPrice = binding.tvPayPrice
        tvPayPrice.text = "¥${price.toDouble()}"

        viewModel.payResultLiveData.observe(this, { payResult ->
            dismissProgressDialog()
            payResult.onFailure {
                it.message?.let { it1 -> CenterToasty.error(this, it1, Toast.LENGTH_LONG).show() }
            }
            payResult.onSuccess {
                OrderRecordManageKit.setSerialNumber()
                PayResultActivity.start(this@PayActivity, it)
            }
        })
        binding.clTitle.llBack.clickWithTrigger { finish() }

        scanGunKeyEventHelper.setOnBarCodeCatchListener {
            showProgressDialog("正在支付..")
            viewModel.pay(price, it)
        }
    }

    override fun dispatchKeyEvent(event: KeyEvent?): Boolean {
        scanGunKeyEventHelper.analysisKeyEvent(event)
        return super.dispatchKeyEvent(event)
    }

}