package com.ym.library.utils

import android.annotation.SuppressLint
import android.app.Activity
import android.content.ContentResolver
import android.content.Context
import android.content.pm.PackageManager
import android.net.ConnectivityManager
import android.net.NetworkInfo
import android.net.Uri
import android.net.wifi.WifiInfo
import android.net.wifi.WifiManager
import android.os.Build
import android.provider.MediaStore
import android.provider.Settings
import android.telephony.TelephonyManager
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.view.ViewTreeObserver
import com.ym.commen.module.VideoEntity
import com.ym.library.Constant
import com.ym.library.module.NewsEntity
import com.ym.library.module.NovelEntity
import com.ym.modulecommon.AppliContext
import okhttp3.Request
import java.io.*
import java.net.NetworkInterface
import java.net.SocketException
import java.net.URLEncoder
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException
import java.util.*

/**
 * Created by gaoleichao on 2018/7/12.
 */
object PhoneUtils {

    /**
     * 获取设备AndroidID
     *
     * @return AndroidID
     */
    @SuppressLint("HardwareIds")
    fun getAndroidID(context: Context): String {
        try {
            return Settings.Secure.getString(context.contentResolver, Settings.Secure.ANDROID_ID)
                ?: "2111111111111112"
        } catch (e: java.lang.Exception) {
            return "2111111111111112";
        }
        return "2111111111111112"
    }


    /**
     * 获取当前的运营商
     *
     * @param context
     * @return 运营商名字
     */
    @SuppressLint("MissingPermission", "HardwareIds")
    fun getOperator(context: Context): String {
        var ProvidersName = ""
        val telephonyManager =
            context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
        val IMSI: String?
        try {
            IMSI = telephonyManager.subscriberId
        } catch (e: SecurityException) {
//                Toast.makeText(context, "请开启读取手机权限", Toast.LENGTH_SHORT).show()
            return "0"
        }

        if (IMSI != null) {
            if (IMSI.startsWith("46000") || IMSI.startsWith("46002") || IMSI.startsWith("46007")) {
                //                ProvidersName = "移动";
                ProvidersName = "1"
            } else if (IMSI.startsWith("46001") || IMSI.startsWith("46006")) {
                ProvidersName = "2"
                //                ProvidersName = "联通";
            } else if (IMSI.startsWith("46003")) {
                ProvidersName = "3"
                //                ProvidersName = "电信";
            }
            return ProvidersName
        } else {
            return "0"
            //            return "没有获取到sim卡信息";
        }
    }

    fun getRealFilePath(context: Context, uri: Uri): String {
        if (null == uri) return ""
        val scheme = uri.getScheme()
        var data = ""
        if (scheme == null)
            data = uri.getPath();
        else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            var cursor =
                context.getContentResolver()
                    .query(uri, arrayOf(MediaStore.Images.ImageColumns.DATA), null, null, null);
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    val index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA)
                    if (index > -1) {
                        data = cursor.getString(index)
                    }
                }
                cursor.close()
            }
        }
        return data
    }

    /**
     * @Description: 获取屏幕的宽度
     * @param: context
     * @return: int
     */
    fun getScreenWidth(context: Context?): Int {
        return context?.resources?.displayMetrics?.widthPixels ?: 0
    }

    /**
     * 获取屏幕高度
     *
     * @param ctx
     * @return
     */
    fun getScreenHeight(ctx: Context?): Int {
        return ctx?.resources?.displayMetrics?.heightPixels ?: 0
    }

    /**
     * 获取设备型号
     *
     * 如MI2SC
     *
     * @return 设备型号
     */
    fun getModel(): String {
        var model: String? = Build.MODEL
        if (model != null) {
            model = model.trim { it <= ' ' }.replace("\\s*".toRegex(), "")
        } else {
            model = ""
        }
        return model
    }

    /**
     * 获取App版本码
     *
     * @return App版本码
     */
    fun getAppVersionCode(context: Context): Int {
        return getAppVersionCode(context.packageName, context)
    }

    /**
     * 获取App版本码
     *
     * @return App版本码
     */
    fun getAppPackage(): String? {
        return AppliContext.get().packageName
    }

    /**
     * 获取App版本码
     *
     * @param packageName 包名
     * @return App版本码
     */
    fun getAppVersionCode(packageName: String, context: Context): Int {
        if (isSpace(packageName)) return -1
        try {
            val pm = context.getPackageManager()
            val pi = pm.getPackageInfo(packageName, 0)
            return if (pi == null) -1 else pi?.versionCode
        } catch (e: PackageManager.NameNotFoundException) {
            e.printStackTrace()
            return -1
        }
    }

    private fun isSpace(s: String?): Boolean {
        if (s == null) return true
        var i = 0
        val len = s.length
        while (i < len) {
            if (!Character.isWhitespace(s[i])) {
                return false
            }
            ++i
        }
        return true
    }


    /**
     * 获取App版本号
     *
     * @return App版本号
     */
    fun getAppVersionName(context: Context): String {
        return getAppVersionName(context.packageName, context)
    }

    /**
     * 获取App版本号
     *
     * @param packageName 包名
     * @return App版本号
     */
    fun getAppVersionName(packageName: String, context: Context): String {
        if (isSpace(packageName)) return ""
        try {
            val pm = context.packageManager
            val pi = pm.getPackageInfo(packageName, 0)
            return if (pi == null) "" else pi?.versionName
        } catch (e: PackageManager.NameNotFoundException) {
            e.printStackTrace()
            return ""
        }

    }

    /**
     * 获取IP地址
     *
     * 需添加权限 `<uses-permission android:name="android.permission.INTERNET"/>`
     *
     * @param useIPv4 是否用IPv4
     * @return IP地址
     */
    fun getIPAddress(useIPv4: Boolean): String {
        try {
            val nis = NetworkInterface.getNetworkInterfaces()
            while (nis.hasMoreElements()) {
                val ni = nis.nextElement()
                // 防止小米手机返回10.0.2.15
                if (!ni.isUp) continue
                val addresses = ni.inetAddresses
                while (addresses.hasMoreElements()) {
                    val inetAddress = addresses.nextElement()
                    if (!inetAddress.isLoopbackAddress) {
                        val hostAddress = inetAddress.hostAddress
                        val isIPv4 = hostAddress.indexOf(':') < 0
                        if (useIPv4) {
                            if (isIPv4) return hostAddress
                        } else {
                            if (!isIPv4) {
                                val index = hostAddress.indexOf('%')
                                return if (index < 0) hostAddress.toUpperCase() else hostAddress.substring(
                                    0,
                                    index
                                ).toUpperCase()
                            }
                        }
                    }
                }
            }
        } catch (e: SocketException) {
            e.printStackTrace()
        }
        return ""
    }

    fun getDeviceId(context: Context): String {
        return getMd5Value(getAndroidID(context))
    }

    fun getMd5Value(sSecret: String): String {
        try {
            val bmd5 = MessageDigest.getInstance("MD5")
            bmd5.update(sSecret.toByteArray())
            var i: Int
            val buf = StringBuffer()
            val b = bmd5.digest()
            for (offset in b.indices) {
                i = b[offset].toInt()
                if (i < 0)
                    i += 256
                if (i < 16)
                    buf.append("0")
                buf.append(Integer.toHexString(i))
            }
            return buf.toString()
        } catch (e: NoSuchAlgorithmException) {
            e.printStackTrace()
            return ""
        }
        return ""
    }


    @SuppressLint("MissingPermission")
    fun getImei(context: Context): String {
        try {
            val telephonyManager: TelephonyManager = context
                .getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
            return telephonyManager.deviceId ?: ""
        } catch (e: SecurityException) {
//            Toast.makeText(context, "请开启读取手机权限", Toast.LENGTH_SHORT).show()
            // In some devices, we are not able to get device id, and may cause some exception,
            // so catch it.
            return ""
        }
        return ""

    }

    fun getMac(context: Context): String? {
        var strMac: String? = null
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            LogUtils.e("=====", "6.0以下")
            strMac = getLocalMacAddressFromWifiInfo(context)
            return strMac
        } else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            LogUtils.e("=====", "6.0以上7.0以下")
            strMac = getMacAddress(context)
            return strMac
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            LogUtils.e("=====", "7.0以上")
            if (!TextUtils.isEmpty(getMacAddress(context))) {
                LogUtils.e("=====", "7.0以上1")
                strMac = getMacAddress(context)
                return strMac
            } else if (!TextUtils.isEmpty(getMachineHardwareAddress())) {
                LogUtils.e("=====", "7.0以上2")
                strMac = getMachineHardwareAddress()
                return strMac
            } else {
                LogUtils.e("=====", "7.0以上3")
                strMac = getLocalMacAddressFromBusybox()
                return strMac
            }
        }
        return ""
    }

    @SuppressLint("MissingPermission")
    fun getLocalMacAddressFromWifiInfo(ctx: Context): String {
        val wifi = ctx.getSystemService(Context.WIFI_SERVICE) as WifiManager
        val info = wifi.connectionInfo
        var str: String? = info.macAddress
        if (str == null) str = ""
        return str
    }


    /**
     * android 7.0及以上 （3）通过busybox获取本地存储的mac地址
     *
     */

    /**
     * 根据busybox获取本地Mac
     *
     * @return
     */
    fun getLocalMacAddressFromBusybox(): String {
        var result: String? = ""
        var Mac = ""
        result = callCmd("busybox ifconfig", "HWaddr")
        // 如果返回的result == null，则说明网络不可取
        if (TextUtils.isEmpty(result)) {
            //            return "网络异常";
            return ""
        }
        // 对该行数据进行解析
        // 例如：eth0 Link encap:Ethernet HWaddr 00:16:E8:3E:DF:67
        if (result?.length ?: 0 > 0 && result?.contains("HWaddr") == true) {
            Mac = result.substring(result.indexOf("HWaddr") + 6, result.length - 1)
            result = Mac
        }
        return result ?: ""
    }

    private fun callCmd(cmd: String, filter: String): String? {
        var result = ""
        var line = ""
        try {
            val proc = Runtime.getRuntime().exec(cmd)
            val mInputStream = InputStreamReader(proc.inputStream) ?: return ""
            val br = BufferedReader(mInputStream)
            while ((line == br.readLine()) != null && line.contains(filter) == false) {
                result += line
                if (TextUtils.isEmpty(result)) {
                    return ""
                }
            }
            result = line
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return result
    }
    /**
     * android 7.0及以上 （2）扫描各个网络接口获取mac地址
     *
     */
    /**
     * 获取设备HardwareAddress地址
     *
     * @return
     */

    fun getMachineHardwareAddress(): String {
        var interfaces: Enumeration<NetworkInterface>? = null
        try {
            interfaces = NetworkInterface.getNetworkInterfaces()
        } catch (e: SocketException) {
            e.printStackTrace()
        }

        var hardWareAddress = ""
        var iF: NetworkInterface? = null
        if (interfaces == null) {
            return ""
        }
        while (interfaces.hasMoreElements()) {
            iF = interfaces.nextElement()
            try {
                hardWareAddress = bytesToString(iF?.hardwareAddress)
                if (hardWareAddress != null)
                    break
            } catch (e: SocketException) {
                e.printStackTrace()
            }

        }
        return hardWareAddress
    }

    /***
     * byte转为String
     *
     * @param bytes
     * @return
     */
    private fun bytesToString(bytes: ByteArray?): String {
        if (bytes == null || bytes.isEmpty()) {
            return ""
        }
        val buf = StringBuilder()
        for (b in bytes) {
            buf.append(String.format("%02X:", b))
        }
        if (buf.length > 0) {
            buf.deleteCharAt(buf.length - 1)
        }
        return buf.toString()
    }

    /**
     * android 6.0及以上、7.0以下 获取mac地址
     *
     * @param context
     * @return
     */

    fun getMacAddress(context: Context): String {

        // 如果是6.0以下，直接通过wifimanager获取
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            val macAddress0 = getMacAddress0(context)
            if (!TextUtils.isEmpty(macAddress0)) {
                return macAddress0
            }
        }
        var str = ""
        var macSerial = ""
        try {
            val pp = Runtime.getRuntime().exec(
                "cat /sys/class/net/wlan0/address"
            )
            val ir = InputStreamReader(pp.inputStream)
            val input = LineNumberReader(ir)
            while (null != str) {
                str = input.readLine()
                if (str != null) {
                    macSerial = str.trim { it <= ' ' }// 去空格
                    break
                }
            }
        } catch (ex: Exception) {
            LogUtils.e("----->" + "NetInfoManager", "getMacAddress:" + ex.toString())
        }

        if (macSerial == null || "" == macSerial) {
            try {
                return loadFileAsString("/sys/class/net/eth0/address")
                    .toUpperCase().substring(0, 17)
            } catch (e: Exception) {
                e.printStackTrace()
                LogUtils.e(
                    "----->" + "NetInfoManager",
                    "getMacAddress:" + e.toString()
                )
            }

        }
        return macSerial
    }

    @SuppressLint("MissingPermission")
    private fun getMacAddress0(context: Context): String {
        if (isAccessWifiStateAuthorized(context)) {
            val wifiMgr = context
                .getSystemService(Context.WIFI_SERVICE) as WifiManager
            var wifiInfo: WifiInfo? = null
            try {
                wifiInfo = wifiMgr.connectionInfo
                return wifiInfo?.macAddress ?: ""
            } catch (e: Exception) {
                LogUtils.e(
                    "----->" + "NetInfoManager",
                    "getMacAddress0:" + e.toString()
                )
            }

        }
        return ""

    }

    /**
     * Check whether accessing wifi state is permitted
     *
     * @param context
     * @return
     */
    private fun isAccessWifiStateAuthorized(context: Context): Boolean {
        if (PackageManager.PERMISSION_GRANTED == context
                .checkCallingOrSelfPermission("android.permission.ACCESS_WIFI_STATE")
        ) {
            LogUtils.e(
                "----->" + "NetInfoManager",
                "isAccessWifiStateAuthorized:" + "access wifi state is enabled"
            )
            return true
        } else
            return false
    }

    private fun loadFileAsString(fileName: String): String {
        try {
            val reader = FileReader(fileName)
            val text = loadReaderAsString(reader)
            reader.close()
            return text
        } catch (e: Exception) {
            return ""
        }
    }

    @Throws(Exception::class)
    private fun loadReaderAsString(reader: Reader): String {
        val builder = StringBuilder()
        val buffer = CharArray(4096)
        var readLength = reader.read(buffer)
        while (readLength >= 0) {
            builder.append(buffer, 0, readLength)
            readLength = reader.read(buffer)
        }
        return builder.toString()
    }

    /**
     * 获取当前网络类型
     *
     * 需添加权限 `<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>`
     *
     * @return 网络类型
     */

    enum class NetworkType {
        NETWORK_WIFI,
        NETWORK_4G,
        NETWORK_3G,
        NETWORK_2G,
        NETWORK_UNKNOWN,
        NETWORK_NO
    }

    fun getNetworkType(context: Context): NetworkType {
        var netType = NetworkType.NETWORK_NO
        val info = getActiveNetworkInfo(context)
        if (info != null && info?.isAvailable) {
            if (info?.type == ConnectivityManager.TYPE_WIFI) {
                netType = NetworkType.NETWORK_WIFI
            } else if (info?.type == ConnectivityManager.TYPE_MOBILE) {
                when (info?.subtype) {
                    TelephonyManager.NETWORK_TYPE_GSM, TelephonyManager.NETWORK_TYPE_GPRS, TelephonyManager.NETWORK_TYPE_CDMA, TelephonyManager.NETWORK_TYPE_EDGE, TelephonyManager.NETWORK_TYPE_1xRTT, TelephonyManager.NETWORK_TYPE_IDEN -> netType =
                        NetworkType.NETWORK_2G

                    TelephonyManager.NETWORK_TYPE_TD_SCDMA, TelephonyManager.NETWORK_TYPE_EVDO_A, TelephonyManager.NETWORK_TYPE_UMTS, TelephonyManager.NETWORK_TYPE_EVDO_0, TelephonyManager.NETWORK_TYPE_HSDPA, TelephonyManager.NETWORK_TYPE_HSUPA, TelephonyManager.NETWORK_TYPE_HSPA, TelephonyManager.NETWORK_TYPE_EVDO_B, TelephonyManager.NETWORK_TYPE_EHRPD, TelephonyManager.NETWORK_TYPE_HSPAP -> netType =
                        NetworkType.NETWORK_3G

                    TelephonyManager.NETWORK_TYPE_IWLAN, TelephonyManager.NETWORK_TYPE_LTE -> netType =
                        NetworkType.NETWORK_4G
                    else -> {

                        val subtypeName = info?.subtypeName
                        if (subtypeName.equals("TD-SCDMA", ignoreCase = true)
                            || subtypeName.equals("WCDMA", ignoreCase = true)
                            || subtypeName.equals("CDMA2000", ignoreCase = true)
                        ) {
                            netType = NetworkType.NETWORK_3G
                        } else {
                            netType = NetworkType.NETWORK_UNKNOWN
                        }
                    }
                }
            } else {
                netType = NetworkType.NETWORK_UNKNOWN
            }
        }
        return netType
    }


    /**
     * 获取活动网络信息
     *
     * 需添加权限 `<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>`
     *
     * @return NetworkInfo
     */
    @SuppressLint("MissingPermission")
    private fun getActiveNetworkInfo(context: Context): NetworkInfo? {
        val manager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        try {
            return manager.activeNetworkInfo
        } catch (e: Exception) {
            return null
        }
    }

    fun buildMap(map: Map<String, String>): String {
        val sb = StringBuffer()
        if (map.size > 0) {
            for (key in map.keys) {
                sb.append(key + "=")
                if (TextUtils.isEmpty(map[key])) {
                    sb.append("&")
                } else {
                    var value = map[key]
                    try {
                        value = URLEncoder.encode(value, "UTF-8")
                    } catch (e: UnsupportedEncodingException) {
                        e.printStackTrace()
                    }

                    sb.append(value + "&")
                }
            }
        }
        return sb.toString()
    }


    @SuppressLint("MissingPermission")
    fun getBSSID(context: Context): String {
        val mWifiManager: WifiManager =
            context.getSystemService(Context.WIFI_SERVICE) as WifiManager
        val mWifiInfo: WifiInfo = mWifiManager.connectionInfo
        return if (mWifiInfo == null) "" else mWifiInfo.bssid ?: ""
    }

    /**
     * 获取手机IMSI号
     */
    @SuppressLint("MissingPermission")
    fun getIMSI(context: Context): String {
        try {
            val mTelephonyMgr =
                context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
            return mTelephonyMgr.subscriberId ?: ""
        } catch (e: Exception) {
            return ""
        }
        return ""

    }

    val METHOD_GET_DEVICE_VALIDATION_TOKEN = "getDeviceValidationToken"
    val RESULT_DEVICE_VALIDATION_TOKEN_JSON = "device_token_json"
    val KEY_DEVICE_VALIDATION_TOKEN = "token"


//    fun addParam(request: Request, builder: HttpUrl.Builder) {
//        val params = addCommonParam()
//        params.put("appKey", "faba1d018f76086")
//        params.put("appLs", Constant.appLs)
//        params.put("gender", SettingPreference.getGender().toString())
//
//        for (i in 0 until request.url().querySize()) {
//            val url = request.url()
//            params.put(url.queryParameterName(i), url.queryParameterValue(i))
//        }
//
//        for (i in 0 until request.url().querySize()) {
//            val url = request.url()
//            builder.removeAllQueryParameters(url.queryParameterName(i))
//        }
//
////        Utils.showToast(AppliContext.get(), SettingPreference.getSource())
//
//        if (params != null && params.size > 0) {
//            if (CesCore.getInstance().isInit) {
//                val json = buildMap(params)
//                builder.addQueryParameter("datamd5", Utils.md5(json))
//                params.put("datamd5", Utils.md5(json))
//
//                val data = CesCore.getInstance().Dowork(json, SettingPreference.getAndroidId())
//                if (!TextUtils.isEmpty(data)) {
//                    val data = URLEncoder.encode(data, "utf-8")
//                    builder.addQueryParameter("data", data)
//                } else {
//                    val putkeys = params.keys
//                    for (s in putkeys) {
//                        builder.addQueryParameter(s, params[s])
//                    }
//                }
//            } else {
//                val putkeys = params.keys
//                for (s in putkeys) {
//                    builder.addQueryParameter(s, params[s])
//                }
//            }
//            var string = ""
//            val sortMap = TreeMap<String, String>(MapKeyComparator())
//            sortMap.putAll(params)
//            for ((item, value) in sortMap) {
//                string += value
//            }
//            Log.d("glc", string)
//            string = CesCore.getInstance().Sgwork(string)
//            builder.addQueryParameter("sign", string)
//        }
////        val putkeys = params.keys
////        for (s in putkeys) {
////            builder.addQueryParameter(s, params[s])
////        }
////
////        var string = ""
////        val sortMap = TreeMap<String, String>(MapKeyComparator())
////        sortMap.putAll(params)
////        for ((_, value) in sortMap) {
////            if (!TextUtils.isEmpty(value)) {
////                string += value
////            }
////        }
////        string = Utils.md5(Utils.md5(string + Constant.a) + SettingPreference.getAppSecret()).substring(0, 16)
////        builder.addQueryParameter("sign", string)
//
//        params.clear()
//    }

    fun addHeader(builder: HashMap<String, String>) {
        builder.put(Constant.pkg, Constant.Param.mPacketName)
        builder.put(Constant.platform, "android")
        builder.put(Constant.vendor, Constant.Param.vendor)
        builder.put(Constant.svn, Constant.Param.svn)
        Log.d("addHeader", "Constant.Param.svn:" + Constant.Param.svn)

//        builder.addHeader(Constant.token, SettingPreference.getUserToken())
//        builder.addHeader(Constant.source, SettingPreference.getChannel())

//        builder.addHeader(Constant.demd5, SettingPreference.getMd5())
//        builder.addHeader(Constant.cv, SettingPreference.getCV())

//        builder.addHeader(Constant.lat, SettingPreference.getLat())
//        builder.addHeader(Constant.lon, SettingPreference.getLon())
//        builder.addHeader(Constant.locationtype, SettingPreference.getLocationType())
//        builder.addHeader(Constant.city, URLEncoder.encode(SettingPreference.getCity(), "utf-8"))
        builder.put(Constant.source, com.ym.modulecommon.utils.SettingPreference.getSource())
        builder.put(Constant.vc, com.ym.modulecommon.utils.SettingPreference.getVC())
        builder.put(Constant.vn, com.ym.modulecommon.utils.SettingPreference.getVN())
        builder.put(Constant.h, com.ym.modulecommon.utils.SettingPreference.getH())
        builder.put(Constant.w, com.ym.modulecommon.utils.SettingPreference.getW())
        builder.put(Constant.model, com.ym.modulecommon.utils.SettingPreference.getModel())
        builder.put(Constant.ntt, com.ym.modulecommon.utils.SettingPreference.getNTT())
        builder.put(Constant.aid, com.ym.modulecommon.utils.SettingPreference.getAndroidId())
        builder.put(Constant.device, com.ym.modulecommon.utils.SettingPreference.getDevice())
        builder.put(Constant.carrier, com.ym.modulecommon.utils.SettingPreference.getCarrier())
        builder.put(Constant.mac, com.ym.modulecommon.utils.SettingPreference.getMac())
        builder.put(Constant.imei, com.ym.modulecommon.utils.SettingPreference.getImei())
        builder.put(Constant.imsi, com.ym.modulecommon.utils.SettingPreference.getImsi())
        builder.put(Constant.ssid, com.ym.modulecommon.utils.SettingPreference.getSsid())
        System.out.println("com.ym.modulecommon.utils.SettingPreference.getAndroidId():" + com.ym.modulecommon.utils.SettingPreference.getAndroidId())
        if (!TextUtils.isEmpty(com.ym.modulecommon.utils.SettingPreference.getUserAgent())) {
            builder.put("web-user-agent", com.ym.modulecommon.utils.SettingPreference.getUserAgent())
            builder.remove("User-Agent")
            builder.put("User-Agent", com.ym.modulecommon.utils.SettingPreference.getUserAgent())
        }
//        if (!TextUtils.isEmpty(com.ym.modulecommon.utils.SettingPreference.getUid())) {
//            builder.put("uid", com.ym.modulecommon.utils.SettingPreference.getUid())
//        }
    }

    fun addHeader(builder: Request.Builder) {
        builder.addHeader(Constant.pkg, Constant.Param.mPacketName)
        builder.addHeader(Constant.platform, "android")
        builder.addHeader(Constant.vendor, Constant.Param.vendor)
        builder.addHeader(Constant.svn, Constant.Param.svn)

        builder.addHeader(Constant.token, com.ym.modulecommon.utils.SettingPreference.getToken())
        builder.addHeader(Constant.vc, com.ym.modulecommon.utils.SettingPreference.getVC())
        builder.addHeader(Constant.vn, com.ym.modulecommon.utils.SettingPreference.getVN())
        builder.addHeader(Constant.h, com.ym.modulecommon.utils.SettingPreference.getH())
        builder.addHeader(Constant.w, com.ym.modulecommon.utils.SettingPreference.getW())
        builder.addHeader(Constant.model, com.ym.modulecommon.utils.SettingPreference.getModel())
        builder.addHeader(Constant.ntt, com.ym.modulecommon.utils.SettingPreference.getNTT())
        builder.addHeader(Constant.aid, com.ym.modulecommon.utils.SettingPreference.getAndroidId())
        builder.addHeader(Constant.device, com.ym.modulecommon.utils.SettingPreference.getDevice())
        builder.addHeader(Constant.carrier, com.ym.modulecommon.utils.SettingPreference.getCarrier())
        builder.addHeader(Constant.mac, com.ym.modulecommon.utils.SettingPreference.getMac())
        builder.addHeader(Constant.imei, com.ym.modulecommon.utils.SettingPreference.getImei())
        builder.addHeader(Constant.imsi, com.ym.modulecommon.utils.SettingPreference.getImsi())
        builder.addHeader(Constant.ssid, com.ym.modulecommon.utils.SettingPreference.getSsid())
        builder.addHeader(Constant.source, com.ym.modulecommon.utils.SettingPreference.getSource())

        if (!TextUtils.isEmpty(com.ym.modulecommon.utils.SettingPreference.getUserAgent())) {
            builder.addHeader("web-user-agent", com.ym.modulecommon.utils.SettingPreference.getUserAgent())
            builder.removeHeader("User-Agent")
            builder.addHeader("User-Agent", com.ym.modulecommon.utils.SettingPreference.getUserAgent())
        }
        if (!TextUtils.isEmpty(com.ym.modulecommon.utils.SettingPreference.getUid())) {
            builder.addHeader("uid", com.ym.modulecommon.utils.SettingPreference.getUid())
        }
        builder.addHeader(
            "dip",
            AppliContext.get().getResources().getDisplayMetrics().density.toString()
        )
    }

    fun addCommonParam(): HashMap<String, String> {
        val params = HashMap<String, String>()
        val ts = System.currentTimeMillis().toString()
        params.put(Constant.Device.ts, ts)
//        params.put("appKey", "faba1d018f76086")
//        params.put("appLs", Constant.appLs)
        params.put(Constant.Device.uid, com.ym.modulecommon.utils.SettingPreference.getUid())
        params.put(Constant.Device.token, com.ym.modulecommon.utils.SettingPreference.getToken())
        params.put(Constant.Device.pkg, AppliContext.get().packageName)
        params.put(Constant.Device.aid, com.ym.modulecommon.utils.SettingPreference.getAndroidId())
        params.put(Constant.Device.imei, com.ym.modulecommon.utils.SettingPreference.getImei())
        params.put(Constant.Device.device, com.ym.modulecommon.utils.SettingPreference.getDevice())
        params.put(Constant.Device.mac, com.ym.modulecommon.utils.SettingPreference.getMac())
        params.put(Constant.Device.platform, "android")
        params.put(Constant.Device.carrier, com.ym.modulecommon.utils.SettingPreference.getCarrier())
        params.put(Constant.Device.w, com.ym.modulecommon.utils.SettingPreference.getW())
        params.put(Constant.Device.vendor, Build.MANUFACTURER)
        params.put(Constant.Device.h, com.ym.modulecommon.utils.SettingPreference.getH())
        params.put(Constant.Device.ip, com.ym.modulecommon.utils.SettingPreference.getIp())
        params.put(Constant.Device.imsi, com.ym.modulecommon.utils.SettingPreference.getImsi())
        params.put(Constant.Device.model, com.ym.modulecommon.utils.SettingPreference.getModel())
        params.put(Constant.Device.vn, com.ym.modulecommon.utils.SettingPreference.getVN())
        params.put(Constant.Device.ntt, com.ym.modulecommon.utils.SettingPreference.getNTT())
        params.put(Constant.Device.vc, com.ym.modulecommon.utils.SettingPreference.getVC())
        params.put(Constant.Device.source, com.ym.modulecommon.utils.SettingPreference.getSource())
        params.put(Constant.Device.ua, com.ym.modulecommon.utils.SettingPreference.getUA())
        params.put(Constant.Device.svn, com.ym.modulecommon.utils.SettingPreference.getSVN())
        params.put(Constant.Device.lat, com.ym.modulecommon.utils.SettingPreference.getLat())
        params.put(Constant.Device.lon, com.ym.modulecommon.utils.SettingPreference.getLon())
        params.put(Constant.Device.locationtype, com.ym.modulecommon.utils.SettingPreference.getLocationType())
//        params.put(Constant.Device.city, URLEncoder.encode(com.ym.modulecommon.utils.SettingPreference.getCity(), "utf-8"))
        params.put(Constant.Device.city, com.ym.modulecommon.utils.SettingPreference.getCity())

        params.put(
            "dip",
            AppliContext.get()?.getResources()?.getDisplayMetrics()?.density.toString()
        )
        if (!TextUtils.isEmpty(com.ym.modulecommon.utils.SettingPreference.getUserAgent())) {
            params.put("web-user-agent", com.ym.modulecommon.utils.SettingPreference.getUserAgent())
        }
        params.put("device_uuid", com.ym.modulecommon.utils.SettingPreference.getUUid())
        return params
    }


    fun getHeadMap(): Map<String, String> {
        val builder: MutableMap<String, String> = HashMap()
        builder.put("h", Constant.Param.h)
        builder.put("w", Constant.Param.w)
        builder.put("model", Constant.Param.model)
        builder.put("vendor", Constant.Param.vendor)
        builder.put("svn", Constant.Param.svn)
        builder.put("ntt", Constant.Param.ntt)
        builder.put("token", Constant.Param.token)
        builder.put("vc", Constant.Param.vc)
        builder.put("vn", Constant.Param.vn)
        builder.put("aid", Constant.Param.androidId)
        builder.put("device", Constant.Param.device)
        builder.put("carrier", Constant.Param.carrier)
        builder.put("demd5", Constant.Param.md5)
        builder.put("mac", Constant.Param.mac)
        builder.put("source", Constant.Param.source)
        builder.put("imei", Constant.Param.imei)
        builder.put("user-agent", Constant.Param.userAgent)
        builder.put("platform", "android")
        builder.put("env", com.ym.modulecommon.Constant.param.env)
        builder.put("cv", Constant.Param.cv)
        builder.put("lat", Constant.Param.lat)
        builder.put("lon", Constant.Param.lon)
        builder.put("imsi", Constant.Param.imsi)
        builder.put("locationtype", Constant.Param.locationType)
        builder.put("city", URLEncoder.encode(Constant.Param.city, "utf-8"))
        builder.put("ssid", Constant.Param.ssid)
        builder.put("mitoken", Constant.Param.miToken)
        if (!TextUtils.isEmpty(Constant.Param.uid)) {
            builder.put("uid", Constant.Param.uid)
        }
        return builder
    }

    fun replaceUrl(url: String, entity: NewsEntity): String {

        var data: String = url
            .replace(
                "__SLOT_WIDTH__",
                if (TextUtils.isEmpty(entity.ad_width)) "-999" else entity.ad_width
                    ?: "-999"
            )
            .replace(
                "__SLOT_HEIGHT__",
                if (TextUtils.isEmpty(entity.ad_width)) "-999" else entity.ad_width
                    ?: "-999"
            )

            .replace(
                "__RE_DOWN_X__",
                if (TextUtils.isEmpty(entity.clickViewDownX)) "-999" else entity.clickViewDownX
                    ?: "-999"
            )
            .replace(
                "__RE_DOWN_Y__",
                if (TextUtils.isEmpty(entity.clickViewDownY)) "-999" else entity.clickViewDownY
                    ?: "-999"
            )

            .replace(
                "__RE_UP_X__",
                if (TextUtils.isEmpty(entity.clickViewUpX)) "-999" else entity.clickViewUpX
                    ?: "-999"
            )
            .replace(
                "__RE_UP_Y__",
                if (TextUtils.isEmpty(entity.clickViewUpY)) "-999" else entity.clickViewUpY
                    ?: "-999"
            )

            .replace(
                "__DOWN_X__",
                if (TextUtils.isEmpty(entity.clickDownX)) "-999" else entity.clickDownX
                    ?: "-999"
            )
            .replace(
                "__DOWN_Y__",
                if (TextUtils.isEmpty(entity.clickDownY)) "-999" else entity.clickDownY
                    ?: "-999"
            )

            .replace(
                "__UP_X__", if (TextUtils.isEmpty(entity.clickUpX)) "-999" else entity.clickUpX
                    ?: "-999"
            )
            .replace(
                "__UP_Y__", if (TextUtils.isEmpty(entity.clickUpY)) "-999" else entity.clickUpY
                    ?: "-999"
            )

            .replace(
                "__LAT__", "-999"
                    ?: "-999"
            )
            .replace(
                "__LON__", "-999"
                    ?: "-999"
            )

            .replace(
                "__SLOT_HEIGHT__",
                if (TextUtils.isEmpty(entity.ad_height)) "-999" else entity.ad_height
                    ?: "-999"
            )
            .replace("__UTC_TS__", System.currentTimeMillis().toString())
            .replace(
                "__CLICK_ID__", if (TextUtils.isEmpty(entity.clickId)) "-999" else entity.clickId
                    ?: "-999"
            )

        return data
    }

    fun replaceUrl(url: String, entity: NovelEntity): String {

        var data: String = url
            .replace(
                "__SLOT_WIDTH__",
                if (TextUtils.isEmpty(entity.ad_width)) "-999" else entity.ad_width
                    ?: "-999"
            )
            .replace(
                "__SLOT_HEIGHT__",
                if (TextUtils.isEmpty(entity.ad_width)) "-999" else entity.ad_width
                    ?: "-999"
            )

            .replace(
                "__RE_DOWN_X__",
                if (TextUtils.isEmpty(entity.clickViewDownX)) "-999" else entity.clickViewDownX
                    ?: "-999"
            )
            .replace(
                "__RE_DOWN_Y__",
                if (TextUtils.isEmpty(entity.clickViewDownY)) "-999" else entity.clickViewDownY
                    ?: "-999"
            )

            .replace(
                "__RE_UP_X__",
                if (TextUtils.isEmpty(entity.clickViewUpX)) "-999" else entity.clickViewUpX
                    ?: "-999"
            )
            .replace(
                "__RE_UP_Y__",
                if (TextUtils.isEmpty(entity.clickViewUpY)) "-999" else entity.clickViewUpY
                    ?: "-999"
            )

            .replace(
                "__DOWN_X__",
                if (TextUtils.isEmpty(entity.clickDownX)) "-999" else entity.clickDownX
                    ?: "-999"
            )
            .replace(
                "__DOWN_Y__",
                if (TextUtils.isEmpty(entity.clickDownY)) "-999" else entity.clickDownY
                    ?: "-999"
            )

            .replace(
                "__UP_X__", if (TextUtils.isEmpty(entity.clickUpX)) "-999" else entity.clickUpX
                    ?: "-999"
            )
            .replace(
                "__UP_Y__", if (TextUtils.isEmpty(entity.clickUpY)) "-999" else entity.clickUpY
                    ?: "-999"
            )

            .replace(
                "__LAT__", "-999"
                    ?: "-999"
            )
            .replace(
                "__LON__", "-999"
                    ?: "-999"
            )

            .replace(
                "__SLOT_HEIGHT__",
                if (TextUtils.isEmpty(entity.ad_height)) "-999" else entity.ad_height
                    ?: "-999"
            )
            .replace("__UTC_TS__", System.currentTimeMillis().toString())
            .replace(
                "__CLICK_ID__", if (TextUtils.isEmpty(entity.clickId)) "-999" else entity.clickId
                    ?: "-999"
            )

        return data
    }

    fun replaceUrl(url: String, entity: VideoEntity): String {

        var data: String = url
            .replace(
                "__SLOT_WIDTH__",
                if (TextUtils.isEmpty(entity.ad_width)) "-999" else entity.ad_width
                    ?: "-999"
            )
            .replace(
                "__SLOT_HEIGHT__",
                if (TextUtils.isEmpty(entity.ad_width)) "-999" else entity.ad_width
                    ?: "-999"
            )

            .replace(
                "__RE_DOWN_X__",
                if (TextUtils.isEmpty(entity.clickViewDownX)) "-999" else entity.clickViewDownX
                    ?: "-999"
            )
            .replace(
                "__RE_DOWN_Y__",
                if (TextUtils.isEmpty(entity.clickViewDownY)) "-999" else entity.clickViewDownY
                    ?: "-999"
            )

            .replace(
                "__RE_UP_X__",
                if (TextUtils.isEmpty(entity.clickViewUpX)) "-999" else entity.clickViewUpX
                    ?: "-999"
            )
            .replace(
                "__RE_UP_Y__",
                if (TextUtils.isEmpty(entity.clickViewUpY)) "-999" else entity.clickViewUpY
                    ?: "-999"
            )

            .replace(
                "__DOWN_X__",
                if (TextUtils.isEmpty(entity.clickDownX)) "-999" else entity.clickDownX
                    ?: "-999"
            )
            .replace(
                "__DOWN_Y__",
                if (TextUtils.isEmpty(entity.clickDownY)) "-999" else entity.clickDownY
                    ?: "-999"
            )

            .replace(
                "__UP_X__", if (TextUtils.isEmpty(entity.clickUpX)) "-999" else entity.clickUpX
                    ?: "-999"
            )
            .replace(
                "__UP_Y__", if (TextUtils.isEmpty(entity.clickUpY)) "-999" else entity.clickUpY
                    ?: "-999"
            )

            .replace(
                "__LAT__", "-999"
                    ?: "-999"
            )
            .replace(
                "__LON__", "-999"
                    ?: "-999"
            )

            .replace(
                "__SLOT_HEIGHT__",
                if (TextUtils.isEmpty(entity.ad_height)) "-999" else entity.ad_height
                    ?: "-999"
            )
            .replace("__UTC_TS__", System.currentTimeMillis().toString())
            .replace(
                "__CLICK_ID__", if (TextUtils.isEmpty(entity.clickId)) "-999" else entity.clickId
                    ?: "-999"
            )

        return data
    }

    fun scheduleStartPostponedTransition(sharedElement: View?, activity: Activity) {
        sharedElement?.viewTreeObserver?.addOnPreDrawListener(object :
            ViewTreeObserver.OnPreDrawListener {
            override fun onPreDraw(): Boolean {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    activity.startPostponedEnterTransition()
                }
                sharedElement?.viewTreeObserver.removeOnPreDrawListener(this)
                return true
            }
        })
    }


}