<template>
  <!-- 主区域 start  -->
  <div
    id="PageRtcLive"
    :class="{
      [role]: true,
      showCam: !muteVideoLeader,
      hideCam: muteVideoLeader || !isPanoramaMode,
    }"
  >
    <chat v-show="chatShow && isPanoramaMode" :chatList="chatList" :currentUser="currentUser" />
    <!-- 当前人数 start -->
    <div class="member_number" v-if="isPanoramaMode">
      <div class="members"></div>
      <span>{{ members.length }}{{ t('base.view') }}</span>
      <span v-if="isPanoramaMode && roomCounter > 0 && isNativeLeader"
        >&nbsp; {{ dayjs.duration(roomCounter, 'seconds').format('mm:ss') }}</span
      >
    </div>
    <!-- 视频头像 start -->
    <Camera />
    <!-- 视频头像 end -->
    <!-- {{ selfRoomStatus }} -->
    <!-- <div class="room_valid" v-if="isPanoramaMode && roomCounter > 0 && isNativeLeader">
      <span>{{ dayjs.duration(roomCounter, 'seconds').format('mm:ss') }}</span>
    </div> -->
    <!-- 当前人数 end -->
    <!-- 控制条 start -->
    <div class="controlBar" v-if="!showInput">
      <div
        v-if="connectStatus === 1"
        class="saySomething"
        @click="onFocus"
        :class="{ disabled: !inputStatus && !isNativeLeader }"
      >
        <!-- <i class="speakIcon"
           :class="{'dis':!user_info.IsWords}"></i> -->
        <span v-if="inputStatus || isNativeLeader">{{ t('base.saySomething') }}</span>
        <span v-else>{{ t('base.silent') }}</span>

        <div
          class="disSpeakBtn"
          @click.stop="chatShow = !chatShow"
          :class="{ dis: !chatShow }"
        ></div>
      </div>
      <div style="text-align: right; width: 100%" v-if="connectStatus === 0">{{
        t('base.connecting')
      }}</div>
      <div class="control_btn" v-if="connectStatus === 1">
        <div
          class="brushesBack"
          @click="onDrawUndo"
          :class="{ disabled: !canUndo }"
          v-if="unref(isBrushes) && isNativeLeader"
        ></div>
        <div
          class="brushes"
          v-if="isNativeLeader"
          :class="{ brushed: isBrushes }"
          @click="onDraw(!isBrushes)"
        ></div>

        <div class="invitation" @click="handleCreateShare"></div>
        <!-- @click="openMember" -->
        <div class="members" @click="openMember"></div>

        <template v-if="isNativeLeader">
          <div class="mic_on" v-if="!audioMuted" @click="handleMute"></div>
          <div class="mic_no" v-if="audioMuted" @click="handleNoMute"></div>
        </template>
        <template v-else>
          <div class="mic_on" v-if="!audioMuted"></div>
          <div class="mic_no" v-if="audioMuted"></div>
        </template>
        <div style="font-size: 0.65rem" v-if="isNativeLeader && sceneList.length > 1">
          <ImageIcon type="scene" @click="showScenes = !showScenes" />
        </div>

        <div style="font-size: 0.65rem" v-if="isNativeLeader && globalVideoEnable">
          <template v-if="hosterhasVideo">
            <ImageIcon type="video_on" v-if="!muteVideoLeader" @click="handleHideCamera" />
            <ImageIcon type="video_off" v-if="muteVideoLeader" @click="handleShowCamera" />
          </template>
          <ImageIcon type="video_disable" v-else />
        </div>
        <div class="exit" @click="showCloseDialog = true"></div>
      </div>
    </div>
    <!-- 控制条 start -->
    <!-- 主区域 end  -->
    <!-- 输入框 start-->
    <div class="layer" v-if="showInput" @click.stop="closeText">
      <div class="inputBox" @click.stop>
        <div class="msgBox">
          <input
            id="input_msg"
            type="text"
            maxlength="50"
            v-model.trim="text"
            :placeholder="t('base.saySomething')"
          />
          <span class="iconsend_icon" :class="{ disable: text == '' }" @click.stop="sendText">{{
            t('base.send')
          }}</span>
        </div>
      </div>
    </div>
    <!-- 输入框 end-->
    <!-- 用户列表 start -->
    <memberList
      :data="members"
      :show="showMember"
      :animateActive="animateActive"
      @close-member="closeMember"
    />
    <!-- 用户列表 end -->
  </div>

  <!-- <teleport :to="`#app`">
    <div v-if="showShare" @click="showShare = false" class="sharetip">
      <img
        @click.stop
        :style="`right:${isMP ? '16%' : '6%'}`"
        :src="require('@/assets/images/icon/img_scene_share.png')"
        alt=""
      />
    </div>
  </teleport> -->
  <!-- 场景列表 start -->
  <SceneList v-if="showScenes" @close="showScenes = false" @change-scene="handleChangeScene" />
  <!-- 场景列表 end -->
  <!-- trtc相关 start -->
  <div class="local" id="local" v-if="isJoined"></div>
  <template v-for="item in remoteStreams" :key="item.getId()">
    <div class="remote" :id="item.getId()"></div>
  </template>
  <!-- trtc相关  end -->

  <ShareContainer :share-link="shareLink" @close="shareLink = ''" />
  <CloseDialog
    v-if="showCloseDialog"
    @close-dialog="showCloseDialog = false"
    @confirm-dialog="handleCloseRoom"
  />
  <CreatedName :show="showCreateNameDialog" @confirm-dialog="handleNameConfirm" />
  <PasswordDialog
    :show="showPasswordDialog"
    :is-single="true"
    @confirm-dialog="handlePasswordConfirm"
    @close-dialog="closeSocket"
  />
</template>

<script lang="ts" setup>
  import {
    computed,
    nextTick,
    onMounted,
    onUnmounted,
    Ref,
    ref,
    unref,
    watch,
    watchEffect,
  } from 'vue';
  import { getApp, useApp } from '/@/hooks/userApp';
  import { initSocketEvent } from './roomControl';
  import { createSocket, useSocket } from '/@/hooks/userSocket';
  import { useRtcSdk } from '/@/hooks/useTRTC';
  import { useDraw } from '/@/hooks/useDraw';
  import browser from '/@/utils/browser';
  import ImageIcon from '/@/components/basic/icon/index.vue';
  import { useRtcStore } from '/@/store/modules/rtc';
  import type { SocketParams, RoleType } from '/@/store/modules/rtc';
  import chat from './chat.vue';
  import memberList from './memberList.vue';
  import SceneList from './sceneList.vue';
  import Camera from './camera.vue';
  import { useRoom, SceneItemType } from '/@/hooks/useRoom';
  import consola from 'consola';
  import CloseDialog from './dialog/close.vue';
  import PasswordDialog from './dialog/password.vue';
  import ShareContainer from './share.vue';
  import CreatedName from './dialog/createdName.vue';

  import { useAppStore } from '/@/store/modules/app';
  import { useI18n } from '/@/hooks/useI18n';
  import { useLocale } from '/@/locales/useLocale';
  import dayjs from 'dayjs';
  import duration from 'dayjs/plugin/duration';
  import { useMiniApp } from '/@/hooks/useMiniApp';
  const { closeSocket } = useSocket();
  dayjs.extend(duration);
  // hook
  const { isDrawing, setDraw, setCloseDraw } = useDraw();
  const { initialRoom } = useRoom();
  const { getLocale } = useLocale();

  const rtcStore = useRtcStore();
  const appStore = useAppStore();
  const isNativeLeader = computed(() => rtcStore.role == 'leader');

  const showInput = ref(false);
  const chatShow = ref(true);
  const isBrushes = isDrawing;
  const canUndo = ref(false);
  const animateActive = ref(false);
  const showMember = ref(false);
  const showPasswordDialog = ref(false);
  // const disableMic = ref(false);
  const connectStatus = computed(() => rtcStore.connectStatus);
  const isJoined = computed(() => rtcStore.isJoined);
  const isLoaded = computed(() => appStore.isLoaded);
  const role = computed(() => rtcStore.role);
  const text = ref<string>('');
  const chatList = computed(() => rtcStore.chatList);
  const currentUser = computed(() => rtcStore.userId);
  const inputStatus = computed(() => rtcStore.inputStatus);

  const members = computed(() => rtcStore.memberList);
  const showScenes = ref(false);

  const remoteStreams = computed(() => rtcStore.remoteStreams);
  const currentSession = computed(() => rtcStore.currentSession);
  const isPanoramaMode = computed(() => appStore.mode === 'panorama');

  const shareLink = ref<string>('');
  const showCloseDialog = ref(false);
  const showCreateNameDialog = ref(false);
  const roomTTL = computed(() => appStore.ttl);

  const selfRoomStatus = computed(() => rtcStore.getSelfRoomStatus());
  const audioMuted = computed(() => unref(selfRoomStatus)?.IsMuted);
  const { globalVideoEnable } = useRtcSdk();
  const hosterhasVideo = computed(() => rtcStore.videoDeviceId?.length > 0);
  const { isUsingMiniApp } = useMiniApp();
  const { muteVideoLeader } = useRtcSdk();
  let roomCounter = ref(-1);
  let roomCount: NodeJS.Timeout;
  const { t } = useI18n();
  const { sceneList } = useRoom();

  watchEffect(() => {
    console.log('sceneList', sceneList);
    console.log('isUsingMiniApp', unref(isUsingMiniApp));
  });
  watch(
    () => currentSession,
    (val) => {
      console.log('当前currentSession', val.value?.IsWords);
      rtcStore.setinputStatus(!!val.value?.IsWords);
    },
    { deep: true, immediate: true },
  );
  watch(
    () => roomTTL,
    (val) => {
      console.log('ttl', unref(val));
      if (!roomCount && unref(val) > 0) {
        roomCounter.value = unref(val);
        roomCount = setInterval(() => {
          roomCounter.value = roomCounter.value - 1;
          if (unref(roomCounter) < 0) {
            clearInterval(roomCount);
          }
        }, 1000);
      }
    },
    { immediate: true, deep: true },
  );

  //设置socket 参数
  const startJoin = async (callback?: () => void) => {
    consola.info({
      message: initParams,
      tag: 'socket参数',
    });
    rtcStore.setSocketParams(initParams);
    await nextTick();
    await initialRoom();
    const { room, currentSceneIndex, firstNum } = useRoom();
    console.log('room', room);
    // if (unref(room)?.takeLookLock === 1) {
    //   showPasswordDialog.value = true;
    //   return;
    // }
    if (unref(room)?.takeLookLock === 1) {
      if (unref(currentSceneIndex) > 0) {
        const hasInput = localStorage.getItem(`${rtcStore.roomId}-${unref(firstNum)}`);
        console.log('密码::', hasInput);

        if (Number(hasInput) === 1) {
          showPasswordDialog.value = false;
          //多场景已输入，放行加入
        } else {
          // 存在密码中断rtc connect
          showPasswordDialog.value = true;
          return;
        }
      } else {
        // 存在密码中断rtc connect
        showPasswordDialog.value = true;
        return;
      }
    }

    const socket = createSocket();
    initSocketEvent(socket);
    const { createRTCSocket } = useRtcSdk();
    await createRTCSocket();
    callback && callback();
  };
  console.log('initParams', rtcStore.userId);
  const nickname = decodeURIComponent(decodeURIComponent(browser.getURLParam('name')));
  const initParams: SocketParams = {
    userId:
      browser.getURLParam('vruserId') ||
      rtcStore.userId ||
      `user_${Math.floor(Math.random() * 100000000)}`,
    roomId: browser.getURLParam('roomId') || `room_${Math.floor(Math.random() * 100000000)}`,
    role: (browser.getURLParam('role') as RoleType) || 'leader',
    avatar: browser.getURLParam('avatar'),
    nickname: nickname || '',
    mode: browser.getURLParam('mode'),
  };

  // if (initParams.nickname === '') {
  //   showCreateNameDialog.value = true;
  // } else {
  //   startJoin();
  // }

  const handleNameConfirm = (userName: string) => {
    const rtcStore = useRtcStore();
    console.log('userName', unref(userName));
    rtcStore.setNickName(unref(userName));
    const search = new URLSearchParams(location.search);
    search.set('name', decodeURIComponent(unref(userName)));
    // search.set('vruserId', rtcStore.userId);
    initParams.nickname = rtcStore.nickname;
    console.log('输入后', initParams);
    startJoin(() => {
      search.set('vruserId', rtcStore.userId);
      const replaceUrl = location.origin + location.pathname + '?' + search.toString();
      console.log('replaceUrl', replaceUrl);
      history.replaceState(null, '', replaceUrl);
    });
  };

  const sceneInit = (app, val) => {
    console.log('初始化同屏', unref(val[0]), unref(val[1]));
    if (unref(val[0])) {
      if (unref(isNativeLeader)) {
        app.Connect.follow.start({ follow: false });
      } else {
        console.log('customer-follow');
        app.Connect.follow.start({ follow: true });
      }
      app.Connect.follow.on('data', leaderSync);
      app.Connect.paint.on('data', leaderPaint);
    }
  };

  onMounted(async () => {
    watch(
      () => isLoaded,
      (val) => {
        if (unref(val)) {
          if (initParams.nickname === '') {
            showCreateNameDialog.value = true;
          } else {
            startJoin();
          }
        }
      },
      { deep: true, immediate: true },
    );
    //初始化同屏等
    watch(
      () => [isJoined, isNativeLeader],
      async (val) => {
        try {
          // console.log('初始化同屏', unref(val[0]), unref(val[1]));
          // if (unref(val[0])) {
          //   const app = await useApp();

          //   app.Scene.

          //   if (unref(isNativeLeader)) {
          //     setTimeout(() => {
          //       app.Connect.follow.start({ follow: false });
          //     }, 1000);
          //   } else {
          //     console.log('customer-follow');
          //     setTimeout(() => {
          //       app.Connect.follow.start({ follow: true });
          //     }, 1000);
          //   }
          //   app.Connect.follow.on('data', leaderSync);
          //   app.Connect.paint.on('data', leaderPaint);
          // }
          const app = await useApp();
          if (app.Scene.loaded) {
            sceneInit(app, val);
          } else {
            app.Scene.on('loaded', () => sceneInit(app, val));
          }
        } catch (error) {
          console.log('error', error);
        }
      },
      {
        deep: true,
      },
    );
  });
  onUnmounted(async () => {
    const { handleLeave } = useRtcSdk();
    const app = await useApp();
    app.Connect.follow.off('data', leaderSync);
    app.Connect.paint.off('data', leaderPaint);
    handleLeave();
  });

  /* method 方法*/

  const leaderSync = (data) => {
    const { socket } = useSocket();
    if (unref(isNativeLeader) && unref(isJoined)) {
      socket.emit('sync', data);
    }
  };
  const leaderPaint = (data) => {
    if (unref(isNativeLeader) && unref(isJoined)) {
      const { socket } = useSocket();
      const records = getApp().Connect.paint.records;
      canUndo.value = records?.length;
      socket.emit('paint', data);
    }
  };

  const onDrawUndo = async () => {
    let app = getApp();
    app.Connect.paint.undo();
    canUndo.value = app.Connect.paint.records.length > 0;

    console.log(app.Connect.paint.records, 'app.Connect.paint.records');
  };

  const onDraw = async (status: boolean) => {
    // isBrushes.value = status;
    status && setDraw();
    const { socket } = useSocket();
    !status && setCloseDraw();
    if (unref(isBrushes)) {
      const app = await useApp();
      console.log('app', app.Connect.paint);
      app.Connect.paint.show({
        role: unref(role),
        paint: isNativeLeader.value ? true : false,
      });
      if (unref(role) == 'leader') {
        socket.emit('action', { type: 'user-paint', open: true });
      }
    } else {
      const app = await useApp();
      app.Connect.paint.hide();
      if (unref(role) == 'leader') {
        socket.emit('action', { type: 'user-paint', open: false });
      }
    }
  };

  function closeText(): void {
    showInput.value = false;
    text.value = '';
  }

  function sendText(): void {
    if (text.value == '') {
      return;
    }
    const { socket } = useSocket();
    let data = {
      role: rtcStore.role,
      mode: rtcStore.mode,
      Nickname: rtcStore.nickname,
      UserId: rtcStore.userId,
      text: text.value,
    };
    consola.info({
      message: data,
      tag: '发送信息',
    });
    socket.emit('action', {
      type: 'danmumsg',
      data,
    });
    rtcStore.addToChatList(data);
    document.getElementById('input_msg')?.blur();
    closeText();
  }
  function onFocus(): void {
    showInput.value = true;
    nextTick(() => {
      document.getElementById('input_msg')?.focus();
    });
  }
  const openMember = () => {
    showMember.value = true;
    animateActive.value = true;
  };
  const closeMember = () => {
    animateActive.value = false;
    let t = setTimeout(() => {
      clearTimeout(t);
      showMember.value = false;
    }, 200);
  };

  const handleNoMute = () => {
    const { localStream } = useRtcSdk();
    const { socket } = useSocket();
    // console.log('localStream', localStream);
    console.log('开启MIC');
    socket.emit('action', {
      type: 'users-muted',
      muted: false,
      userId: rtcStore.userId,
    });
    localStream && localStream.resume();
    rtcStore.unmute();
    localStream && localStream.unmuteAudio();
  };
  const handleMute = () => {
    const { localStream } = useRtcSdk();
    const { socket } = useSocket();
    socket.emit('action', {
      type: 'users-muted',
      muted: true,
      userId: rtcStore.userId,
    });
    console.log('localStream', localStream);
    console.log('关闭MIC');
    rtcStore.mute();
    localStream && localStream.muteAudio();
  };

  const handleCloseRoom = async () => {
    showCloseDialog.value = false;
    const { socket, closeSocket, closeRoomForWechat } = useSocket();
    socket.emit('exit', {
      roomId: rtcStore.roomId,
      userId: rtcStore.userId,
    });
    if (isUsingMiniApp.value) {
      //@ts-ignore
      closeRoomForWechat();
    } else {
      closeSocket();
    }
  };

  const handleCreateShare = async () => {
    const search = new URLSearchParams();
    search.set('isTour', '0');
    // search.set('vruserId', `user_${Math.floor(Math.random() * 100000000)}`);
    search.set('role', 'customer');
    search.set('name', '');
    search.set('roomId', `${rtcStore.roomId}`);
    search.set('m', browser.getURLParam('m'));
    const lang = unref(getLocale);
    search.set('lang', lang);
    Number(import.meta.env.VITE_SHOW_CONSOLE) === 1 && search.set('vlog', '1');
    const url = new URL(location.href);
    url.search = `?` + search.toString();

    if (!unref(isUsingMiniApp)) {
      shareLink.value = url.toString();
    } else {
      const { socket } = useSocket();

      socket.emit('action', {
        type: 'users-inviteMember',
        userId: rtcStore.userId,
        data: search.toString(),
      });
    }
  };

  const handleChangeScene = (scene: Ref<SceneItemType>) => {
    const { changeScene } = useRoom();
    const { socket } = useSocket();
    console.log('changeScene');
    socket.emit('action', {
      type: 'changeScene',
      data: scene,
    });
    changeScene(unref(scene));
  };
  const handleHideCamera = () => {
    const { localStream, muteVideoLeader } = useRtcSdk();
    const { socket } = useSocket();
    muteVideoLeader.value = true;
    socket.emit('action', {
      type: 'sync-camera',
      data: {
        show: false,
        userId: rtcStore.userId,
      },
    });
    localStream && localStream.muteVideo();
  };
  const handleShowCamera = () => {
    const { localStream, muteVideoLeader } = useRtcSdk();
    const { socket } = useSocket();
    if (!unref(isUsingMiniApp)) {
      socket.emit('action', {
        type: 'sync-camera',
        data: {
          show: true,
          userId: rtcStore.userId,
        },
      });
      localStream && localStream.unmuteVideo();
      muteVideoLeader.value = false;
    }
  };
  const handlePasswordConfirm = async () => {
    showPasswordDialog.value = false;
    const socket = createSocket();
    initSocketEvent(socket);
    const { createRTCSocket } = useRtcSdk();
    await createRTCSocket();
  };
</script>

<style scoped lang="scss">
  @import './chatroom.scss';
</style>
