package com.miya.fastcashier.ui

import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProvider
import com.miya.fastcashier.databinding.ActivityPayResultBinding
import com.miya.fastcashier.utils.CenterToasty
import com.miya.fastcashier.utils.MiYaPayPlantformPayWayEnum
import com.miya.fastcashier.utils.StringPriceFormat
import com.miya.fastcashier.utils.clickWithTrigger
import com.miya.fastcashier.viewmodel.PrintViewModel
import com.sdy.miya.moblie.component.pay.platform.bean.PayServiceResponse


class PayResultActivity : AppCompatActivity() {
    private lateinit var viewModel: PrintViewModel
    private lateinit var binding: ActivityPayResultBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = ActivityPayResultBinding.inflate(layoutInflater)
        setContentView(binding.root)
        viewModel = ViewModelProvider(this).get(PrintViewModel::class.java)

        val tvPayPrice = binding.tvPayPrice
        val tvOrderNo = binding.tvOrderNo
        val tvPayWay = binding.tvPayWay
        val tvTradeNo = binding.tvTradeNo
        val tvTradeTime = binding.tvTradeTime
        val tvStatus = binding.tvStatus
        val tvRePrint = binding.tvRePrint
        val tvGoHome = binding.tvGoHome

        val extra = intent.getSerializableExtra("payServiceResponse")
        extra?.let {
            val payServiceResponse = it as PayServiceResponse
            tvPayPrice.text = "￥".plus(StringPriceFormat.transStringPriceToDecimalString(
                payServiceResponse.tradPrice))
            tvOrderNo.text = payServiceResponse.shopTradeNo
            tvPayWay.text = MiYaPayPlantformPayWayEnum.MiyaPayType.find(
                payServiceResponse.chanelTag
            ).desc
            tvTradeNo.text = payServiceResponse.chanelSerialNumber
            tvTradeTime.text = payServiceResponse.miyaResponseTime

            viewModel.printOrder(payServiceResponse)
        }

        viewModel.printResultLiveData.observe(this,{ result ->
            result.getOrElse {
                it.message?.let { it1 -> {
                    tvStatus.text = it1
                    tvRePrint.visibility = View.VISIBLE
                } }
                return@observe
            }

            result.getOrNull().also {
                it?.let {
                    tvStatus.text = "小票打印成功!"
                }
            }
        })

        tvRePrint.clickWithTrigger {
            tvStatus.text = "小票打印中，请稍等…"
            viewModel.printOrder(extra as PayServiceResponse)
        }

        tvGoHome.clickWithTrigger {
            val intent = Intent()
            intent.setClass(this@PayResultActivity, MainActivity::class.java)
            startActivity(intent)
        }

    }
}