package com.grkj.iscs.view.dialog

import android.content.Context
import android.view.View
import com.grkj.iscs.R
import com.grkj.iscs.view.base.BaseDialog
import com.grkj.iscs.databinding.DialogTipBinding
import com.grkj.iscs.util.Executor
import java.util.Timer
import java.util.TimerTask

/**
 * 通用提示弹框
 */
class TipDialog(ctx: Context) : BaseDialog<DialogTipBinding>(ctx) {

    private var confirmListener: (() -> Unit)? = null
    private var cancelListener: (() -> Unit)? = null
    private var mTimer: Timer? = null

    companion object {
        const val TYPE_CONFIRM = 0
        const val TYPE_ALL = 1
    }

    override val viewBinding: DialogTipBinding
        get() = DialogTipBinding.inflate(layoutInflater)

    override fun initView() {
        mBinding?.btnConfirm?.setOnClickListener {
            dismiss()
            confirmListener?.invoke()
        }

        mBinding?.btnCancel?.setOnClickListener {
            dismiss()
            cancelListener?.invoke()
        }
    }

    fun setTip(tip: String) {
        mBinding?.tvTip?.text = tip
    }

    fun setType(type: Int) {
        when (type) {
            TYPE_CONFIRM -> {
                mBinding?.btnCancel?.visibility = View.GONE
            }
            TYPE_ALL -> {
                mBinding?.btnCancel?.visibility = View.VISIBLE
            }
        }
    }

    /**
     * 自动倒计时取消模式显示
     */
    fun showCancelCountdown(seconds: Int) {
        mBinding?.btnCancel?.visibility = View.VISIBLE
        mBinding?.btnCancel?.text = context.getString(R.string.cancel_countdown, seconds)

        show()

        var countSeconds = seconds
        mTimer = Timer().apply {
            schedule(object : TimerTask() {
                override fun run() {
                    Executor.runOnMain {
                        mBinding?.btnCancel?.text = context.getString(R.string.cancel_countdown, countSeconds)
                        if (countSeconds == 0) {
                            dismiss()
                            cancelListener?.invoke()
                        }
                        countSeconds--
                    }
                }
            }, 0, 1000)
        }
    }

    fun setConfirmListener(listener: () -> Unit) {
        confirmListener = listener
    }

    fun setCancelListener(listener: () -> Unit) {
        cancelListener = listener
    }

    override fun dismiss() {
        super.dismiss()
        mTimer?.cancel()
    }
}