package com.zxhl.cms.utils

import android.annotation.SuppressLint
import android.app.Activity
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.os.Bundle
import android.provider.Settings
import android.telephony.TelephonyManager
import android.text.TextUtils
import android.view.View
import android.view.ViewTreeObserver
import android.widget.Toast
import com.ayl.ces.jni.CesCore
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.zxhl.cms.ad.upload.Utils.MapKeyComparator
import com.zxhl.cms.ad.upload.model.NewsEntity
import com.zxhl.cms.ad.upload.model.ReportAd
import com.zxhl.cms.common.Constant
import com.zxhl.cms.net.SettingPreference
import okhttp3.HttpUrl
import okhttp3.Request
import org.json.JSONObject
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 {
        return Settings.Secure.getString(context.contentResolver, Settings.Secure.ANDROID_ID)
                ?: ""
    }


    /**
     * 获取当前的运营商
     *
     * @param context
     * @return 运营商名字
     */
    @SuppressLint("MissingPermission", "HardwareIds")
    fun getOperator(context: Context): String {
//        try {
//            var ProvidersName = ""
//            val telephonyManager = context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
//            val IMSI: String? = telephonyManager.subscriberId
//
//            LogUtils.i("qweqwes", "运营商代码" + IMSI)
//            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卡信息";
//            }
//        } catch (e: java.lang.Exception) {
////                Toast.makeText(context, "请开启读取手机权限", Toast.LENGTH_SHORT).show()
            return "0"
//        }

    }

    /**
     * @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版本码
     *
     * @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 ""
    }


    @SuppressLint("MissingPermission")
    fun getImei(context: Context): String {
        try {
            val telephonyManager: TelephonyManager? = context?.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager?
            return telephonyManager?.deviceId?:""
        } catch (e: Exception) {
//            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 ""
        }

    }

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


    fun ListToJson(list: List<ReportAd>): String {
        return Gson().toJson(list)
    }

    fun getAdImpressionList(value: String): List<ReportAd> {
        return Gson().fromJson(value, object : TypeToken<List<ReportAd>>() {}.type)
    }

    fun getAdClickJson(reportAd: ReportAd): String {
        return Gson().toJson(reportAd)
    }

//    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__", if (TextUtils.isEmpty(Constant.Param.lat)) "-999" else Constant.Param.lat
//                        ?: "-999")
//                .replace("__LON__", if (TextUtils.isEmpty(Constant.Param.lon)) "-999" else Constant.Param.lon
//                        ?: "-999")
//
//                .replace("__SLOT_HEIGHT__", if (TextUtils.isEmpty(entity.ad_width)) "-999" else entity.ad_width
//                        ?: "-999")
//                .replace("__UTC_TS__", System.currentTimeMillis().toString())
//                .replace("__CLICK_ID__", if (TextUtils.isEmpty(entity.clickId)) "-999" else entity.clickId
//                        ?: "-999")
//
//        return data
//    }

    @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: SecurityException) {
            return ""
//        }

    }

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

    fun getDeviceToken(context: Context): String {
        var token = ""
        val cr = context.contentResolver
        try {
            val uri = Uri.parse("content://com.miui.analytics.server.AnalyticsProvider")
            val client = cr.acquireContentProviderClient(uri)
            val res = client?.call(METHOD_GET_DEVICE_VALIDATION_TOKEN, "", Bundle())
            val json = res?.getString(RESULT_DEVICE_VALIDATION_TOKEN_JSON)

            val jsonObject = JSONObject(json)
            token = jsonObject.getString(KEY_DEVICE_VALIDATION_TOKEN)
        } catch (e: Exception) {
            // log exception
        }

        return token
    }

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

    fun addParam(request: Request, builder: HttpUrl.Builder) {
        val params = addCommonParam()
        params.put("appLs", Constant.Param.APPLS)
        for (i in 0 until request.url.querySize) {
            val url = request.url
            params.put(url.queryParameterName(i), url.queryParameterValue(i).toString())
        }
        for (i in 0 until request.url.querySize) {
            val url = request.url
            builder.removeAllQueryParameters(url.queryParameterName(i))
        }

        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) + Constant.b).substring(0, 16)
        builder.addQueryParameter("sign", string)

        params.clear()
    }

    fun addCommonParam(): HashMap<String, String> {
        val params = HashMap<String, String>()
        val ts = System.currentTimeMillis().toString()
        params.put(Constant.Device.ts, ts)
        params.put(Constant.Device.uid, SettingPreference.getUid())
        params.put(Constant.Device.token, SettingPreference.getUserToken())
        params.put(Constant.Device.pkg, Constant.Param.mPacketName)
        params.put(Constant.Device.aid, SettingPreference.getAndroidId())
        params.put(Constant.Device.imei, SettingPreference.getImei())
        params.put(Constant.Device.device, SettingPreference.getDevice())
        params.put(Constant.Device.mac, SettingPreference.getMac())
        params.put(Constant.Device.platform, "android")

        params.put(Constant.Device.w, SettingPreference.getW())
        params.put(Constant.Device.vendor, Build.MANUFACTURER)
        params.put(Constant.Device.h, SettingPreference.getH())
        params.put(Constant.Device.oaid, SettingPreference.getOaid())
        params.put(Constant.Device.imsi, SettingPreference.getImsi())
        params.put(Constant.Device.model, SettingPreference.getModel())
        params.put(Constant.Device.vn, SettingPreference.getVN())
        params.put(Constant.Device.ntt, SettingPreference.getNTT())
        params.put(Constant.Device.vc, SettingPreference.getVC())
        params.put(Constant.Device.source, SettingPreference.getSource())
        params.put(Constant.Device.ua, SettingPreference.getUA())
        params.put(Constant.Device.svn, SettingPreference.getSVN())
        params.put(Constant.Device.flowTag, SettingPreference.getFlowTag())
        params.put("lang", "en_us")
        if (!TextUtils.isEmpty(SettingPreference.getUserAgent())) {
            params.put("web-user-agent", SettingPreference.getUserAgent())
        }
        params.put("device_uuid", SettingPreference.getUUid())
//
        params.put(Constant.Device.carrier, SettingPreference.getCarrier())
//        params.put(Constant.Device.ip, SettingPreference.getIp())
        return params
    }


    fun addHeader(builder: Request.Builder) {
        builder.addHeader(Constant.h, Constant.Param.h)
        builder.addHeader(Constant.w, Constant.Param.w)
        builder.addHeader(Constant.model, Constant.Param.model)
        builder.addHeader(Constant.vendor, Constant.Param.vendor)
        builder.addHeader(Constant.svn, Constant.Param.svn)
        builder.addHeader(Constant.ntt, Constant.Param.ntt)
        builder.addHeader(Constant.token, Constant.Param.token)
        builder.addHeader(Constant.vc, Constant.Param.vc)
        builder.addHeader(Constant.vn, Constant.Param.vn)
        builder.addHeader(Constant.aid, Constant.Param.androidId)
        builder.addHeader(Constant.device, SettingPreference.getDevice())
        builder.addHeader(Constant.carrier, Constant.Param.carrier)
        builder.addHeader(Constant.demd5, Constant.Param.md5)
        builder.addHeader(Constant.mac, Constant.Param.mac)
        builder.addHeader(Constant.source, Constant.Param.source)
        builder.addHeader(Constant.imei, Constant.Param.imei)
        builder.addHeader(Constant.platform, "android")
        builder.addHeader(Constant.env, Constant.Param.env)
        builder.addHeader(Constant.cv, Constant.Param.cv)
        builder.addHeader(Constant.lat, Constant.Param.lat)
        builder.addHeader(Constant.lon, Constant.Param.lon)
        builder.addHeader(Constant.imsi, Constant.Param.imsi)
        builder.addHeader(Constant.locationtype, Constant.Param.locationType)
//        builder.addHeader(Constant.city, URLEncoder.encode(Constant.Param.city, "utf-8"))
        builder.addHeader(Constant.ssid, Constant.Param.ssid)
        builder.addHeader(Constant.mitoken, Constant.Param.miToken)
        builder.addHeader(Constant.pkg, Constant.Param.mPacketName)
        builder.addHeader(Constant.ua, Constant.Param.userAgent)
        builder.addHeader(Constant.flowTag, Constant.Param.flowTag)

        if (!TextUtils.isEmpty(Constant.Param.userAgent)) {
            builder.addHeader("web-user-agent", Constant.Param.userAgent)
            builder.removeHeader("User-Agent")
            builder.addHeader("User-Agent", Constant.Param.userAgent)
        }
        if (!TextUtils.isEmpty(Constant.Param.uid)) {
            builder.addHeader("uid", Constant.Param.uid)
        }
    }


    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
    }


}