package com.xhly.manageapp.service.websocket

import android.content.Context
import com.xhly.corelib.Const
import com.xhly.corelib.eventbus.UIEvent
import com.xhly.corelib.utils.GsonUtils
import com.xhly.corelib.utils.LogShow
import com.xhly.corelib.utils.MD5Utils
import com.xhly.manageapp.ManageApplication
import com.xhly.websocket.bean.WebSocketData
import com.xhly.websocket.bean.WebSocketUserBean
import com.xhly.websocket.service.SocketClient
import com.xhly.websocket.service.WebSocketHelper
import com.xhly.websocket.utils.SocketPushUtils
import java.util.UUID

object AppSocket : SocketClient() {

    override fun startSocket(context: Context?) {
        connectUrl = Const.WSURL
        LogShow("已经创建")
        super.startSocket(context)
    }

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

    override fun onConnectedSuccess() {
        super.onConnectedSuccess()
        UIEvent(Const.UPDATE_CONNECTED_SUCCESS).post()
        val webData = WebSocketData()
        webData.code = 1001
        webData.mid = UUID.randomUUID().toString()
        val currentTimeSeconds = System.currentTimeMillis() / 1000
        webData.timeunix = currentTimeSeconds
        webData.fid = ManageApplication.getDeviceInfo()
        val jsMD5 =
            MD5Utils.getJsMD5(webData.code.toString() + "_" + webData.mid + "_" + webData.timeunix.toString())
        webData.sign = MD5Utils.getJsMD5(jsMD5)
        val socketUserBean = WebSocketUserBean()
        socketUserBean.usertype = 2
        socketUserBean.username = Const.USERNAME
        socketUserBean.userid = ManageApplication.getDeviceInfo()
        socketUserBean.schoolid=Const.SCHOOLID
        webData.body = socketUserBean
        WebSocketHelper.getInstance().sendSocketString(GsonUtils.parseClassToJson(webData))
    }



    override fun onDestroy() {
        super.onDestroy()
        LogShow("Socket被销毁")
    }
}