package com.xty.base.fragment

import android.app.Activity
import android.content.Context
import android.net.ConnectivityManager
import android.net.Network
import android.net.NetworkCapabilities
import android.net.NetworkInfo
import android.os.Build
import androidx.annotation.RequiresApi
import com.hjq.toast.ToastUtils
import com.tamsiree.rxkit.RxActivityTool
import com.xty.base.R
import com.xty.base.vm.BaseVm
import com.xty.base.refresh.RefreshUtils
import com.xty.common.MMkvHelper
import com.xty.common.arouter.ARouterUrl
import com.xty.common.arouter.RouteManager
import com.xty.common.event.LoginOutEvent
import org.greenrobot.eventbus.EventBus

abstract class BaseVmFrag<T : BaseVm> : IBaseFrag() {
    lateinit var mViewModel: T
    val refresh by lazy { RefreshUtils() }
    override fun initView() {
        super.initView()
        mViewModel = setViewModel()
        mViewModel.loading = loadingView

        mViewModel.nowData.observe(this) {
            loadingView.dismiss()
//            ToastUtils.show(R.string.again_login)

            //RxActivityTool.finishAllActivity()
            MMkvHelper.clearUserInfo()
            EventBus.getDefault().post(LoginOutEvent())
          //  RouteManager.goAct(ARouterUrl.LOGIN_ACT)
        }
        observer()
    }

    abstract fun setViewModel(): T

    abstract fun observer()

    //判断网络连接是否可用返回true表示网络可用false为不可用
    fun checkNetworkAvailable(context: Context): Boolean {
        return try {
            //获取手机所有链接管理对象包括对Wifi 4G net等连接的管理
            var manager =
                context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
            if (manager == null) {
                false
            } else {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    checkHighVersionNetWork(manager)
                } else {
                    checkLowVersionNetWork(manager)
                }
            }
        } catch (e: Exception) {
            false
        }
    }

    @RequiresApi(Build.VERSION_CODES.M)
    private fun checkHighVersionNetWork(manager: ConnectivityManager): Boolean {
        return try {
            var info = manager.getNetworkCapabilities(manager.activeNetwork)
            if (null != info) {
                return info.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)
            }
            false
        } catch (e: Exception) {
            false
        }
    }

    private fun checkLowVersionNetWork(manager: ConnectivityManager): Boolean {
        return try {
            var info = manager.activeNetworkInfo
            if (null != info) {
                return info.isConnected
            }
            false
        } catch (e: Exception) {
            false
        }
    }
}