import { unref } from 'vue';
import { useRtcStore } from '/@/store/modules/rtc';
import consola from 'consola';
import type { ConsolaLogObject } from 'consola';
import { handleActions, handleSync, handleReceivePaint, handleJoin } from './controls';
import type { SocketParams } from '/@/store/modules/rtc';
import Dialog from '/@/components/basic/dialog';
import { roomId, useRoom } from '/@/hooks/useRoom';
import { useI18n } from '/@/hooks/useI18n';
import dayjs from 'dayjs';
import {
  handleTimeOutError,
  handleEarlyError,
  handleError,
  handleMaxRoomsError,
} from '../chatRoom/controls/actions';
// 所有socket业务事件集中点

export function initSocketEvent(socket: SocketIOClient.Socket): void {
  if (socket) {
    socket.on('connect', () => {
      const rtcStore = useRtcStore();
      const params: SocketParams = {
        userId: rtcStore.userId,
        roomId: rtcStore.roomId,
        role: rtcStore.role || 'leader',
        avatar: rtcStore.avatar || '',
        nickname: rtcStore.nickname,
        isClient: false,
      };
      const { room } = useRoom();
      const useEndTime = unref(room)?.useEndTime || '';
      const useStartTime = unref(room)?.useStartTime;
      const limit = unref(room)?.maxMan || 10;
      const now = dayjs();
      const roomEnd = dayjs(useEndTime);
      const ttl = roomEnd.diff(now, 'second');

      if (useStartTime) {
        const unstartTTl = dayjs(useStartTime).diff(now, 'second');
        if (unstartTTl > 0) {
          console.log('提前！！', dayjs(useStartTime));
          handleEarlyError();
          return;
        }
      }

      if (unref(room)) {
        if (rtcStore.role === 'leader') {
          console.log('unref(room)', unref(room));
          if (useEndTime) {
            params.roomConfig = {
              masterId: rtcStore.userId,
              limit: limit,
              ttl: ttl,
            };
          } else {
            params.roomConfig = {
              masterId: rtcStore.userId,
              limit: limit,
            };
          }
        }
        if (ttl > 0) {
          socket.emit('join', params);
        } else {
          //超时房间
          handleTimeOutError();
        }
      } else {
        //临时房间放行
        if (roomId.indexOf('temp_') > -1) {
          if (rtcStore.role === 'leader') {
            params.roomConfig = {
              masterId: rtcStore.userId,
              limit: limit,
            };
          }
          socket.emit('join', params);
          return;
        }
        handleTimeOutError();
      }
    });

    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('manager-error', ({ type, code }) => {
      const { t } = useI18n();
      switch (type) {
        case 'repeat-login':
          Dialog.toast({ content: t('action.errorRepeatLogin') });
          handleMaxRoomsError();
          break;
        case 'room-maxing':
          Dialog.toast({ content: t('action.errorRoomMaxing') });
          handleMaxRoomsError();
          break;
        case 'invalid-master':
          Dialog.toast({ content: t('action.errorInvalidMaster') });
          handleError();
          break;
        case 'invalid-match-role':
          Dialog.toast({ content: t('base.errorRoom') });
          handleError();
          break;
        case 'invalid-room-params':
          Dialog.toast({ content: t('base.errorRoom') });
          handleError();
          break;
        case 'ttl-out':
          handleError();
          break;
        default:
          Dialog.toast({ content: `错误代码：${code}，类型：${type}` });
          break;
      }
    });
    socket.on('error', (error: any) => {
      const actionLog: ConsolaLogObject = {
        message: error,
        tag: 'socket',
        level: 0,
      };
      consola.error(actionLog);
    });
  } else {
    throw new Error('socket没有初始化！');
  }
}
