package com.dlc.chemical.ui.dialog

import android.app.Dialog
import android.content.Context
import android.graphics.Color
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.view.LayoutInflater
import com.dlc.chemical.R
import com.dlc.chemical.databinding.DialogSuccessBinding
import com.rc.core.util.DeviceUtils

/**
 * info
 *
 * @author ReiChin_
 */
class SuccessDialog(
    context: Context,
    private val message: String,
    private val messageTextColor: String = "#FF018D13",
    private val imageRes: Int = R.mipmap.icon_rzcg,
    private val showTimes: Long = 3000
) :
    Dialog(context, R.style.AlertDialogStyle) {

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

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

        setContentView(viewBinding.root)

        viewBinding.text.text = message
        viewBinding.text.setTextColor(Color.parseColor(messageTextColor))
        viewBinding.image.setImageResource(imageRes)

        window?.apply {
            attributes.width = DeviceUtils.dip2px(context, 338.0f)
            attributes.height = DeviceUtils.dip2px(context, 68.0f)
        }
    }

    override fun onStart() {
        super.onStart()

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

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

    private val mDismissHandler = object : Handler(Looper.getMainLooper()) {

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

}