package com.duben.microtribe.common

import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.ApplicationInfo
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.net.ConnectivityManager
import android.net.NetworkInfo
import android.net.Proxy
import android.net.Uri
import android.net.wifi.WifiInfo
import android.net.wifi.WifiManager
import android.os.BatteryManager
import android.os.Build
import android.os.SystemClock
import android.provider.Settings
import android.telephony.TelephonyManager
import android.text.TextUtils
import com.duben.library.utils.json.JsonUtil
import com.duben.microtribe.MintsApplication
import com.duben.microtribe.R
import com.duben.microtribe.utils.SimUtils
import com.duben.microtribe.utils.StorageQueryUtil
import com.duben.microtribe.utils.SystemUtils
import java.io.*
import java.lang.reflect.Method
import java.net.NetworkInterface
import java.util.*

/**
 * 描述：设备信息
 * 作者：孟崔广
 * 时间：2020/9/17 17:51
 */
class DeviceInfo private constructor() {
    private var mContext: Context? = null
    private fun init() {
        mContext = MintsApplication.getContext()
    }

    val proxyUrl: String?
        get() {
            var proxyUrl: String? = null
            if (!isWifi) {
                proxyUrl = Proxy.getDefaultHost()
            }
            return proxyUrl
        }

    /**
     * 返回系统语言
     *
     * zh-汉语
     * pt-葡萄牙语
     * en-英语
     *
     * @return
     */
    fun getLanguage(): String? {
        val locale: Locale
        var lang: String? = ""
        try {
            locale = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                mContext!!.resources.configuration.locales[0]
            } else {
                mContext!!.resources.configuration.locale
            }
            //或者仅仅使用 locale = Locale.getDefault(); 不需要考虑接口 deprecated(弃用)问题
            lang = locale.language
        } catch (e: java.lang.Exception) {
            e.printStackTrace()
        }
        return lang
    }

    /**
     * android4.2以上
     * 系统从启动到现在的时间
     * 单位:ms
     *
     */
    val elapsedRealtime = SystemClock.elapsedRealtime()

    /**
     * 运营商相关信息
     */
    val newModel: String
        get() {
            return brand + " " + mobileModel +
                    " " + totalMemory + "+" + totalStorage +
                    " " + operator
        }

    /**
     * 双卡信息只能在(android 5.1-9.0)获取
     *
     * 运营商名称
     *
     */
    val operator: String
        get() {
            val sb = StringBuilder("")
            try {

                // 判断是否使用单卡 (android10 获取不到双卡信息，只能获取单卡)
                var needSingleSim = false
                // 卡1
                val simStateBySlotIdx1 =
                    SimUtils.getSimStateBySlotIdx(MintsApplication.getContext(), 0)

                // 卡2
                val simStateBySlotIdx2 =
                    SimUtils.getSimStateBySlotIdx(MintsApplication.getContext(), 1)

                if (simStateBySlotIdx1) {
                    val providersName1 =
                        SimUtils.getSimOperatorName2(MintsApplication.getContext(), 0)

                    if (TextUtils.equals(providersName1, "unknown")) {
                        needSingleSim = true
                        sb.append(SimUtils.getSimOperatorNameBySingle(MintsApplication.getContext()) + " ")
                    } else {
                        sb.append("$providersName1 ")
                    }
                } else {
                    sb.append("未插卡 ")
                }

                if (simStateBySlotIdx2) {
                    val providersName2 =
                        SimUtils.getSimOperatorName2(MintsApplication.getContext(), 1)

                    if (TextUtils.equals(providersName2, "unknown") && !needSingleSim) {
                        sb.append(SimUtils.getSimOperatorNameBySingle(MintsApplication.getContext()) + " ")
                    } else {
                        sb.append("$providersName2")
                    }
                } else {
                    sb.append("未插卡")
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }

            return sb.toString()
        }

    /**
     * 是否使用vpn 需使用网络权限
     */
    val isVPN: Int
        get() {
            try {
                val niList = NetworkInterface.getNetworkInterfaces()
                if (niList != null) {
                    for (intf in Collections.list(niList)) {
                        if (!intf.isUp || intf.interfaceAddresses.size == 0) {
                            continue
                        }
                        if ("tun0" == intf.name || "ppp0" == intf.name) {
                            return 1 // The VPN is up
                        }
                    }
                }
            } catch (e: Throwable) {
                e.printStackTrace()
            }
            return 0
        }

    /**
     * 手机内存大小
     *
     */
    val totalMemory: String
        get() {
            return SystemUtils.getTotalMemory()
        }

    /**
     * 手机存储大小
     *
     */
    val totalStorage: String
        get() {
            return StorageQueryUtil.getTotalStorageSize(MintsApplication.getContext())
        }

    /**
     * get device's IMSI
     *
     * @return IMSI number
     */
    val iMSI: String
        get() = (mContext
            ?.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager).subscriberId

    /**
     * get device's IMEI
     *
     * @return IMEI number
     */
    val iMEI: String
        get() {
            var imei = ""
            try {
                imei =
                    (MintsApplication.getContext()
                        .getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager).deviceId
            } catch (e: Exception) {
                imei = ""
                e.printStackTrace()
            }
            return imei
        }

    val userAgent: String?
        get() {
            var userAgent: String? = ""
            try {
                userAgent = System.getProperty("http.agent")
            } catch (e: Exception) {
                e.printStackTrace()
            }
            return userAgent
        }

    /**
     * get device's MODEL
     *
     * @return model string
     */
    val mobileModel: String
        get() = Build.MODEL

    /**
     * Get application SDK version
     *
     * @return
     */
    val sDKVersionNumber: Int
        get() = Build.VERSION.SDK_INT

    /**
     * Get application OS version
     *
     * @return
     */
    val oSVersion: String
        get() = Build.VERSION.RELEASE

    /**
     * Test if wifi is activated
     *
     * @param
     * @return
     */
    val isWifi: Boolean
        get() {
            val connectivityManager = mContext
                ?.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
            val activeNetInfo = connectivityManager.activeNetworkInfo
            return (activeNetInfo != null
                    && activeNetInfo.type == ConnectivityManager.TYPE_WIFI)
        }

    /**
     * 获取versionName
     *
     * @return
     */
    val versionName: String
        get() {
            var versionName = "1.0.0"
            try {
                versionName = mContext!!.packageManager.getPackageInfo(
                    mContext!!.packageName, 0
                ).versionName
            } catch (e: PackageManager.NameNotFoundException) {
                e.printStackTrace()
            }
            return versionName
        }

    /**
     * 获取CPU核数
     *
     * @return
     */
    val cupCount: Int
        get() {
            if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.GINGERBREAD_MR1) {
                // Gingerbread doesn't support giving a single application access to both cores, but a
                // handful of devices (Atrix 4G and Droid X2 for example) were released with a dual-core
                // chipset and Gingerbread; that can let an app in the background run without impacting
                // the foreground application. But for our purposes, it makes them single core.
                return 1
            }
            val cores: Int
            cores = try {
                File("/sys/devices/system/cpu/").listFiles(CPU_FILTER).size
            } catch (e: SecurityException) {
                0
            } catch (e: java.lang.NullPointerException) {
                0
            }
            return cores
        }

    /**
     * 获取CPU型号
     *
     * @return
     */
    val cupInfo: String
        get() {
            val cpuInfo = arrayOf("", "") //0:型号 1：频率
            try {
                val str1 = "/proc/cpuinfo"
                var str2 = ""
                var arrayOfString: Array<String>
                val fr = FileReader(str1)
                if (fr != null) {
                    val localBufferedReader = BufferedReader(fr, 8192)
                    str2 = localBufferedReader.readLine()
                    arrayOfString = str2.split("\\s+".toRegex()).toTypedArray()
                    for (i in 2 until arrayOfString.size) {
                        cpuInfo[0] = cpuInfo[0] + arrayOfString[i] + " "
                    }
                    str2 = localBufferedReader.readLine()
                    arrayOfString = str2.split("\\s+".toRegex()).toTypedArray()
                    cpuInfo[1] += arrayOfString[2]
                    localBufferedReader.close()
                }
            } catch (e: IOException) {
                cpuInfo[0] = "unknow"
            }
            return cpuInfo[0]
        }

    /**
     * 获取versionCode
     *
     * @return
     */
    val versionCode: String
        get() {
            var versionCode = "0"
            try {
                versionCode = mContext!!.packageManager.getPackageInfo(
                    mContext!!.packageName, 0
                ).versionCode.toString()
            } catch (e: PackageManager.NameNotFoundException) {
                e.printStackTrace()
            }
            return versionCode
        }

    /**
     * 获取APP的名称
     *
     * @return
     */
    val appName: String
        get() {
            var appName = ""
            try {
                appName = mContext!!.resources.getString(R.string.app_name)
            } catch (e: Exception) {
                e.printStackTrace()
            }
            return appName
        }

    /**
     * 获取mac地址
     *
     * @return
     */
    private val mac: String?
        private get() {
            if (mContext == null) {
                return null
            }
            val wifi = mContext!!
                .getSystemService(Context.WIFI_SERVICE) as WifiManager
            val info = wifi.connectionInfo
            return info.macAddress
        }

    /**
     * 获取ssid地址
     *
     * @return
     */
    val ssid: String?
        get() {
            if (mContext == null) {
                return null
            }
            val wifi = mContext!!
                .getSystemService(Context.WIFI_SERVICE) as WifiManager
            val info = wifi.connectionInfo
            return info.ssid
        }

    /**
     * 设备品牌
     *
     * @return
     */
    val brand: String
        get() = Build.BRAND

    /**
     * 获取bssid地址
     *
     * @return
     */
    val bssid: String?
        get() {
            if (mContext == null) {
                return null
            }
            val wifi = mContext!!
                .getSystemService(Context.WIFI_SERVICE) as WifiManager
            val info = wifi.connectionInfo
            return info.bssid
        }

    /**
     * 获取apk签名
     *
     * @return
     */
    val signInfo: Boolean
        get() {
            var sign_bool = false
            try {
                val packageInfo = mContext!!.packageManager
                    .getPackageInfo(mContext!!.packageName, PackageManager.GET_SIGNATURES)
                val signs = packageInfo.signatures
                if (signs != null && signs.size != 0) {
                    for (i in signs.indices) {
                        val str =
                            Integer.toHexString(signs[i].toCharsString().hashCode())
                        println("mcg --_ " + str)
                        if ("652248d".equals(str, ignoreCase = true)
                        ) sign_bool = true
                    }
                }
            } catch (e: Exception) {
            }
            return sign_bool
        }

    /**
     * 获取基带版本
     *
     * @return
     */
    val bandInfo: String?
        get() {
            var result: Any? = null
            result = try {
                val cl = Class.forName("android.os.SystemProperties")
                val invoker = cl.newInstance()
                val m = cl.getMethod(
                    "get", *arrayOf<Class<*>>(
                        String::class.java, String::class.java
                    )
                )
                m.invoke(invoker, *arrayOf<Any>("gsm.version.baseband", "no message"))
            } catch (e: Exception) {
                "unknow"
            }
            return result as String?
        }

    /**
     * 获取附近wifi列表
     *
     * @param context
     * @return
     */
    fun getApsInfo(context: Context): String {
        val wifiManager =
            context.getSystemService(Context.WIFI_SERVICE) as WifiManager
        val apsInfo: MutableList<String> =
            ArrayList()
        val sbAps = StringBuffer()

//        //有些手机getScanResults 需要定位权限
        try {
            val scanResults =
                wifiManager.scanResults
            for (i in scanResults.indices) {
                apsInfo.add(scanResults[i].SSID.toString())
                if (i == scanResults.size - 1) {
                    sbAps.append(apsInfo[i])
                } else {
                    sbAps.append(apsInfo[i] + ",")
                }
            }
        } catch (e: Exception) {
        }
        return sbAps.toString()
    }

    /**
     * 获取基站信息
     *
     *
     * MCC，Mobile Country Code，移动国家代码（中国的为460）；
     * MNC，Mobile Network Code，移动网络号码（中国移动为00，中国联通为01）；
     */
    fun getCellInfo(context: Context): Array<String> {
        val mTelephonyManager =
            context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
        // 返回值MCC + MNC
        val cellInfo = arrayOf("", "")
        val operator = mTelephonyManager.networkOperator
        if (!TextUtils.isEmpty(operator)) {
            cellInfo[0] = operator.substring(0, 3)
            cellInfo[1] = operator.substring(3)
        }
        return cellInfo
    }

    /**
     * 最近安装10个APP列表
     *
     * @param context
     * @return
     */
    fun getAPPInstalled(context: Context): String {
        val listItems: MutableList<String?> =
            ArrayList()
        val installTime: MutableMap<Long, String> =
            HashMap()
        val time: MutableList<Long> = ArrayList()
        // 获取系统内的所有程序信息
        val mainintent = Intent(Intent.ACTION_MAIN, null)
        mainintent.addCategory(Intent.CATEGORY_LAUNCHER)
        val packageinfo =
            context.packageManager.getInstalledPackages(0)
        var pinfo: PackageInfo? = null
        val count = packageinfo.size
        for (i in 0 until count) {
            pinfo = packageinfo[i]
            val appInfo = pinfo.applicationInfo
            if (appInfo.flags and ApplicationInfo.FLAG_SYSTEM > 0) {
                //系统程序 忽略
            } else {
                //非系统程序
                time.add(pinfo.firstInstallTime)
                installTime[pinfo.firstInstallTime] =
                    pinfo.applicationInfo.loadLabel(context.packageManager) as String
            }
        }
        Collections.sort(
            time,
            Collections.reverseOrder()
        ) //降序
        val size = if (time.size >= 10) 10 else time.size
        for (i in 0 until size) {
            val s = installTime[time[i]]
            listItems.add(s)
        }
        val sb = StringBuffer()
        for (i in listItems.indices) {
            if (i == listItems.size - 1) {
                sb.append(listItems[i])
            } else {
                sb.append(listItems[i].toString() + ",")
            }
        }
        return sb.toString()
    }

    /**
     * 获取APP列表信息
     */
    fun getAppInfoMap(): String {
        try {
            val appList: MutableList<MutableMap<String, String>> = ArrayList()
            val mainintent = Intent(Intent.ACTION_MAIN, null)
            mainintent.addCategory(Intent.CATEGORY_LAUNCHER)
            val packageinfo =
                mContext!!.packageManager.getInstalledPackages(0)
            var pinfo: PackageInfo? = null
            val count = packageinfo.size
            for (i in 0 until count) {
                pinfo = packageinfo[i]
                val appInfo = pinfo.applicationInfo
                if (appInfo.flags and ApplicationInfo.FLAG_SYSTEM > 0) {
                    //系统程序 忽略
                } else {
                    //非系统程序
                    val appMap: MutableMap<String, String> = HashMap()
                    appMap["appName"] = appInfo.loadLabel(mContext!!.packageManager) as String
                    appMap["appPkg"] = pinfo.packageName
                    if (TextUtils.equals(
                            Constant.MINTS_PKG_NAME,
                            appInfo.loadLabel(mContext!!.packageManager) as String
                        ) &&
                        TextUtils.equals(pinfo.packageName, Constant.MINTS_PKG_NAME)
                    ) {
                        continue
                    }
                    appList.add(appMap)
                }
            }
            return JsonUtil.toJson(appList)
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return ""
    }

    /**
     * 获取APP名称列表信息
     */
    fun getAppNameInfoList(): MutableList<String>? {
        try {
            val appList: MutableList<String> = ArrayList()
            val mainintent = Intent(Intent.ACTION_MAIN, null)
            mainintent.addCategory(Intent.CATEGORY_LAUNCHER)
            val packageinfo =
                mContext!!.packageManager.getInstalledPackages(0)
            var pinfo: PackageInfo? = null
            val count = packageinfo.size
            for (i in 0 until count) {
                pinfo = packageinfo[i]
                val appInfo = pinfo.applicationInfo
                if (appInfo.flags and ApplicationInfo.FLAG_SYSTEM > 0) {
                    //系统程序 忽略
                } else {
                    //非系统程序
                    if (TextUtils.equals(
                            Constant.MINTS_PKG_NAME,
                            appInfo.loadLabel(mContext!!.packageManager) as String
                        ) &&
                        TextUtils.equals(pinfo.packageName, Constant.MINTS_PKG_NAME)
                    ) {
                        continue
                    }
                    appList.add(appInfo.loadLabel(mContext!!.packageManager) as String)
                }
            }

            return appList
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return null
    }

    /**
     * 获取APP包名列表信息
     */
    fun getAppPkgInfoList(): MutableList<String>? {
        try {
            val appList: MutableList<String> = ArrayList()
            val mainintent = Intent(Intent.ACTION_MAIN, null)
            mainintent.addCategory(Intent.CATEGORY_LAUNCHER)
            val packageinfo =
                mContext!!.packageManager.getInstalledPackages(0)
            var pinfo: PackageInfo? = null
            val count = packageinfo.size
            for (i in 0 until count) {
                pinfo = packageinfo[i]
                val appInfo = pinfo.applicationInfo
                if (appInfo.flags and ApplicationInfo.FLAG_SYSTEM > 0) {
                    //系统程序 忽略
                } else {
                    //非系统程序
                    if (TextUtils.equals(
                            Constant.MINTS_PKG_NAME,
                            appInfo.loadLabel(mContext!!.packageManager) as String
                        ) &&
                        TextUtils.equals(pinfo.packageName, Constant.MINTS_PKG_NAME)
                    ) {
                        continue
                    }

                    appList.add(pinfo.packageName)
                }
            }

            return appList
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return null
    }


    /**
     * 根据应用名称获取包名
     *
     * return:包名
     */
    fun getAppPkg(name: String): String {
        var pkg = ""
        try {
            val mainintent = Intent(Intent.ACTION_MAIN, null)
            mainintent.addCategory(Intent.CATEGORY_LAUNCHER)
            val packageinfo =
                mContext!!.packageManager.getInstalledPackages(0)
            var pinfo: PackageInfo? = null
            val count = packageinfo.size
            for (i in 0 until count) {
                pinfo = packageinfo[i]
                val appInfo = pinfo.applicationInfo
                if (appInfo.flags and ApplicationInfo.FLAG_SYSTEM > 0) {
                    //系统程序 忽略
                } else {
                    //非系统程序
                    if (TextUtils.equals(
                            name,
                            appInfo.loadLabel(mContext!!.packageManager) as String
                        )
                    ) {
                        pkg = pinfo.packageName
                        break
                    }
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return pkg
    }

    /**
     *
     *
     * return:包名
     */
    fun isLoadingPkg(pkg: String): Boolean {
        var flag = false
        try {
            val mainintent = Intent(Intent.ACTION_MAIN, null)
            mainintent.addCategory(Intent.CATEGORY_LAUNCHER)
            val packageinfo =
                mContext!!.packageManager.getInstalledPackages(0)
            var pinfo: PackageInfo? = null
            val count = packageinfo.size
            for (i in 0 until count) {
                pinfo = packageinfo[i]
                val appInfo = pinfo.applicationInfo
                if (appInfo.flags and ApplicationInfo.FLAG_SYSTEM > 0) {
                    //系统程序 忽略
                } else {
                    //非系统程序
                    if (TextUtils.equals(pkg, pinfo.packageName)) {
                        return true
                    }
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return flag
    }

    /**
     * Android ID
     *
     * @return
     */
    val androidId: String
        get() {
            val androidId = Settings.Secure.getString(
                mContext!!.contentResolver, Settings.Secure.ANDROID_ID
            )
            return if (TextUtils.isEmpty(androidId)) "unknow" else androidId
        }

    /**
     * Android ID
     *
     * @param context
     * @return
     */
    fun getAndroidId(context: Context?): String {
        val androidId = Settings.Secure.getString(
            mContext?.contentResolver, Settings.Secure.ANDROID_ID
        )
        return if (TextUtils.isEmpty(androidId)) "unknow" else androidId
    }// Gingerbread doesn't support giving a single application access to both cores, but a
    // handful of devices (Atrix 4G and Droid X2 for example) were released with a dual-core
    // chipset and Gingerbread; that can let an app in the background run without impacting
    // the foreground application. But for our purposes, it makes them single core.

    /**
     * 获取CPU核数
     *
     * @return
     */
    val cpuCount: Int
        get() {
            if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.GINGERBREAD_MR1) {
                // Gingerbread doesn't support giving a single application access to both cores, but a
                // handful of devices (Atrix 4G and Droid X2 for example) were released with a dual-core
                // chipset and Gingerbread; that can let an app in the background run without impacting
                // the foreground application. But for our purposes, it makes them single core.
                return 1
            }
            val cores: Int
            cores = try {
                File("/sys/devices/system/cpu/").listFiles(CPU_FILTER).size
            } catch (e: SecurityException) {
                0
            } catch (e: NullPointerException) {
                0
            }
            return cores
        }

    private val CPU_FILTER = FileFilter { pathname ->
        val path = pathname.name
        //regex is slow, so checking char by char.
        if (path.startsWith("cpu")) {
            for (i in 3 until path.length) {
                if (path[i] < '0' || path[i] > '9') {
                    return@FileFilter false
                }
            }
            return@FileFilter true
        }
        false
    }//0:型号 1：频率

    /**
     * 获取手机CPU信息
     *
     * @return
     */
    val cpuInfo: String
        get() {
            val str1 = "/proc/cpuinfo"
            var str2 = ""
            val cpuInfo = arrayOf("", "") //0:型号 1：频率
            var arrayOfString: Array<String>
            try {
                val fr = FileReader(str1)
                if (fr != null) {
                    val localBufferedReader = BufferedReader(fr, 8192)
                    str2 = localBufferedReader.readLine()
                    arrayOfString = str2.split("\\s+".toRegex()).toTypedArray()
                    for (i in 2 until arrayOfString.size) {
                        cpuInfo[0] = cpuInfo[0] + arrayOfString[i] + " "
                    }
                    str2 = localBufferedReader.readLine()
                    arrayOfString = str2.split("\\s+".toRegex()).toTypedArray()
                    cpuInfo[1] += arrayOfString[2]
                    localBufferedReader.close()
                }
            } catch (e: IOException) {
                cpuInfo[0] = "unknow"
            }
            return cpuInfo[0]
        }

    /**
     * 获取系统prop. 手机系统环境变量
     *
     * @return 如果不存在该key则返回空字符串
     * @throws IllegalArgumentException 如果key超过32个字符则返回空字符串
     */
//    @Throws(IllegalArgumentException::class)
//    operator fun get(context: Context, key: String?): String? {
//        var ret = ""
//        try {
//            val cl = context.classLoader
//            val SystemProperties = cl.loadClass("android.os.SystemProperties")
//
//            //参数类型
//            val paramTypes: Array<Class<*>> = arrayOfNulls(1)
//            paramTypes[0] = String::class.java
//            val get = SystemProperties.getMethod("get", *paramTypes)
//
//            //参数
//            val params = arrayOfNulls<Any>(1)
//            params[0] = String(key)
//            ret = get.invoke(SystemProperties, *params) as String
//        } catch (iAE: IllegalArgumentException) {
//            ret = ""
//        } catch (e: Exception) {
//            ret = ""
//        }
//        return ret
//    }

    /**
     * 获取MAC地址
     *
     * @param context
     * @return
     */
    fun getMacAddress(): String {
        var mac: String = "02:00:00:00:00:00"
        try {
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
                mac = getMacDefault()
            } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
                mac = macFromFile
            } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                mac = macFromHardware
            }
        } catch (e: Exception) {
        }
        return mac
    }

    /**
     * Android  6.0 之前（不包括6.0）
     * 必须的权限  <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
     *
     * @param context
     * @return
     */
    private fun getMacDefault(): String {
        var mac = "02:00:00:00:00:00"
        try {
            if (mContext == null) {
                return mac
            }
            val wifi = mContext!!.getSystemService(Context.WIFI_SERVICE) as WifiManager
                ?: return mac
            var info: WifiInfo? = null
            try {
                info = wifi.connectionInfo
            } catch (e: Exception) {
            }
            if (info == null) {
                return mac
            }
            mac = info.macAddress
            if (!TextUtils.isEmpty(mac)) {
                mac = mac.toUpperCase(Locale.ENGLISH)
            }
        } catch (e: Exception) {
        }
        return mac
    }

    /**
     * Android 6.0（包括） - Android 7.0（不包括）
     *
     * @return
     */
    private val macFromFile: String
        private get() {
            var WifiAddress = "02:00:00:00:00:00"
            try {
                WifiAddress =
                    BufferedReader(FileReader(File("/sys/class/net/wlan0/address")))
                        .readLine()
            } catch (e: IOException) {
                e.printStackTrace()
            }
            return WifiAddress
        }

    /**
     * 遍历循环所有的网络接口，找到接口是 wlan0
     * 必须的权限 <uses-permission android:name="android.permission.INTERNET"></uses-permission>
     *
     * @return
     */
    private val macFromHardware: String
        private get() {
            try {
                val all: List<NetworkInterface> =
                    Collections.list(NetworkInterface.getNetworkInterfaces())
                for (nif in all) {
                    if (!nif.name.equals("wlan0", ignoreCase = true)) continue
                    val macBytes = nif.hardwareAddress ?: return ""
                    val res1 = StringBuilder()
                    for (b in macBytes) {
                        res1.append(String.format("%02X:", b))
                    }
                    if (res1.length > 0) {
                        res1.deleteCharAt(res1.length - 1)
                    }
                    return res1.toString()
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
            return "02:00:00:00:00:00"
        }

    /**
     * 否充电中
     */
    val isCharging: Int
        get() {
            try {
                val batteryBroadcast: Intent? = mContext!!.registerReceiver(
                    null,
                    IntentFilter(Intent.ACTION_BATTERY_CHANGED)
                )
                val isCharging =
                    batteryBroadcast?.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1) != 0
                if (isCharging) {
                    return 1
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
            return 0
        }

    /**
     * 否处于USB调试模式
     */
    val getUsbStatus: Int
        get() {
            try {
                val enableAdb = Settings.Secure.getInt(
                    mContext!!.contentResolver, Settings.Secure.ADB_ENABLED, 0
                ) > 0
                if (enableAdb) {
                    return 1
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
            return 0
        }

    /**
     * 是否连接wifi
     */
    val getWifiConnected: Int
        get() {
            try {
                val connectivityManager =
                    mContext!!.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
                val activeNetInfo: NetworkInfo? = connectivityManager.activeNetworkInfo
                if (activeNetInfo != null && activeNetInfo.getType() === ConnectivityManager.TYPE_WIFI) {
                    return 1
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
            return 0
        }

    /**
     * 是否root
     */
    val isRoot: Int
        get() {
            var file: File? = null
            val paths = arrayOf(
                "/system/bin/",
                "/system/xbin/",
                "/system/sbin/",
                "/sbin/",
                "/vendor/bin/",
                "/su/bin/"
            )
            try {
                for (path in paths) {
                    file = File(path + "su")
                    if (file.exists() && file.canExecute()) {
                        return 1
                    }
                }
            } catch (x: java.lang.Exception) {
                x.printStackTrace()
            }
            return 0
        }

    /**
     * 获取后台运行APP
     */
    fun getRunningApp(): String {
        try {
            val appList: MutableList<MutableMap<String, String>> = ArrayList()
            val localPackageManager = mContext?.packageManager
            localPackageManager?.let {
                val localList = localPackageManager.getInstalledPackages(0)
                for (i in 0 until localList.size) {
                    val pinfo = localList.get(i) as PackageInfo

                    if (pinfo.applicationInfo.flags and ApplicationInfo.FLAG_SYSTEM > 0) {
                        //系统程序 忽略
                        continue
                    }

                    if (ApplicationInfo.FLAG_UPDATED_SYSTEM_APP and pinfo.applicationInfo.flags == 0
                        && ApplicationInfo.FLAG_STOPPED and pinfo.applicationInfo.flags == 0
                    ) {
                        val appMap: MutableMap<String, String> = HashMap()
                        appMap["appName"] =
                            pinfo.applicationInfo.loadLabel(mContext!!.packageManager) as String
                        appMap["appPkg"] = pinfo.packageName
                        appList.add(appMap)
                    }
                }
                return JsonUtil.toJson(appList)
            }
        } catch (e: Exception) {

        }
        return ""
    }

    /**
     * 是否鸿蒙系统
     *
     * return true-是
     */
    fun isHarmonyOS(): Boolean {
        try {
            val clz = Class.forName("com.huawei.system.BuildEx")
            val method: Method = clz.getMethod("getOsBrand")
            return "harmony" == method.invoke(clz)
        } catch (e: java.lang.Exception) {
            e.printStackTrace()
        }
        return false
    }

    /**
     * 是否是模拟器.
     *
     * @return `true`: 是
     */
    fun isEmulator(): Boolean {
        try {
            val checkProperty = (Build.FINGERPRINT.startsWith("generic")
                    || Build.FINGERPRINT.toLowerCase().contains("vbox")
                    || Build.FINGERPRINT.toLowerCase().contains("test-keys")
                    || Build.MODEL.contains("google_sdk")
                    || Build.MODEL.contains("Emulator")
                    || Build.MODEL.contains("Android SDK built for x86")
                    || Build.MANUFACTURER.contains("Genymotion")
                    || Build.BRAND.startsWith("generic") && Build.DEVICE.startsWith("generic")
                    || "google_sdk" == Build.PRODUCT)
            if (checkProperty) return true
            var operatorName = ""
            val tm = mContext!!.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
            if (tm != null) {
                val name = tm.networkOperatorName
                if (name != null) {
                    operatorName = name
                }
            }
            val checkOperatorName = operatorName.toLowerCase() == "android"
            if (checkOperatorName) return true
            val url = "tel:" + "123456"
            val intent = Intent()
            intent.data = Uri.parse(url)
            intent.action = Intent.ACTION_DIAL
            val checkDial = intent.resolveActivity(mContext!!.getPackageManager()) == null
            return if (checkDial) true else false
        }catch (e:Exception){
            e.printStackTrace()
            return false
        }
    }


    companion object {
        private var _inst: DeviceInfo? = null
        val instance: DeviceInfo
            get() = if (_inst != null) {
                _inst!!
            } else {
                _inst = DeviceInfo()
                _inst!!
            }
    }

    init {
        init()
    }
}