import { useRtcStore } from '/@/store/modules/rtc';
import type { ChatContentType, UserInfoType } from '/@/store/modules/rtc';
import Dialog from '/@/components/basic/dialog';
import { useApp } from '/@/hooks/userApp';
import consola from 'consola';
import { useSocket } from '/@/hooks/userSocket';
import { useRoom, SceneItemType } from '/@/hooks/useRoom';
import { useI18n } from '/@/hooks/useI18n';
import browser from '/@/utils/browser';
import { unref } from 'vue';
import { useAppStore } from '/@/store/modules/app';
import dayjs from 'dayjs';
import duration from 'dayjs/plugin/duration';
import { useRtcSdk } from '/@/hooks/useTRTC';
import { useMiniApp } from '/@/hooks/useMiniApp';
dayjs.extend(duration);
const { isUsingMiniApp } = useMiniApp();
// import { useRtcSdk } from '/@/hooks/useTRTC';
interface ActionDataType {
  type: string;
  data: any;
  members?: UserInfoType[];
  open?: boolean;
  user?: UserInfoType;
  userId?: string;
  words?: boolean;
  muted?: boolean;
}
interface sceneAnswerType {
  scene?: string;
  pose?: string;
}

export function handleActions({
  data,
  type,
  members,
  open,
  user,
  userId,
  words,
  muted,
}: ActionDataType) {
  switch (type) {
    case 'user-init':
      handleUserInit();
      break;
    case 'danmumsg':
      handleDanMumSg(data);
      break;

    case 'changeScene':
      handleChangeScene(data);
      break;

    case 'user-join':
      handleUserJoin(members, user);
      break;
    case 'user-leave':
      handleUserLeave(user, members);
      break;
    case 'user-exit':
      handleUserExit(user, members);
      break;

    case 'users-muted':
      handleUserMuted(userId, muted);
      break;

    case 'users-words':
      handleUserSetWords(userId, words, members);
      break;
    case 'leader-dismiss':
      handleLeaderDismiss();
      break;
    case 'user-paint':
      handleUserPaint(open);
      break;
    case 'tagclick':
      break;
    case 'tagclose':
      break;
    case 'tag-image-index':
      handleTagImageIndex(data);
      break;
    case 'ask-currentscene':
      handleAskCurrentscene();
      break;
    case 'answer-currentscene':
      console.log('handleAnswerCurrentscene', data);
      handleAnswerCurrentscene(data as sceneAnswerType);
      break;
    case 'error':
      // Dialog.toast({ content: `房间未找到`, type: 'error' });
      handleError();

    case 'sync-floor':
      handleSyncFloor(data);

    case 'room-valid-time':
      handleRoomValidTime(data);
    case 'rooms-status': // 新加房间全员动态
      console.log('data', members);
      const membersStatus = members as any as UserInfoType[];
      handleRoomStatus(membersStatus);
    default:
      break;
    case 'user-be-kicked':
      const { t } = useI18n();
      Dialog.toast({ content: t('action.endUpRoom') });
      handleMaxRoomsError();
      break;
  }
  if (members?.length) {
    console.log('服务器的', members);
  }
}

//被动处理初始化
async function handleUserInit() {
  const rtcStore = useRtcStore();
  if (rtcStore.role === 'leader') {
    const app = await useApp();
    setTimeout(() => {
      app.Connect.follow.sync();
    }, 300);

    // setTimeout(() => {
    //     socket.value.emit("action", {
    //       type: "leader-avatar",
    //       data: { avatar: leaderAvatar.value },
    //     });
    //     if (tagclick.value && tagclick.value.type == "goodlist") {
    //       socket.value.emit("action", {
    //         type: "tagclick",
    //         data: {
    //           sid: tagclick.value.data.sid,
    //         },
    //       });
    //       if (tagImageIndex.value != null) {
    //         setTimeout(() => {
    //           socket.value.emit("action", {
    //             type: "tag-image-index",
    //             data: {
    //               index: tagImageIndex.value,
    //             },
    //           });
    //         }, 200);
    //       }
    //     }
    //   }, 200);
  }
}

// 被动处理弹幕
function handleDanMumSg(data: ChatContentType) {
  const { t } = useI18n();
  const rtcStore = useRtcStore();
  if (data.role == 'leader') {
    data.Nickname = t('action.hoster');
  }
  rtcStore.addToChatList(data);
}
// 其他用户进入
function handleUserJoin(members?: UserInfoType[], user?: UserInfoType) {
  const { t } = useI18n();
  consola.info({
    tag: 'socket',
    message: '有人进来了',
  });
  const rtcStore = useRtcStore();
  const appStore = useAppStore();
  members && rtcStore.setMemberList(members);
  const isMaxAlert = rtcStore.memberList.length > Number(import.meta.env.VITE_ROOM_MEMBER);

  if (user && !isMaxAlert) {
    let name = user.Nickname;
    if (user.Role === 'leader') {
      const { socket } = useSocket();
      name = t('action.hoster');
      Dialog.toast({ content: t('action.hosterEnterRoom') });
      socket.emit('action', { type: 'user-init' });
      socket.emit('sync-floor', { floorId: appStore.floorId });
      rtcStore.setHosterOnline(true);
    } else {
      // if (rtcStore.isLeader) {
      //   const { socket } = useSocket();
      //   console.log('进入，主持人禁音', user.UserId);
      //   socket.emit('action', {
      //     type: 'users-muted',
      //     muted: true,
      //     userId: user.UserId,
      //   });
      // }
    }
    const data: ChatContentType = {
      role: user?.Role,
      mode: rtcStore.mode,
      Nickname: name,
      UserId: user?.UserId,
      text: t('action.enterRoom'),
    };

    if (rtcStore.isLeader) {
      console.log('主持人看到', data);
      rtcStore.addToChatList(data);
    } else {
      console.log('参与者看到', data);
      if (user.Role == 'leader') {
        // const { handleJoin } = useRtcSdk();
        rtcStore.addToChatList(data);

        // setTimeout(() => {
        //   console.log('主持人重新进入，参与者重新加入语言');
        //   handleJoin();
        // }, 2000);
      }
    }
  }
}

// 其他用户开起画笔通知

async function handleUserPaint(open: boolean | undefined) {
  const { t } = useI18n();
  const app = await useApp();
  const rtcStore = useRtcStore();
  if (!rtcStore.isLeader) {
    if (open) {
      console.log(open);
      app.Connect.paint.show({
        role: rtcStore.role,
        paint: false,
      });
      Dialog.toast({ content: t('action.hosterOpenDraw') });
    } else {
      Dialog.toast({ content: t('action.hosterCloseDraw') });
      app.Connect.paint.hide();
    }
  }
}

const handleChangeScene = (data: SceneItemType) => {
  const { changeScene } = useRoom();
  console.log('handleChangeScene', data);
  data && changeScene(data);
};
// 由leader回复转场
const handleAskCurrentscene = () => {
  const { socket } = useSocket();
  const rtcStore = useRtcStore();
  if (rtcStore.isLeader) {
    socket.emit('action', {
      type: 'answer-currentscene',
      data: {
        scene: browser.getURLParam('m'),
        pose: browser.getURLParam('pose'),
      },
    });
  }
};

const handleAnswerCurrentscene = (data: sceneAnswerType) => {
  const rtcStore = useRtcStore();
  const { currentScene, changeScene, sceneList } = useRoom();
  if (!rtcStore.isLeader) {
    if (unref(currentScene)?.num !== data.scene) {
      const otherScene = unref(sceneList).find((item) => item.num === data.scene);
      otherScene && changeScene(otherScene);
    }
    // if(unref(currentScene))
    // debugger;
  }
};

const handleTagImageIndex = (data) => {
  console.log('data', data);
};

const handleUserSetWords = (UserId?: string, words?: boolean, members?: UserInfoType[]) => {
  console.log('members', members);
  const { t } = useI18n();
  const rtcStore = useRtcStore();
  console.log('handleUserSetWords', UserId, words);
  UserId &&
    rtcStore.updateMemberDatabyId(UserId, {
      IsWords: words,
    });
  if (UserId == rtcStore.userId) {
    Dialog.toast({
      content: !words ? t('action.hostBanInput') : t('action.hostAllowInput'),
    });
  }
};
const handleUserMuted = (UserId?: string, muted?: boolean) => {
  const rtcStore = useRtcStore();
  UserId &&
    rtcStore.updateMemberDatabyId(UserId, {
      IsMuted: muted,
    });
  if (UserId == rtcStore.userId) {
    rtcStore.setMute(!!muted);

    // console.log('audio::status', UserId, muted);
    setTimeout(() => {
      console.log('被禁人状态-->', UserId, muted);
      const { localStream } = useRtcSdk();
      if (muted) {
        console.log('被禁人状态-->', localStream);
        localStream && localStream.muteAudio();
      } else {
        localStream && localStream.unmuteAudio();
      }
    }, 500);
  }
};

//被动处理用离开
const handleUserLeave = (user?: UserInfoType, members?: UserInfoType[]) => {
  const { t } = useI18n();
  const rtcStore = useRtcStore();
  const isMaxAlert = members && members.length > Number(import.meta.env.VITE_ROOM_MEMBER);
  console.log('有人离开了', user?.UserId, isMaxAlert);
  if (user && !isMaxAlert) {
    let name = user.Nickname;
    if (user.Role == 'leader') {
      name = t('action.hoster');
      Dialog.toast({ content: t('action.hostExitRoom') });
      rtcStore.setHosterOnline(false);
    }
    const data = {
      role: user.Role,
      mode: '',
      Nickname: name,
      UserId: user.UserId,
      text: t('action.leaveRoom'),
    };

    console.log('members', user, members);
    if (rtcStore.isLeader) {
      console.log('主持人看到', data);
      rtcStore.addToChatList(data);
      const { muteVideoLeader } = useRtcSdk();
      muteVideoLeader.value = false;
    } else {
      console.log('参与者看到', data);
      user.Role == 'leader' && rtcStore.addToChatList(data);
    }

    members && rtcStore.setMemberList(members);
  }
};

const handleUserExit = (user?: UserInfoType, members?: UserInfoType[]) => {
  const { t } = useI18n();
  const rtcStore = useRtcStore();
  const isMaxAlert = members && members.length > Number(import.meta.env.VITE_ROOM_MEMBER);
  console.log('有人退出了', user?.UserId, isMaxAlert);
  if (user && !isMaxAlert) {
    let name = user.Nickname;
    if (user.Role == 'leader') {
      name = t('action.hoster');
      Dialog.toast({ content: t('action.hostExitRoom') });
      rtcStore.setHosterOnline(false);
    }
    const data = {
      role: user.Role,
      mode: '',
      Nickname: name,
      UserId: user.UserId,
      text: t('action.exitRoom'),
    };

    if (rtcStore.isLeader) {
      console.log('主持人看到', data);
      rtcStore.addToChatList(data);
      const { muteVideoLeader } = useRtcSdk();
      muteVideoLeader.value = false;
    } else {
      console.log('参与者看到', data);
      user.Role == 'leader' && rtcStore.addToChatList(data);
    }

    members && rtcStore.setMemberList(members);
  }
};
//被动处理用离开 全员解散
const handleLeaderDismiss = () => {
  const { closeSocket, closeRoomForWechat } = useSocket();
  const rtcStore = useRtcStore();
  const { t } = useI18n();
  // Dialog.toast({ content: t('action.hosterDismissRoom') });
  rtcStore.showBaseDialog(
    {
      title: t('base.tips'),
      desc: t('action.hosterDismissRoom'),
      okTxt: t('base.confirm'),
      closeTxt: t('base.cancel'),
      isSingle: true,
    },
    () => {
      if (isUsingMiniApp.value) {
        closeRoomForWechat();
      } else {
        closeSocket();
      }
    },
  );
  setTimeout(() => {
    if (isUsingMiniApp.value) {
      //@ts-ignore
      wx.miniProgram.switchTab({
        url: '/pages/index/index',
      });
    } else {
      closeSocket();
    }
  }, 5000);
};

//

export const handleError = () => {
  const rtcStore = useRtcStore();
  const { t } = useI18n();
  rtcStore.showBaseDialog(
    {
      title: t('base.tips'),
      desc: t('action.endUpRoom'),
      okTxt: t('base.confirm'),
      closeTxt: t('base.cancel'),
      isSingle: true,
    },
    () => {
      const { closeSocket } = useSocket();
      closeSocket();
    },
  );
};
// 满员提示
export const handleMaxRoomsError = () => {
  // const rtcStore = useRtcStore();
  // const { t } = useI18n();
  const { closeSocket, closeRoomForWechat } = useSocket();
  setTimeout(() => {
    if (isUsingMiniApp.value) {
      closeRoomForWechat();
    } else {
      closeSocket();
    }
  }, 3000);
};

export const handleTimeOutError = () => {
  const rtcStore = useRtcStore();

  const { t } = useI18n();
  rtcStore.showBaseDialog(
    {
      title: t('base.tips'),
      desc: t('action.timeOutRoomError'),
      okTxt: t('base.knowIt'),
      closeTxt: t('base.cancel'),
      isSingle: true,
    },
    () => {
      if (isUsingMiniApp.value) {
        //@ts-ignore
        wx.miniProgram.switchTab({
          url: '/pages/index/index',
        });
      } else {
        const { closeSocket } = useSocket();
        closeSocket();
      }
    },
  );
};
export const handleEarlyError = () => {
  const rtcStore = useRtcStore();
  const { t } = useI18n();
  rtcStore.showBaseDialog(
    {
      title: t('base.tips'),
      desc: t('action.earlyRoomError'),
      okTxt: t('base.knowIt'),
      closeTxt: t('base.cancel'),
      isSingle: true,
    },
    () => {
      if (isUsingMiniApp.value) {
        //@ts-ignore
        wx.miniProgram.switchTab({
          url: '/pages/index/index',
        });
      } else {
        const { closeSocket } = useSocket();
        closeSocket();
      }
    },
  );
};

interface FloorType {
  floorId: string;
}
const handleSyncFloor = (data: FloorType) => {
  const rtcStore = useRtcStore();
  const appStore = useAppStore();
  if (!rtcStore.isLeader) {
    console.log('data', data, rtcStore);
    appStore.setFloor(data.floorId);
  }
};
interface RoomValidTimeType {
  ttl: number;
}
const handleRoomValidTime = (data: RoomValidTimeType) => {
  const rtcStore = useRtcStore();
  const appStore = useAppStore();
  const { t } = useI18n();
  appStore.setRoomValidTime(data.ttl);
  if (rtcStore.isLeader) {
    const seconds = data.ttl;
    if (seconds > 3) {
      setTimeout(() => {
        // const time = dayjs.duration(seconds - 1, 'seconds').format('mm:ss');
        // console.log('time', time);
        // const timeString = time == '00:00' ? '60:00' : time;
        // const msg = String(t('base.roomTimeOut')).replace(new RegExp('%time%', 'g'), timeString);
        const chat: ChatContentType = {
          role: 'leader',
          mode: '',
          Nickname: t('base.tips'),
          UserId: rtcStore.userId,
          text: t('base.roomTimeOut'),
        };
        rtcStore.addToChatList(chat);
      }, 500);
    }
  }
};

const handleRoomStatus = (members: UserInfoType[]) => {
  const rtcStore = useRtcStore();
  members && rtcStore.setMemberList(members);
};
