package com.ccwangluo.accelerator.utils

import android.Manifest
import android.app.DownloadManager
import android.content.Context
import android.content.Context.DOWNLOAD_SERVICE
import android.content.Intent
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.text.TextUtils
import android.util.DisplayMetrics
import androidx.core.content.FileProvider
import androidx.fragment.app.FragmentActivity
import com.ccwangluo.accelerator.ui.dialog.DownloadDialog
import com.ccwangluo.cc_quickly.utils.SettingSPUtils
import com.hjq.toast.ToastUtils
import com.mcxiaoke.packer.helper.PackerNg
import com.tencent.mmkv.MMKV
import com.xuexiang.xpage.base.XPageActivity
import com.xuexiang.xpage.base.XPageFragment
import com.xuexiang.xutil.app.AppUtils
import com.xuexiang.xutil.net.NetworkUtils
import com.xuexiang.xutil.system.DeviceUtils
import com.xuexiang.xutil.system.PermissionUtils
import java.io.File
import java.text.SimpleDateFormat
import java.util.*


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 {
        try {
            return context.getPackageManager().getPackageInfo(packageName, 0) != null
        } catch (e: Exception) {

        }
        return false
    }

    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 getChannel(): Int {
        return SettingSPUtils.channel
//        return 4
    }

    fun initChannel(context: Context) {
        if (SettingSPUtils.channel == 0) {
            val channel = PackerNg.getChannel(context)
            SettingSPUtils.channel = when (channel) {
                "guanwang" -> 1
                "huawei" -> 2
                "xiaomi" -> 3
                "vivo" -> 4
                "yingyongbao" -> 5
                "OPPO" -> 6
                "baiduzhushou" -> 7
                "wufan" -> 8
                "share" -> 9
                "update" -> 10
                else -> 1
            }
        }
    }


    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)
    }

}