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.billbook.lib.downloader.Download
import com.billbook.lib.downloader.Downloader
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.log.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.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.io.File
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
        /* startNotification()*/
        LogShow("已经创建")
        appList = AppUtils.GetAppList(this) as ArrayList<AppInfo>
        //downLoadFile("")
    }

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


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


    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("Service被销毁")
    }

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

}
