<template>
  <!-- 主区域 start  -->
  <div id="PageRtcLive">
    <chat v-show="chatShow" :chatList="chatList" :currentUser="currentUser" />
    <!-- 当前人数 start -->
    <div class="member_number">
      <div class="members"></div>
      <span>{{ members.length }}观看</span>
    </div>
    <!-- 当前人数 end -->
    <!-- 控制条 start -->
    <div class="controlBar" v-if="!showInput">
      <div class="saySomething" @click="onFocus" :class="{ disabled: !inputStatus }">
        <!-- <i class="speakIcon"
           :class="{'dis':!user_info.IsWords}"></i> -->
        <span v-if="inputStatus">说点什么~</span>
        <span v-else>已被禁言</span>

        <div
          class="disSpeakBtn"
          @click.stop="chatShow = !chatShow"
          :class="{ dis: !chatShow }"
        ></div>
      </div>
      <!-- <div style="text-align: right; width: 100%">连接中...</div> -->
      <div class="control_btn">
        <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>

        <div style="font-size: 0.65rem" v-if="isNativeLeader">
          <ImageIcon type="scene" @click="showScenes = !showScenes" />
        </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="`说点什么~`"
          />
          <span class="iconsend_icon" :class="{ disable: text == '' }" @click.stop="sendText"
            >发送</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" @changeScene="changeScene" />
  <!-- 场景列表 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"
  />
</template>

<script lang="ts" setup>
  import { computed, nextTick, onMounted, onUnmounted, 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 { useRoom } from '/@/hooks/useRoom';
  import consola from 'consola';
  // import Dialog from '../basic/dialog';
  import CloseDialog from './dialog/close.vue';
  // import { storeToRefs } from 'pinia';
  import ShareContainer from './share.vue';
  // hook
  const { isDrawing, setDraw, setCloseDraw } = useDraw();
  const { initialRoom } = useRoom();

  const rtcStore = useRtcStore();
  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 disableMic = ref(false);
  const isJoined = computed(() => rtcStore.isJoined);
  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 audioMuted = computed(() => rtcStore.audioMuted);
  const remoteStreams = computed(() => rtcStore.remoteStreams);
  const currentSession = computed(() => rtcStore.currentSession);

  const shareLink = ref<string>('');
  const showCloseDialog = ref(false);

  // watchEffect(() => {

  // });
  watch(
    () => currentSession,
    (val) => {
      console.log('当前currentSession', val.value?.IsWords);
      rtcStore.setinputStatus(!!val.value?.IsWords);
    },
    { deep: true, immediate: true },
  );
  //设置socket 参数
  const initParams: SocketParams = {
    userId:
      browser.getURLParam('vruserId') ||
      `user_${browser.getURLParam('role')}${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: browser.getURLParam('name'),
    mode: browser.getURLParam('mode'),
  };
  consola.info({
    message: initParams,
    tag: 'socket参数',
  });
  rtcStore.setSocketParams(initParams);

  const socket = createSocket();
  initSocketEvent(socket);
  const { createRTCSocket, handleLeave } = useRtcSdk();

  (async () => {
    await createRTCSocket();
  })();
  initialRoom();
  onMounted(async () => {
    const app = await useApp();
    // app.Connect.follow.start({ follow: !unref(isNativeLeader) });
    watchEffect(() => {
      if (unref(isNativeLeader)) {
        app.Connect.follow.start({ follow: false });
        app.Connect.follow.on('data', leaderSync);
        app.Connect.paint.on('data', leaderPaint);
      }
    });
  });
  onUnmounted(async () => {
    const app = await useApp();
    app.Connect.follow.off('data', leaderSync);
    app.Connect.paint.off('data', leaderPaint);
    handleLeave();
  });

  /* method 方法*/

  const leaderSync = (data) => {
    if (unref(isNativeLeader) && unref(isJoined)) {
      socket.emit('sync', data);
    }
  };
  const leaderPaint = (data) => {
    if (unref(isNativeLeader) && unref(isJoined)) {
      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();
    !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;
    }
    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();
    console.log('localStream', localStream);
    rtcStore.unmute();
    localStream.unmuteAudio();
    socket.emit('action', {
      type: 'users-muted',
      muted: false,
      userId: rtcStore.userId,
    });
  };
  const handleMute = () => {
    const { localStream } = useRtcSdk();
    console.log('localStream', localStream);
    rtcStore.mute();
    localStream.muteVideo();
    socket.emit('action', {
      type: 'users-muted',
      muted: true,
      userId: rtcStore.userId,
    });
  };

  const handleCloseRoom = () => {
    showCloseDialog.value = false;
    const { closeSocket } = useSocket();
    closeSocket();
  };

  const handleCreateShare = () => {
    shareLink.value = location.href;
  };

  const changeScene = () => {
    console.log('changeScene');
  };
</script>

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