package com.lukouguoji.module_base.model

import android.app.Activity
import android.content.Context
import androidx.fragment.app.Fragment
import com.lukouguoji.module_base.interfaces.ILoading
import com.lukouguoji.module_base.ktx.getActivity
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.impl.LoadingPopupView
import dev.DevUtils
import dev.utils.app.HandlerUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch

/**
 * @author：孟凡华
 * @date：2022/1/16 13:15
 * @desc：通用加载弹窗
 */
class LoadingModel(private val context: Context? = null) : ILoading {

    private var dialog: LoadingPopupView? = null

    private var lastTime = 0L
    private val minInterval = 200L

    /**
     * 展示加载弹窗
     */
    override fun showLoading() {
        try {
            HandlerUtils.postRunnable {
                val cont = getContext()
                createLoadingDialog()
                if (cont is Activity) {
                    if (!cont.isFinishing) {
                        dialog?.show()
                    }
                } else if (cont is Fragment) {
                    if (cont.activity?.isFinishing == false) {
                        dialog?.show()
                    }
                }
                lastTime = System.currentTimeMillis()
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun dismissLoading() {
        try {
            if (lastTime + minInterval > System.currentTimeMillis()) {
                HandlerUtils.postRunnable({
                    dialog?.dismiss()
                }, minInterval)
            } else {
                HandlerUtils.postRunnable {
                    dialog?.dismiss()
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    fun dismissInNoTime() {
        GlobalScope.launch(Dispatchers.Main) {
            try {
                if (dialog?.context?.getActivity()?.isFinishing != true) {
                    dialog?.dismiss()
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    /**
     * 创建加载弹窗
     */
    private fun createLoadingDialog() {
        if (dialog == null) {
            dialog = XPopup
                .Builder(getContext())
                .dismissOnBackPressed(true)
                .dismissOnTouchOutside(true)
                .hasShadowBg(false)
                .asLoading("请稍候……")
        }
    }

    /**
     * 设置弹窗文本内容
     */
    fun setMessage(msg: String) {
        createLoadingDialog()
        dialog?.setTitle(msg)
    }

    private fun getContext(): Context {
        return context ?: DevUtils.getTopActivity()
    }
}