package xn.xxp.home.sign

import android.app.Dialog
import android.content.Context
import android.graphics.Color
import android.os.Bundle
import android.os.Message
import android.view.LayoutInflater
import android.view.View
import core.util.OnWeakListener
import core.util.WeakHandler
import xn.xxp.R
import xn.xxp.databinding.DialogSafetyCheckResultBinding

/**
 * info
 *
 * @author ReiChin_
 */
class SafetyCheckResultDialog(
    context: Context,
    private val resultEnum: ResultEnum?,
    private val message: CharSequence?,
    private val showTimes: Long = -1
) :
    Dialog(context, R.style.AlertDialogStyle),
    OnWeakListener {

    private val viewBinding: DialogSafetyCheckResultBinding by lazy {
        DialogSafetyCheckResultBinding.inflate(LayoutInflater.from(context))
    }

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

        setContentView(viewBinding.root)

        viewBinding.text.text = message
        val color = when (resultEnum) {
            ResultEnum.START,
            ResultEnum.LOADING,
            ResultEnum.SUCCESS -> Color.parseColor("#0183FA")

            ResultEnum.FAIL -> Color.parseColor("#FF4552")
            ResultEnum.WARNING -> Color.parseColor("#FF9600")
            else -> Color.parseColor("#0183FA")
        }
        viewBinding.text.setTextColor(color)

        if (ResultEnum.LOADING == resultEnum) {
            viewBinding.loading.visibility = View.VISIBLE
            viewBinding.image.visibility = View.GONE
        } else {
            viewBinding.loading.visibility = View.GONE
            viewBinding.image.visibility = View.VISIBLE
            val imgResId = when (resultEnum) {
                ResultEnum.START -> R.mipmap.icon_qd_start
                ResultEnum.FAIL -> R.mipmap.icon_qd_fail
                ResultEnum.SUCCESS -> R.mipmap.icon_qd_success
                ResultEnum.WARNING -> R.mipmap.icon_qd_warning
                else -> R.mipmap.icon_qd_fail
            }
            viewBinding.image.setImageResource(imgResId)
        }
    }

    override fun onStart() {
        super.onStart()

        if (showTimes > 0) {
            // 显示showTimes毫秒秒后，自动关闭
            mDismissHandler.sendEmptyMessageDelayed(1, showTimes)
        }
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        mDismissHandler.removeCallbacksAndMessages(null)
    }

    private val mDismissHandler by lazy { WeakHandler(this) }

    override fun onWeakHandleMessage(msg: Message) {
        if (isShowing) dismiss()
    }

}

enum class ResultEnum {
    START, FAIL, SUCCESS, WARNING, LOADING
}