import { useWebSocket } from '@vueuse/core'
import { user } from '@/store'
import { ref } from 'vue'
import type { UseWebSocketReturn } from '@vueuse/core'

let SOCKET: UseWebSocketReturn<any>
export const useSocket = () => {
  const { token, userInfo } = user()
  const inspectorMessage = ref<any>()
  const inspectorDesktopMessage = ref([])
  const desktopPath = ref<string>()
  enum SOCKET_MSG_TYPE {
    lockScreen = 'lockScreen',
    unLockScreen = 'unLockScreen',
    desktopPreview = 'desktopPreview',
    inspectorTalkMessage = 'inspectorTalkMessage',
    desktopScreenshotImage = 'desktopScreenshotImage',
  }
  function init() {
    SOCKET = useWebSocket(
      `${process.env.VITE_WS_URL}?accessToken=${token.replace('Bearer ', '')}`,
      {
        autoReconnect: {
          retries: 5,
          delay: 3000,
          onFailed() {
            console.log('重新连接失败')
          },
        },
        heartbeat: {
          message: '{"type":"ping"}',
          interval: 5000,
          pongTimeout: 3000,
        },
        onConnected,
        onDisconnected,
        onError,
        onMessage,
      },
    )
    sendMsg({
      type: 'ping',
    })
  }

  function onConnected(ws: WebSocket) {
    // ws.binaryType = 'arraybuffer';
    console.log('ws已连接')
  }
  function onDisconnected() {
    console.log('ws已关闭')
  }
  function onError(ws: WebSocket, event: Event) {
    // console.log(event);
  }

  function onMessage(ws: WebSocket, event: MessageEvent) {
    const data = JSON.parse(event.data)
    console.log(data)
    switch (data.type) {
      // case SOCKET_MSG_TYPE.lockScreen:
      //   // 执行锁屏
      //   useLog(LogType.LockScreenTime, {
      //     simSerialNumber: SN,
      //     lockFlag: 1,
      //   });
      //   break;
      // case SOCKET_MSG_TYPE.unLockScreen:
      //   // 执行解锁
      //   useLog(LogType.LockScreenTime, {
      //     simSerialNumber: SN,
      //     lockFlag: 0,
      //   });
      //   break;
      case SOCKET_MSG_TYPE.desktopPreview:
        onDesktopPreview()
        break
      case SOCKET_MSG_TYPE.inspectorTalkMessage:
        inspectorMessage.value = data.msg
        break
      case SOCKET_MSG_TYPE.desktopScreenshotImage:
        inspectorDesktopMessage.value = data
        break
    }
  }
  // 桌面预览
  async function onDesktopPreview() {
    // const { data: res } = await uploadFile({});
    // sendMsg({
    //     type: 'desktopScreenshotImage',
    //     userId: userInfo.userId,
    //     simSerialNumber: SN,
    //     msg: '',
    // });
    // SOCKET.send(
    //     JSON.stringify({
    //         type: 'desktopScreenshotImage',
    //         userId: userInfo.userId,
    //         simSerialNumber: SN,
    //         msg: ''
    //     }),
    // );
  }
  // 发送消息
  function sendMsg(data: any, config = {}) {
    if (!SOCKET) {
      console.error('ws不存在')
      return
    }
    inspectorDesktopMessage.value = []
    SOCKET.send(JSON.stringify(data))
  }

  function textToBuffer(str: string) {
    return new TextEncoder().encode(str)
  }

  function bufferToText(buffer: ArrayBuffer) {
    return new TextDecoder().decode(buffer)
  }
  return {
    init,
    sendMsg,
    inspectorMessage,
    inspectorDesktopMessage,
  }
}
