package com.yzx.escreen.fragment.base


import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog
import com.yzx.escreen.presenter.base.BasePresenter
import com.yzx.escreen.utils.hideNavigationBar

/**
 * fragment 基类
 */
abstract class BaseFragment<out P : BasePresenter<*>> : Fragment() {

    /**
     * 当前页面需要加载的layoutId，等价setContentView
     */
    abstract val inflateId: Int

    private var mLoadingDialog: QMUITipDialog? = null

    /**
     * 初始化视图操作在这里执行，执行时机为onCreate之后
     */
    abstract fun initView(): Unit

    /**
     * 数据初始化在这里执行，执行时机为initView之后
     */
    abstract fun initData(): Unit

    //kotlin 懒加载，在第一次使用Presenter时初始化，这种设计是针对一个View只针对一个Presenter。
    //多个Presenter的情况此处不应该使用泛型
    protected val mPresenter: P? by lazy { initPresenter() }

    abstract fun initPresenter(): P?


    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(inflateId, null)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        initView()
        initData()
    }

    override fun onStart() {
        super.onStart()

    }

    override fun onStop() {
        super.onStop()

    }


    override fun onDestroy() {
        super.onDestroy()
    }

    fun showDialogToast(
        msg: String,
        duration: Long = 1500,
        @QMUITipDialog.Builder.IconType icon: Int = QMUITipDialog.Builder.ICON_TYPE_SUCCESS
    ) {
        val tipDialog = QMUITipDialog.Builder(activity)
            .setIconType(icon)
            .setTipWord(msg)
            .create()
        tipDialog.show()
        tipDialog.hideNavigationBar()
        view?.postDelayed({
            tipDialog.dismiss()
        }, duration)
    }

    fun showLoading(msg: String = "加载中...") {
        mLoadingDialog = QMUITipDialog.Builder(activity)
            .setIconType(QMUITipDialog.Builder.ICON_TYPE_LOADING)
            .setTipWord(msg)
            .create()
        mLoadingDialog?.apply {
            show()
        }
    }

    fun hideLoading() {
        mLoadingDialog?.apply {
            if (isShowing) {
                dismiss()
            }
        }
    }
}