package com.ccwangluo.accelerator.utils

import android.content.Context
import android.content.Intent
import android.content.pm.ApplicationInfo
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
import android.net.Uri
import android.os.Build
import android.text.TextUtils
import android.util.DisplayMetrics
import com.ccwangluo.accelerator.utils.SysUtils.channelString
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.net.NetworkUtils
import com.xuexiang.xutil.system.DeviceUtils
import java.text.SimpleDateFormat
import java.util.*


object SysUtils {

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

    var channelString: String? = ""

    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 isMobileNet(): Boolean {
        return NetworkUtils.isMobile()
    }


    /*
    * 判断设备 是否使用代理上网
    * */
    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 getReportChannel(): Int {
        return when (channelString) {
            "v2_guanwang" -> 51
            "v2_huawei" -> 52
            "v2_xiaomi" -> 53
            "v2_vivo" -> 54
            "v2_yingyongbao" -> 55
            "v2_OPPO" -> 56
            "v2_baiduzhushou" -> 57
            "v2_wufan" -> 58
            "v2_share" -> 59
            "v2_update" -> 60
            else -> 51
        }
    }


    fun initChannel(context: Context) {
            channelString = PackerNg.getChannel(context)
            SettingSPUtils.channel = when (channelString) {
                "v2_guanwang" -> 1
                "v2_huawei" -> 2
                "v2_xiaomi" -> 3
                "v2_vivo" -> 4
                "v2_yingyongbao" -> 5
                "v2_OPPO" -> 6
                "v2_baiduzhushou" -> 7
                "v2_wufan" -> 8
                "v2_share" -> 9
                "v2_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)
    }


    fun compareVersionTo(localVersion: String?, remoteVersion: String?): Boolean {
        try {
            if (TextUtils.isEmpty(localVersion) || TextUtils.isEmpty(remoteVersion)) {
                return true
            }
            val local = localVersion!!.split(".")
            val remote = remoteVersion!!.split(".")
            if (remote.size == 0 || local.size == 0) {
                return true
            }


            for (i in 0..local.size) {
                if (remote.size > i && local[i].toInt() < remote[i].toInt()) {
                    return false
                }
            }

        } catch (e: java.lang.Exception) {
            e.printStackTrace()
            println("localVersion = $localVersion   remoteVersion=${remoteVersion}")
        }
        return true
    }

    /**
     * 获取手机已安装应用列表
     * @param ctx
     * @return
     */
    fun getAllAppInfo(ctx: Context): List<String> {
        val gameList = mutableListOf<String>()
        val packageManager = ctx.packageManager
        val list = packageManager.getInstalledPackages(0)
        for (p in list) {
            val flags = p.applicationInfo.flags
            // 判断是否是属于系统的apk
            if (flags != ApplicationInfo.FLAG_SYSTEM) {
                val packageName = p.applicationInfo.packageName
                if (packageName.contains("samsung")) {
                    continue
                }
                gameList.add(p.applicationInfo.packageName)
            }
        }
        return gameList
    }

}