package cn.muchinfo.rma.view.base

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProvider
import cn.muchinfo.rma.R
import com.afollestad.materialdialogs.MaterialDialog
import com.afollestad.materialdialogs.customview.customView
import com.afollestad.materialdialogs.lifecycle.lifecycleOwner
import com.aleyn.mvvm.event.Message
import com.blankj.utilcode.util.ToastUtils
import java.lang.reflect.ParameterizedType
/**
 *   @auther : lbl
 *   time   : 2021/1/01
 */
abstract class BaseActivity<VM : BaseViewModel> : AppCompatActivity() {

    protected lateinit var viewModel: VM
    private var dialog: MaterialDialog? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initViewDataBinding()
        lifecycle.addObserver(viewModel)
        //注册 UI事件
        registorDefUIChange()
    }

    /**
     * DataBinding
     */
    private fun initViewDataBinding() {

        createViewModel()
    }


    /**
     * 注册 UI 事件
     */
    private fun registorDefUIChange() {
//        viewModel.defUI.showDialog.observe(this, {
//            showLoading()
//        })
//        viewModel.defUI.dismissDialog.observe(this, {
//            dismissLoading()
//        })
//        viewModel.defUI.toastEvent.observe(this, {
//            ToastUtils.showShort(it)
//        })
//        viewModel.defUI.msgEvent.observe(this, {
//            handleEvent(it)
//        })
    }

    open fun handleEvent(msg: Message) {}

    /**
     * 打开等待框
     */
    private fun showLoading() {
//        (dialog ?: MaterialDialog(this)
//                .cancelable(false)
//                .cornerRadius(8f)
//                .customView(R.layout.custom_progress_dialog_view, noVerticalPadding = true)
//                .lifecycleOwner(this)
//                .maxWidth(R.dimen.dialog_width))
//                .show()
    }

    /**
     * 关闭等待框
     */
    private fun dismissLoading() {
        dialog?.run { if (isShowing) dismiss() }
    }


    /**
     * 创建 ViewModel
     */
    @Suppress("UNCHECKED_CAST")
    private fun createViewModel() {
        val type = javaClass.genericSuperclass
        if (type is ParameterizedType) {
            val tp = type.actualTypeArguments[0]
            val tClass = tp as? Class<VM> ?: BaseViewModel::class.java
            viewModel = ViewModelProvider(viewModelStore, defaultViewModelProviderFactory)
                    .get(tClass) as VM
        }
    }

    override fun getDefaultViewModelProviderFactory(): ViewModelProvider.Factory {
        return MVVM.getConfig().viewModelFactory() ?: super.getDefaultViewModelProviderFactory()
    }

}