package com.ydl.ydlcommon.utils.actionutil

import android.annotation.SuppressLint
import android.content.Context
import android.net.ConnectivityManager
import android.net.NetworkInfo
import android.net.wifi.WifiManager
import android.os.Build
import com.umeng.commonsdk.UMConfigure
import com.ydl.ydlcommon.base.BaseApp
import com.ydl.ydlcommon.data.http.api.ApiRequestUtil
import com.ydl.ydlcommon.data.http.params.ActionDataBean
import com.ydl.ydlcommon.modular.ModularServiceManager
import com.ydl.ydlcommon.utils.DeviceTool
import com.yidianling.common.tools.LogUtil
import com.yidianling.common.tools.RxDeviceTool
import com.yidianling.common.tools.RxTool
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"
        var appId: String = ""
        var appName: String = ""
        var packageName: String = ""
        var oaId = ""


        /**
         * appId:消息端来源  - ydl:ydl-app-android-user、xlzx:ydl-app-android-xlzx
         * appName:应用名称 - "心理咨询" else "壹点灵心理咨询"
         */

        fun init(id: String, name: String) {
            packageName = BaseApp.instance.packageName
            appId = id
            appName = name
            // 获取oaid
            UMConfigure.getOaid(BaseApp.instance) {
                oaId = it
            }
        }



        /**
         * 埋点构造方法
         */
        fun baiDuCountSign1(partId: String,position: String, sign1: String){
            baiDuCount(partId,position,sign1,"","","","")
        }

        /**
         * 埋点构造方法
         */
        fun baiDuCountSign2(partId: String,position: String, sign1: String,sign2:String){
            baiDuCount(partId,position,sign1,sign2,"","","")
        }

        /**
         * 埋点构造方法
         */
        fun baiDuCountSign3(partId: String,position: String, sign1: String,sign2:String,sign3: String){
            baiDuCount(partId,position,sign1,sign2,sign3,"","")
        }

        /**
         * 埋点构造方法
         */
        fun baiDuCountSign4(partId: String,position: String, sign1: String,sign2:String,sign3: String,sign4: String){
            baiDuCount(partId,position,sign1,sign2,sign3,sign4,"")
        }


        /**
         * 埋点方法
         * @param partId 例如：pardId-ydl_user_error_business
         */

        fun baiDuCount(
            partId: String,
            position: String,
            sign1: String,
            sign2: String,
            sign3: String,
            sign4: String,
            sign5: String
        ) {
            val actionDataParams = ActionDataBean.Builder()
            actionDataParams.partId = partId
            actionDataParams.position = position
            actionDataParams.sign1 = sign1
            actionDataParams.sign2 = sign2
            actionDataParams.sign3 = sign3
            actionDataParams.sign4 = sign4
            actionDataParams.sign5 = sign5
            actionDataParams.appVersion(RxDeviceTool.getAppVersionName(BaseApp.getApp()))
            val deviceId = if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.P) {
                //获取imei
                DeviceTool.getIMEI()
            } else {
                //android Q及以上取oaid
                oaId
            }
            actionDataParams.deviceId = deviceId
            actionDataParams.time(System.currentTimeMillis())
            actionDataParams.appId(appId)
            actionDataParams.manufacturer(Build.BRAND.trim().toUpperCase())
            actionDataParams.model(Build.MODEL)
            actionDataParams.os(BIConstants.OS)
            actionDataParams.osVersion(Build.VERSION.RELEASE)
            actionDataParams.wifi(if (isWifi()) 0 else 1)
            actionDataParams.uid = ModularServiceManager.getPlatformUserService()!!.getUser()?.userId
            //请求
            request(actionDataParams.build())
        }


        /**
         * 传入ActionDataParams参数，访问接口
         */

        @SuppressLint("CheckResult")
        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是否开启
            return if (wifiManager.isWifiEnabled) {
                // 已经开启了WiFi
                val wifiInfo = wifiManager.connectionInfo
                val ipAddress = wifiInfo.ipAddress
                intToIp(ipAddress)
            } else {
                // 未开启WiFi
                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 {
            val en: Enumeration<NetworkInterface> = NetworkInterface.getNetworkInterfaces()

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

                    }
                }
            }
            return "null"
        }


        /**
         * 判断是否是wifi
         */

        private fun isWifi(): Boolean {
            try {
                val connectivityManager: ConnectivityManager =
                    RxTool.getContext()
                        .getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
                val info: NetworkInfo = connectivityManager.activeNetworkInfo
                if (info.type == ConnectivityManager.TYPE_WIFI) {
                    return true
                }
                return false
            } catch (e: Exception) {
                return false
            }

        }
    }
}
