package com.xhly.manageapp.service.websocket

import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.os.Build
import android.widget.Toast
import com.xhly.corelib.Const
import com.xhly.corelib.bean.AppInfo
import com.xhly.corelib.eventbus.UIEvent
import com.xhly.corelib.network.RetrofitService
import com.xhly.corelib.utils.AppUtils
import com.xhly.corelib.utils.GsonUtils
import com.xhly.corelib.utils.LogShow
import com.xhly.corelib.utils.MD5Utils
import com.xhly.corelib.utils.SharedPreferencesUtils
import com.xhly.manageapp.ManageApplication
import com.xhly.manageapp.bean.EventLog
import com.xhly.manageapp.bean.log.LogAppStartBean
import com.xhly.manageapp.bean.log.LogdOperateBean
import com.xhly.manageapp.network.LogService
import com.xhly.websocket.bean.WebSocketData
import com.xhly.websocket.service.LongConnService
import com.xhly.websocket.service.WebSocketHelper
import com.xhly.websocket.utils.SocketPushUtils.dealPushMessage
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.util.UUID

open class AppSocketService : LongConnService() {
    var CHANNEL_ID = "1"
    var CHANNEL_NAME = "通知"
    var logService = RetrofitService.create<LogService>()
    private val serviceScope = CoroutineScope(MainScope().coroutineContext)
    private var appList = arrayListOf<AppInfo>()

    /*  private var csdkManager: CSDKManager? = null*/
    val spUtils by lazy { SharedPreferencesUtils.getInstance(this) }

    companion object {
        //标记上次打开的包名，当连续打开同一包名时，不认为打开多次
        var lastPkgName = ""
        fun openWebSocket(context: Context) {
            LogShow("打开广播")
            context.startService(Intent(context, AppSocketService::class.java))
        }

        fun closeWebSocket(context: Context) {
            context.stopService(Intent(context, AppSocketService::class.java))
        }
    }

    override fun onCreate() {
        super.onCreate()
        EventBus.getDefault().register(this)
        connectUrl = Const.WSURL
        /*   csdkManager = CSDKManager(this)*/
        /* startNotification()*/
        LogShow("已经创建")
        appList = AppUtils.GetAppList(this) as ArrayList<AppInfo>
    }


    override fun processTextMessage(text: String) {
        //Log.v("websocket收到的消息", text);
        dealPushMessage(text)
    }

    override fun onConnectedSuccess() {
        super.onConnectedSuccess()
        UIEvent(Const.UPDATE_CONNECTED_SUCCESS).post()
        val webData = WebSocketData()
        webData.code = 1002
        webData.mid = UUID.randomUUID().toString()
        val currentTimeSeconds = System.currentTimeMillis() / 1000
        webData.timeunix = currentTimeSeconds
        webData.fid = 1
        val jsMD5 =
            MD5Utils.getJsMD5(webData.code.toString() + "_" + webData.mid + "_" + webData.timeunix.toString())
        webData.sign = MD5Utils.getJsMD5(jsMD5)
        WebSocketHelper.getInstance().sendSocketString(GsonUtils.parseClassToJson(webData))
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onUiEvent(uiEvent: UIEvent) {
        /* if (csdkManager == null) {
             csdkManager = CSDKManager(this)
         }*/
        when (uiEvent.event) {
            Const.CODE2001.toString() -> {
                Toast.makeText(this, "这就是新消息", Toast.LENGTH_LONG).show()
            }

            Const.CODE2002.toString() -> {
                Toast.makeText(this, "限制使用", Toast.LENGTH_LONG).show()
                spUtils.setParam(Const.DISABLEAPP, true)
                goMainActivity()
            }

            Const.CODE2005.toString() -> {
                //csdkManager?.rebootDevice()
            }

            Const.CODE2006.toString() -> {
                //csdkManager?.launchFactoryReset()
            }

            Const.LOGAPPSTART -> {
                val message = uiEvent.message
                if (lastPkgName == message) {
                    return
                }
                val filter = appList.filter { it.packageName == message }
                if (filter.isNotEmpty()) {
                    val appInfo = filter[0]
                    lastPkgName = message
                    serviceScope.launch {
                        val logStartBean = LogAppStartBean()
                        ManageApplication.getDeviceInfo()?.let {
                            logStartBean.sn = it
                        }
                        logStartBean.appName = appInfo.name
                        logStartBean.appPackage = appInfo.packageName
                        logStartBean.versionName = appInfo.versionName
                        logStartBean.versionNum = appInfo.versionNum
                        LogShow("当前应用" + logStartBean.appName + "|||" + logStartBean.versionName + "|||" + logStartBean.versionNum)
                        logService.postLogAppStartAdd(logStartBean)
                    }
                    val data = LogdOperateBean()
                    ManageApplication.getDeviceInfo()?.let {
                        data.sn = it
                    }
                    data.appPackage=message
                    data.doEvent = EventLog.STARTAPPEVENT
                    eventLog(data)
                }
            }

            Const.APPINSTALL -> {
                val message = uiEvent.message
                val data = LogdOperateBean()
                ManageApplication.getDeviceInfo()?.let {
                    data.sn = it
                }
                data.appPackage=message
                data.comm="应用安装"
                data.doEvent = EventLog.APPINSTALLEVENT
                eventLog(data)
            }

            Const.APPUNINSTALL -> {
                val message = uiEvent.message
                val data = LogdOperateBean()
                ManageApplication.getDeviceInfo()?.let {
                    data.sn = it
                }
                data.appPackage=message
                data.comm="应用卸载"
                data.doEvent = EventLog.APPUNINSTALLEVENT
                eventLog(data)
            }

            "10086" -> {
                serviceScope.launch {
                    logService.postLogdoperateAdd(LogdOperateBean())
                }
                Toast.makeText(this, "违规操作，安装未知应用", Toast.LENGTH_LONG).show()
                goMainActivity()
            }
        }
    }

    private fun goMainActivity() {
        try {
            // 为应用程序的启动Activity 准备Intent
            val launchIntent = Intent()
            launchIntent.setComponent(
                ComponentName(
                    "com.xhly.manageapp",
                    "com.xhly.manageapp.ui.MainActivity"
                )
            )
            launchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            startActivity(launchIntent)
        } catch (e: Exception) {
            LogShow("跳转失败$e")
        }
    }

    //用来发送事件日志
    private fun eventLog(operateBean: LogdOperateBean) {
        serviceScope.launch {
            logService.postLogdoperateAdd(operateBean)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
        serviceScope.cancel()
        /* stopForeground(Service.STOP_FOREGROUND_REMOVE)*/
        val intent = Intent()
        intent.setPackage("com.xhly.manageapp")
        intent.setAction("test")
        sendBroadcast(intent)
        LogShow("已经销毁")
    }

    private fun startNotification() {
        var channel: NotificationChannel? = null
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            channel =
                NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH)
            val manager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
            manager.createNotificationChannel(channel)
            val notification = Notification.Builder(
                applicationContext, CHANNEL_ID
            ).build()
            startForeground(1, notification)
        }
    }
}
