package com.abbidot.tracker.base

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.result.ActivityResultLauncher
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.viewbinding.ViewBinding
import com.abbidot.baselibrary.util.LogUtil
import com.abbidot.tracker.R
import com.abbidot.tracker.constant.GetResultCallback
import com.abbidot.tracker.util.Util
import com.qmuiteam.qmui.alpha.QMUIAlphaButton
import com.qmuiteam.qmui.alpha.QMUIAlphaImageButton
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog

/**
 *Created  by .yzq on 2021/11/2/002.
 * @link
 * @description:Fragment基类
 * 关于@JvmOverloads constructor说明 https://stackoverflow.com/questions/34469487/caused-by-java-lang-nosuchmethodexception-init-class-android-content-contex
 */
abstract class BaseFragment<T : ViewBinding>(
    val inflater: (inflater: LayoutInflater, container: ViewGroup?, attachToRoot: Boolean) -> T
) : Fragment(), View.OnClickListener {

    protected lateinit var mViewBinding: T
    var mActivity: Activity? = null
    var mContext: Context? = null
    var mLoadingDialog: QMUITipDialog? = null

    //防止某个时间执行多次
    private var mLimitExecutionTime = 0L

    /**
     * Fragment中嵌套子Fragment时，如果父Fragment被销毁而子Fragment未被销毁，会导致子Fragment的视图不再显示‌
     */
    override fun onCreate(savedInstanceState: Bundle?) {
        savedInstanceState?.remove("android:support:fragments")
        super.onCreate(savedInstanceState)
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View? {
        mViewBinding = this.inflater(inflater, container, false)
        LogUtil.e("${javaClass.simpleName},onCreateView")
        return mViewBinding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        mActivity = activity
        mContext = context
        //统一设置的渐变背景色
        mViewBinding.root.background =
            ContextCompat.getDrawable(mContext!!, R.drawable.v2_bg_color_gradient)
        LogUtil.e("${javaClass.simpleName},onViewCreated")
        initData()
        liveDataObserve()
    }

    /**
     * 注册监听livedata观察者
     */
    open fun liveDataObserve() {}

    /**
     * 初始化
     */
    open fun initData() {}

    fun showLoading(show: Boolean, tip: String = "", cancelable: Boolean = true) {
        (activity as BaseActivity<*>).showLoading(show, tip, cancelable)
    }

    fun showLoading(show: Boolean) {
        (activity as BaseActivity<*>).showLoading(show)
    }

    fun showNoCancelableLoading(show: Boolean) {
        (activity as BaseActivity<*>).showNoCancelableLoading(show)
    }

    /**
     * 显示提示toast
     */
    fun showToast(
        tip: String, isFinish: Boolean = false, gravity: Int = Gravity.BOTTOM
    ) {
//        DialogUtils.showTipDialog(mContext!!, mViewBinding.root, tip, iconType, isFinish = isFinish)
        (activity as BaseActivity<*>).showToast(tip, isFinish, gravity)
    }

    fun showToast(
        resIdString: Int, isFinish: Boolean = false, gravity: Int = Gravity.BOTTOM
    ) {
//        showToast(getString(resIdString), isFinish, iconType)
        (activity as BaseActivity<*>).showToast(resIdString, isFinish, gravity)
    }

    /**
     * 设置多个view的监听事件
     */
    fun setOnClickListenerViews(vararg views: View?) {
        for (v in views) {
            v?.let {
                if (v is QMUIAlphaButton) {
                    //设置按下点击透明效果
                    v.setChangeAlphaWhenPress(true)
                } else if (v is QMUIAlphaImageButton) {
                    //设置按下点击透明效果
                    v.setChangeAlphaWhenPress(true)
                }
                v.setOnClickListener(this)
            }
        }
    }

    override fun onClick(v: View?) {
        // 默认不实现，让子类实现
    }

    fun finish(activity: Activity) {
        (activity as BaseActivity<*>).finish()
    }

    fun startActivity(activity: Activity, intent: Intent) {
        (activity as BaseActivity<*>).startActivity(intent)
    }

    fun startActivityFinish(activity: Activity, intent: Intent) {
        (activity as BaseActivity<*>).startActivityFinish(intent)
    }

    fun startActivity(activity: Activity, intent: Intent, options: Bundle?) {
        (activity as BaseActivity<*>).startActivity(intent, options)
    }

    /**
     * onActivityResult 替换跳转方法
     */
    fun launchActivity(
        activity: Activity, activityResultLauncher: ActivityResultLauncher<Intent>, intent: Intent
    ) {
        (activity as BaseActivity<*>).launchActivity(activityResultLauncher, intent)
    }

    /**
     * 限制多次点击按钮
     */
    fun isLimitClick(): Boolean {
        //防止执行多次弹窗
        if (Util.isTimeLimit(mLimitExecutionTime)) {
            return true
        }
        mLimitExecutionTime = System.currentTimeMillis()
        return false
    }

    /**
     * 统一处理网络请求结果
     */
    fun <T> dealRequestResult(
        it: Result<T>,
        getResultCallback: GetResultCallback,
        showLoading: Boolean = false,
        isShowNoDataTip: Boolean = true,
        isRequestErrorTip: Boolean = true,
        isShowCodeError: Boolean = true,
        errorTip: String = getString(R.string.txt_net_error)
    ) {
        (activity as BaseActivity<*>).dealRequestResult(
            it,
            getResultCallback,
            showLoading,
            isShowNoDataTip,
            isRequestErrorTip,
            isShowCodeError,
            errorTip
        )
    }
}