package com.yidianling.ydlcommon.custom.utils.actionutil

import android.app.Activity
import android.content.Context
import android.net.ConnectivityManager
import android.net.NetworkInfo
import android.net.wifi.WifiManager
import android.util.Log
import com.google.gson.Gson
import com.yidianling.ydlcommon.core.base.BaseApplication
import com.yidianling.common.tools.LogUtil
import com.yidianling.common.tools.RxDeviceTool
import com.yidianling.common.tools.RxTool
import com.yidianling.ydlcommon.custom.http.api.ApiRequestUtil
import com.yidianling.ydlcommon.custom.http.params.ActionDataBean
import com.yidianling.ydlcommon.custom.http.params.BaiduActionDataBean
import com.yidianling.ydlcommon.custom.router.YdlCommonOut
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import java.net.Inet4Address
import java.net.InetAddress
import java.net.NetworkInterface
import java.net.SocketException
import java.util.*


/**
 * 行为数据埋点工具类
 * Created by xj on 2019/6/22.
 */
class ActionCountUtils {

    companion object {

        const val TAG: String = "ActionCountUtils"

        /**
         * 行为数据埋点调用的方法
         */
        fun count(uid: String?, partId: String, position: String, url: String, api: String, sign1: String) {
            try {
                val actionDataParams = ActionDataBean.Builder()
                actionDataParams.partId(partId)
                actionDataParams.position(position)
                actionDataParams.url(url)

                uid?.let {
                    actionDataParams.uid(uid)
                }
                actionDataParams.time(System.currentTimeMillis())
                actionDataParams.appVersion(RxDeviceTool.getAppVersionName(BaseApplication.getApp()))
                actionDataParams.appId(BIConstants.APP_ID)
                actionDataParams.api(api)
                actionDataParams.manufacturer(android.os.Build.BRAND.trim().toUpperCase())
                actionDataParams.model(android.os.Build.MODEL)
                actionDataParams.os(BIConstants.OS)
                actionDataParams.osVersion(android.os.Build.VERSION.RELEASE)
                actionDataParams.wifi(if (isWifi()) 0 else 1)
                actionDataParams.sign1(sign1)
                actionDataParams.screenWidth(RxDeviceTool.getScreenWidth(RxTool.getContext()!!))
                actionDataParams.screenHeight(RxDeviceTool.getScreenHeight(RxTool.getContext()!!))

                //剩余额外参数根据需求定义

                //请求
                request(actionDataParams.build())

            } catch (e: Exception) {
                LogUtil.i(TAG, e.toString())
            }
        }

        /**
         * 百度检测数据埋点调用的方法
         */
        fun baiduCount(uid : String?,partId: String, position: String, url: String, api: String, activity: Activity, convertType: Int) {
            try {
                val actionDataParams = ActionDataBean.Builder()
                actionDataParams.partId(partId)
                actionDataParams.position(position)
                actionDataParams.url(url)

                actionDataParams.time(System.currentTimeMillis())
                actionDataParams.appVersion(RxDeviceTool.getAppVersionName(BaseApplication.getApp()))
                actionDataParams.appId(BIConstants.APP_ID)
                actionDataParams.api(api)
                actionDataParams.manufacturer(android.os.Build.BRAND.trim().toUpperCase())
                actionDataParams.model(android.os.Build.MODEL)
                actionDataParams.os(BIConstants.OS)
                actionDataParams.osVersion(android.os.Build.VERSION.RELEASE)
                actionDataParams.wifi(if (isWifi()) 0 else 1)
                actionDataParams.screenWidth(RxDeviceTool.getScreenWidth(RxTool.getContext()!!))
                actionDataParams.screenHeight(RxDeviceTool.getScreenHeight(RxTool.getContext()!!))

                val baiduActionDataParams = BaiduActionDataBean.Builder()
                baiduActionDataParams.pkname = "com.cxzapp.yidianling"
                baiduActionDataParams.deviceType = 2
                baiduActionDataParams.deviceId(com.yidianling.ydlcommon.custom.utils.DeviceTool.getIMEI(activity))
                baiduActionDataParams.convertType(convertType)
                baiduActionDataParams.convertTime(System.currentTimeMillis() / 1000)
                baiduActionDataParams.appid(0.toLong())
                baiduActionDataParams.appName("壹点灵心理咨询")
                baiduActionDataParams.androidId(com.yidianling.ydlcommon.custom.utils.DeviceTool.getAndroidID())
                baiduActionDataParams.ip("")
                baiduActionDataParams.ipv6("")
                baiduActionDataParams.tp(android.os.Build.MODEL)
                baiduActionDataParams.network(com.yidianling.ydlcommon.custom.utils.DeviceTool.getNetworkState(RxTool.getContext()))
                baiduActionDataParams.convertParam("")
                baiduActionDataParams.uid(uid)
                baiduActionDataParams.channel(YdlCommonOut.getChannelName())
                val gson = Gson().toJson(baiduActionDataParams)
                Log.e("Action", "---------$gson")
                actionDataParams.sign2(gson)
                actionDataParams.sign3(YdlCommonOut.getChannelName())

                //剩余额外参数根据需求定义

                //请求
                request(actionDataParams.build())

            } catch (e: Exception) {
            }
        }

        /**
         * 传入ActionDataParams参数，访问接口
         */
        fun request(actionDataBean: ActionDataBean) {
            try {
                ApiRequestUtil.actionDataCount(actionDataBean)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe({
                            LogUtil.i(TAG, it.data)
                        }) {
                            LogUtil.i(TAG, it.toString())
                        }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }

        /**
         * 获取当前ipv4地址
         * @return
         */
        fun getIpAddress(context: Context): String {
            // 获取WiFi服务
            val wifiManager = context.getSystemService(Context.WIFI_SERVICE) as WifiManager
            // 判断WiFi是否开启
            if (wifiManager.isWifiEnabled) {
                // 已经开启了WiFi
                val wifiInfo = wifiManager.connectionInfo
                val ipAddress = wifiInfo.ipAddress
                return intToIp(ipAddress)
            } else {
                // 未开启WiFi
                return getIpAddress()
            }
        }

        private fun intToIp(ipAddress: Int): String {
            return (ipAddress and 0xFF).toString() + "." +
                    (ipAddress shr 8 and 0xFF) + "." +
                    (ipAddress shr 16 and 0xFF) + "." +
                    (ipAddress shr 24 and 0xFF)
        }

        private fun getIpAddress(): String {
            try {
                var networkInterface: NetworkInterface
                var inetAddress: InetAddress
                val en = NetworkInterface.getNetworkInterfaces()
                while (en.hasMoreElements()) {
                    networkInterface = en.nextElement()
                    val enumIpAddr = networkInterface.inetAddresses
                    while (enumIpAddr.hasMoreElements()) {
                        inetAddress = enumIpAddr.nextElement()
                        if (!inetAddress.isLoopbackAddress && !inetAddress.isLinkLocalAddress) {
                            return inetAddress.hostAddress
                        }
                    }
                }
                return ""
            } catch (ex: SocketException) {
                ex.printStackTrace()
                return ""
            }

        }

        fun getLocalIPAddress(): String {
            var en: Enumeration<NetworkInterface> = NetworkInterface.getNetworkInterfaces()

            while (en.hasMoreElements()){
                var intf: NetworkInterface = en.nextElement()
                var  enumIpAddr: Enumeration<InetAddress> = intf.inetAddresses
                while (enumIpAddr.hasMoreElements()){
                var inetAddress: InetAddress = enumIpAddr.nextElement()
                if(!inetAddress.isLoopbackAddress && (inetAddress is Inet4Address)){
                return inetAddress.getHostAddress().toString()

            }
            }
            }
            return "null"
        }

        /**
         * 判断是否是wifi
         */
        private fun isWifi(): Boolean {
            try {
                var connectivityManager: ConnectivityManager = RxTool.getContext().getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
                var info: NetworkInfo = connectivityManager.activeNetworkInfo
                if (info != null && info.type == ConnectivityManager.TYPE_WIFI) {
                    return true
                }
                return false
            } catch (e: Exception) {
                return false
            }

        }
    }
}