package com.ccwangluo.accelerator.utils

import android.content.Context
import android.content.pm.PackageManager
import android.text.TextUtils
import android.util.DisplayMetrics
import com.xuexiang.xpage.base.XPageFragment
import com.xuexiang.xutil.net.NetworkUtils
import java.text.SimpleDateFormat
import java.util.*
import kotlin.collections.ArrayList
import android.app.DownloadManager
import android.content.Intent
import android.net.*
import android.os.Build
import com.hjq.toast.ToastUtils
import com.tencent.mmkv.MMKV
import com.xuexiang.xpage.base.XPageActivity
import com.xuexiang.xutil.app.AppUtils
import com.xuexiang.xutil.system.DeviceUtils
import java.lang.Exception


object SysUtils {

    fun getConnectivityStatus(): Boolean {
        return NetworkUtils.isHaveInternet()
    }

    fun getActiveNet(): String {
        when (NetworkUtils.getNetStateType()) {
            NetworkUtils.NetState.NET_WIFI -> return "WIFI"
            NetworkUtils.NetState.NET_5G -> return "5G"
            NetworkUtils.NetState.NET_4G -> return "4G"
            NetworkUtils.NetState.NET_3G -> return "3G"
            NetworkUtils.NetState.NET_2G -> return "2G"
            NetworkUtils.NetState.NET_UNKNOWN -> return "UNKNOWN"
            NetworkUtils.NetState.NET_NO -> return "__"
            else -> return "__"
        }
    }


    /*
    * 判断设备 是否使用代理上网
    * */
    fun isVpn(context: Context): Boolean {
        val connectivityManager =
            context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        val activeNetwork = connectivityManager?.getActiveNetwork()
        val caps = connectivityManager.getNetworkCapabilities(activeNetwork)
        caps?.hasTransport(NetworkCapabilities.TRANSPORT_VPN)?.let {
            return it
        }
        return false
    }

    /**
     * 判断包是否安装
     */
    fun isPackageInstall(context: Context, packageName: String): Boolean {
       return AppUtils.isInstallApp(packageName)
    }

    fun getnetQuality(delay: Int): String {
        when (delay) {
            in (1..30) -> return "极快"
            in (31..50) -> return "良好"
            in (51..100) -> return "一般"
            else -> return "差"
        }
    }

    fun getAccTimeString(time: Long): String {
        return "加速中 ${tranlateTime(time)} "
    }

    fun tranlateTime(long: Long): String {
        val formatter = SimpleDateFormat("HH:mm:ss");//这里想要只保留分秒可以写成"mm:ss"
        formatter.setTimeZone(TimeZone.getTimeZone("GMT+00:00"));
        val hms = formatter.format(long);
        return hms
    }

    /**
     * 获取dpi
     */
    fun getDpi(xPageFragment: XPageFragment): Float {
        val dm = DisplayMetrics()
        xPageFragment.activity?.windowManager?.getDefaultDisplay()?.getMetrics(dm)
        return (dm.density * 160)
    }

    /**
     * 获取dpi
     */
    fun getDpi(xPageActivity: XPageActivity): Float {
        val dm = DisplayMetrics()
        xPageActivity?.windowManager?.getDefaultDisplay()?.getMetrics(dm)
        return (dm.density * 160)
    }

    fun downloadFile(context: Context, url: String) {
        val request = DownloadManager.Request(Uri.parse(url))
        request.setDestinationInExternalPublicDir("", url.substring(url.lastIndexOf("/") + 1))
        val downloadManager = context.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
        downloadManager.enqueue(request)
    }

    fun joinQQGroup(context: Context) {

        val key = "5CmyFzMWyucgmmLTM7JLG_sSArmaFQxT"
        val intent = Intent()
        intent.data =
            Uri.parse("mqqopensdkapi://bizAgent/qm/qr?url=http%3A%2F%2Fqm.qq.com%2Fcgi-bin%2Fqm%2Fqr%3Ffrom%3Dapp%26p%3Dandroid%26jump_from%3Dwebapi%26k%3D$key")
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        // 此Flag可根据具体产品需要自定义，如设置，则在加群界面按返回，返回手Q主界面，不设置，按返回会返回到呼起产品界面    //intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        // 此Flag可根据具体产品需要自定义，如设置，则在加群界面按返回，返回手Q主界面，不设置，按返回会返回到呼起产品界面    //intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        try {
            context.startActivity(intent)
        } catch (e: Exception) {
            // 未安装手Q或安装的版本不支持
            ToastUtils.show("没有安装qq")
        }
    }


    fun getDeviceUUID(): String? {
        var uuid = loadDeviceUUID()
        if (TextUtils.isEmpty(uuid)) {
            uuid = buildDeviceUUID()
            saveDeviceUUID(uuid)
        }
        return uuid
    }

    private fun buildDeviceUUID(): String {
        var androidId: String = DeviceUtils.getAndroidID()
        if ("9774d56d682e549c" == androidId) {
            val random = Random()
            androidId = (Integer.toHexString(random.nextInt())
                    + Integer.toHexString(random.nextInt())
                    + Integer.toHexString(random.nextInt()))
        }
        return UUID(androidId.hashCode().toLong(), getBuildInfo().hashCode().toLong()).toString()
    }

    fun getBuildInfo(): String {
        val buildSB = StringBuffer()
        buildSB.append(Build.BRAND).append("/")
        buildSB.append(Build.PRODUCT).append("/")
        buildSB.append(Build.DEVICE).append("/")
        buildSB.append(Build.ID).append("/")
        buildSB.append(Build.VERSION.INCREMENTAL)
        return buildSB.toString()
    }


    private fun saveDeviceUUID(uuid: String) {
        //device_uuid
        MMKV.defaultMMKV().putString("device_uuid", uuid)
    }

    private fun loadDeviceUUID(): String? {
        return MMKV.defaultMMKV().decodeString("device_uuid", null)
    }
}