package com.ypsx.yppos.ui.popup

import android.app.Activity
import android.content.Context
import android.view.Gravity
import android.view.View
import com.ypsx.base.base.appContext
import com.ypsx.base.ext.util.screenWidth
import com.ypsx.yppos.R
import com.ypsx.yppos.databinding.PopupCashPaySuccessBinding
import com.ypsx.yppos.viewmodel.state.PaySuccessViewModel
import razerdp.basepopup.BasePopupWindow
import java.util.*


class CashPaySuccessPopWindow(context: Context) : BasePopupWindow(context) {
    lateinit var bind: PopupCashPaySuccessBinding
    var timer: Timer? = null
    var task: TimerTask? = null
    var recLen = 5
    lateinit var activity: Activity



    init {
        setContentView(R.layout.popup_cash_pay_success)
        width = appContext.screenWidth / 4 * 3
        popupGravity = Gravity.CENTER
        isOutSideTouchable = false
        setOutSideDismiss(false)

    }

    private fun stopTimer() {
        if (task != null && timer != null) {
            timer?.cancel()
            timer?.purge()
            timer = null
            task = null
        }
    }

    override fun onViewCreated(contentView: View) {
        bind = PopupCashPaySuccessBinding.bind(contentView)
        bind.vm = PaySuccessViewModel()
        bind.click = ProxyClick()
        activity = context


        timer = Timer()
        task = object : TimerTask() {
            override fun run() {
                recLen--
                if (recLen < 0) {
                    if (isShowing) {
                        activity.runOnUiThread {
                            dismiss()
                        }
                    }
                    stopTimer()
                }
            }
        }
        timer?.schedule(task, 1000, 1000);
    }

    fun setData(payAmount: String,changeAmount:String) {
        bind.vm?.payAmount?.set(payAmount)
        bind.vm?.changeAmount?.set(changeAmount)
    }

    override fun dismiss() {
        super.dismiss()
        stopTimer()
    }


    inner class ProxyClick {
        fun close() {
            dismiss()
        }

    }
}