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.miya.fastcashier.databinding.ActivityPayBinding
import com.miya.fastcashier.utils.CenterToasty
import com.miya.fastcashier.utils.DateUtils
import com.miya.fastcashier.utils.ScanGunKeyEventHelper
import com.miya.fastcashier.utils.clickWithTrigger
import com.miya.fastcashier.viewmodel.PayViewModel
import com.tencent.mmkv.MMKV
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

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

        price = intent.getStringExtra("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 {
                //自增流水
                val today = DateUtils.format8(Date())
                var no = kv.getInt(today, 0);
                kv.putInt(DateUtils.format8(Date()), ++no)


                val intent = Intent()
                intent.setClass(this@PayActivity, PayResultActivity::class.java)
                intent.putExtra("payServiceResponse", it)
                startActivity(intent)
            }
        })
        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)
    }

}