import { useRtcStore } from '/@/store/modules/rtc';
import consola from 'consola';
import type { ConsolaLogObject } from 'consola';
import { handleActions, handleSync, handleReceivePaint, handleJoin } from './controls';

// 所有socket业务事件集中点

export function initSocketEvent(socket: SocketIOClient.Socket): void {
  if (socket) {
    socket.on('connect', () => {
      const rtcStore = useRtcStore();
      const params = {
        userId: rtcStore.userId,
        roomId: rtcStore.roomId,
        role: rtcStore.role || 'leader',
        avatar: rtcStore.avatar,
        nickname: rtcStore.nickname,
      };
      socket.emit('join', params);
      rtcStore.setIsJoined(true);
    });

    socket.on('action', (data: any) => {
      const actionLog: ConsolaLogObject = {
        message: data,
        tag: `action-${data.type || ''}`,
        level: 3,
      };
      consola.info(actionLog);
      handleActions(data);
    });
    // 自已进入逻辑
    socket.on('join', handleJoin);
    // 同屏帶看
    socket.on('sync', handleSync);
    // 畫筆
    socket.on('paint', handleReceivePaint);

    socket.on('onAny', (event: any) => {
      console.error('onAny:-->', event);
    });
    socket.on('error', (error: any) => {
      const actionLog: ConsolaLogObject = {
        message: error,
        tag: 'socket',
        level: 0,
      };
      consola.error(actionLog);
    });
  } else {
    throw new Error('socket没有初始化！');
  }
}
