package com.example.base.dialog

import android.content.Context
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.text.TextUtils
import android.view.Gravity
import android.view.View
import android.view.Window
import android.view.WindowManager
import android.view.animation.Animation
import android.view.animation.Animation.REVERSE
import android.view.animation.LinearInterpolator
import android.view.animation.RotateAnimation
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatDialog
import com.example.base.R


/**
 * @date 2021-08-12 13:50
 * @desc 自定义进度对话框
 */
class LoadingDialog(context: Context?) : AppCompatDialog(context!!) {

    init {

        // 禁止取消
        setCancelable(false)

        // 去掉对话框顶部栏
        requestWindowFeature(Window.FEATURE_NO_TITLE)

        setContentView(R.layout.mvvm_dialog_loading)

        //设置dialog靠近顶部
        window?.setGravity(Gravity.TOP)

        window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))

        //设置margin为屏幕的40%
        val lps: WindowManager.LayoutParams? = window?.attributes
        lps?.verticalMargin = 0.4f
        window?.attributes = lps

        startAnim()
    }

    private fun startAnim() {
        val imageView = findViewById<ImageView>(R.id.ivLoading)
        val anim = RotateAnimation(0f, 360f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f)
        anim.repeatCount = Animation.INFINITE
        anim.duration = 1000
        anim.interpolator = LinearInterpolator()
        imageView?.startAnimation(anim)
    }

    fun setMessage(msg: String) {
        val textView = findViewById<TextView>(R.id.tvMessage)
        if (!TextUtils.isEmpty(msg)) {
            textView?.visibility = View.VISIBLE
            textView?.text = msg
        } else {
            textView?.visibility = View.GONE
        }
    }
}