import consolaGlobalInstance from 'consola';
// import sortBy from 'lodash-es/sortBy';
import { unref } from 'vue';
import { useI18n } from '/@/hooks/useI18n';
// import { unref } from 'vue';
// import Dialog from '/@/components/basic/dialog';
// import { getApp } from '/@/hooks/userApp';
import { useRoom } from '/@/hooks/useRoom';
import { useSocket } from '/@/hooks/userSocket';
import { UserInfoType, useRtcStore } from '/@/store/modules/rtc';
const { enterRoom } = useRoom();

// 自已join的方法
export function handleJoin(data: any) {
  // const app = getApp();
  const { socket, closeSocket } = useSocket();
  const members = data?.members as any as UserInfoType[];
  const user = data?.user as any as UserInfoType;
  const rtcStore = useRtcStore();

  // const userExsit = rtcStore.checkUserInMemberList(rtcStore.userId);
  // banLaterEnterer(members, user);
  enterRoom();
  rtcStore.setIsJoined(true);
  consolaGlobalInstance.info({
    message: data,
    tag: 'socket:enter',
  });

  console.log('lala', user);
  const maxNumber = import.meta.env.VITE_ROOM_MEMBER || 10;
  // console.log('roomMaxNumber', maxNumber);
  console.log('roomMaxNumber', maxNumber, members.length, Number(maxNumber));
  if (members.length > Number(maxNumber)) {
    if (rtcStore.role === 'customer') {
      const { t } = useI18n();
      rtcStore.showBaseDialog(
        {
          title: t('base.tips'),
          desc: t('base.maxRooms'),
          okTxt: t('base.freeWalk'),
          closeTxt: t('base.cancel'),
          isSingle: true,
        },
        () => {
          setTimeout(() => {
            closeSocket();
          }, 1500);
        },
      );
      setTimeout(() => {
        closeSocket();
      }, 3000);
      // Dialog.toast({ content: `房间已满员` });
      // setTimeout(() => {
      //   closeSocket();
      // }, 1500);
      // return;
    }
  } else {
    members && rtcStore.setMemberList(members);
  }

  rtcStore.setConnectStatus(1);

  setTimeout(() => {
    if (!rtcStore.isLeader) {
      socket.emit('action', {
        type: 'user-init',
      });
      socket.emit('action', {
        type: 'ask-currentscene',
      });
    } else {
      const { currentScene } = useRoom();
      console.log('currentScene', unref(currentScene));
      socket.emit('action', {
        type: 'changeScene',
        data: unref(currentScene),
      });
      console.log('进入，主持人禁音-1');
      // socket.emit('action', {
      //   type: 'users-muted',
      //   muted: true,
      //   userId: user.UserId,
      // });
    }
  }, 1500);
}

// const banLaterEnterer = (members: UserInfoType[], user: UserInfoType) => {
//   if (members && user) {
//     console.log('banLaterEnterer', members);
//     const sameIDsArray = members.some((item) => item.UserId === user.UserId);
//     const sortList = sortBy(sameIDsArray, ['InTime'], ['asc']);
//     console.log('banLaterEnterer', sortList);
//     // const beforeUSer =
//   }
// };
