import { useAppStore } from '../store/modules/app';
import { getApp } from './userApp';
import { useRoom } from './useRoom';
import { useRtcStore } from '/@/store/modules/rtc';

const io = (window as any).io as SocketIOClientStatic;
let socket: SocketIOClient.Socket;

interface ReturnUseSocketType {
  createSocket: Fn;
  closeSocket: Fn;
  socket: SocketIOClient.Socket;
  closeRoomForWechat: Fn;
}

export function createSocket() {
  const rtcStore = useRtcStore();
  // console.log('rtcStore', rtcStore)
  const address = import.meta.env.VITE_APP_SOCKET_URL;
  console.log('address', address);
  socket = io(address, {
    path: '/ws-sync',
    transports: ['websocket'],
  });
  rtcStore.setSocket(socket);
  return socket;
}

async function closeSocket() {
  const { leaveRoom, createNewURLEntry } = useRoom();
  const rtcStore = useRtcStore();
  const appStore = useAppStore();
  try {
    await getApp().Connect.follow.exit();
    await leaveRoom();
  } catch (error) {
    console.error('exit-error', error);
  }

  appStore.setIsTourMode(true);
  if (rtcStore.isLeader) {
    socket && socket.emit('action', { type: 'leader-dismiss' });
  }
  console.log('socket', socket);
  socket && socket.emit('disconnected');
  // console.log('socket', socket.connected);
  rtcStore.clearMemberList();
  createNewURLEntry({
    vruserId: '',
    isTour: 1,
    name: '',
    role: '',
    roomId: rtcStore.roomId,
    avatar: '',
  });
  setTimeout(() => {
    location.reload();
  }, 100);
}

async function closeRoomForWechat() {
  const { leaveRoom } = useRoom();
  const rtcStore = useRtcStore();
  // const appStore = useAppStore();
  try {
    await getApp().Connect.follow.exit();
    await leaveRoom();
  } catch (error) {
    console.error('exit-error', error);
  }

  // appStore.setIsTourMode(true);
  if (rtcStore.isLeader) {
    socket && socket.emit('action', { type: 'leader-dismiss' });
  }
  console.log('socket', socket);
  socket && socket.emit('disconnected');

  setTimeout(() => {
    //@ts-ignore
    wx.miniProgram.switchTab({
      url: '/pages/index/index',
    });
  }, 1000);
}

export function useSocket(): ReturnUseSocketType {
  return {
    socket,
    closeSocket,
    createSocket,
    closeRoomForWechat,
  };
}
