<template>
  <BaseLive :room-info="roomInfo">
    <div class="teacher">
      <div class="middle">
        <!-- 教师学员列表 -->
        <PersonnelList
          :has-video="isShowPersonnelList"
          :student-list="student_list"
          :teacher-name="roomInfo.teacher_name"
          @invite="invite"
          @kickOut="kickOut"
        />

        <!-- 直播视频与连线 -->
        <div v-show="!isShowDraw" class="live-main">
          <div class="live-connection" :style="{ 'padding-top': connect || callLoading ? '131px' : '0' }">
            <div class="live">
              <div v-show="hasVideo" id="live"></div>
            </div>
            <div v-show="callLoading" class="call-loading">
              <span>等待接通...</span>
            </div>
            <div v-show="connect" id="student" class="student-video"></div>
          </div>
          <div v-show="callLoading || connect" class="close">
            <el-button type="danger" @click="() => (remoteStreamType === 1 ? unPubShareStream() : handsDown())">
              {{ remoteStreamType === 1 ? '关闭共享' : '结束连线' }}
            </el-button>
          </div>
        </div>

        <!-- 画板 -->
        <div class="draw" :style="{ left: isShowDraw ? '0' : `-${innerWidth}px` }">
          <div id="draw-parent">
            <div class="draw-setting">
              <span class="brush-shape" @click="changeDraw('type', 2)">
                <svg-icon icon-class="brush-shape" />
              </span>
              <!-- 画笔颜色 -->
              <span
                v-for="item in drawColorList"
                :key="item"
                :class="['draw-color', item === curColor ? 'current' : '']"
                :style="{ 'background-color': item }"
                @click="changeDraw('color', item)"
              ></span>
              <span
                v-for="item in drawThicknessList"
                :key="item"
                class="draw-thickness"
                @click="changeDraw('thickNess', item)"
              >
                <span :style="{ width: item * 2 + 'px', height: item * 2 + 'px' }"></span>
              </span>
              <span class="eraser" @click="changeDraw('type', 9)">
                <svg-icon icon-class="back" />
              </span>
              <span class="eraser" @click="changeDraw('type', 10)">
                <svg-icon icon-class="eraser" />
              </span>
              <span class="brush-clear" @click="changeDraw('type', 0)">
                <svg-icon icon-class="clear" />
              </span>
            </div>
          </div>
        </div>

        <!-- 聊天 -->
        <ChatPage ref="cPage" :chat-list="chatList" :chat-show="chatShow" @sendMsg="sendMsg" />

        <!-- 成员列表 -->
        <MemberList :member-show="memberShow" :student-list="student_list" @invite="invite" @kickOut="kickOut" />
      </div>
      <div class="bottom">
        <div class="operation">
          <div class="operation-item" @click="playOrPauseAudio">
            <img :src="hasAudio ? require('@/assets/live/voice.png') : require('@/assets/live/voice-off.png')" alt="" />
            <span>{{ hasAudio ? '开启静音' : '解除静音' }}</span>
          </div>
          <div class="operation-item" @click="playOrPauseVideo">
            <img
              :src="hasVideo ? require('@/assets/live/monitor.png') : require('@/assets/live/monitor-off.png')"
              alt="视频流开关"
            />
            <span>{{ hasVideo ? '关闭视频' : '开启视频' }}</span>
          </div>
        </div>
        <div class="operation">
          <div class="operation-item" @click="publishShareStream">
            <img src="@/assets/live/laptop-computer.png" alt="" />
            <span>共享屏幕</span>
          </div>

          <div class="operation-item" @click="changeWhiteboard">
            <img src="@/assets/live/laptop-computer.png" alt="" />
            <span>{{ isShowDraw ? '退出白板' : '互动白板' }}</span>
          </div>

          <div class="operation-item" @click="dialogVisible = true">
            <img src="@/assets/live/folder-upload.png" alt="" />
            <span>课件推送</span>
          </div>

          <el-popover width="280" popper-class="group-discussion" title="分组设置" trigger="click" placement="top">
            <div>
              <el-form :model="groupForm" label-width="80px" label-position="left">
                <el-form-item label="分组方式">
                  <el-radio v-model="groupForm.operation_mode" label="group_count">按组</el-radio>
                  <el-radio v-model="groupForm.operation_mode" label="person_count">按人</el-radio>
                </el-form-item>
                <el-form-item label="分成几组">
                  <el-input-number
                    v-model="groupForm.group_count"
                    :disabled="groupForm.operation_mode !== 'group_count'"
                    size="small"
                    :min="1"
                  />
                </el-form-item>
                <el-form-item label="几人一组">
                  <el-input-number
                    v-model="groupForm.person_count"
                    :disabled="groupForm.operation_mode !== 'person_count'"
                    size="small"
                    :min="1"
                  />
                </el-form-item>
                <el-form-item>
                  <el-button size="small" @click="startGroup">确定</el-button>
                </el-form-item>
              </el-form>
            </div>
            <div slot="reference" class="operation-item">
              <img src="@/assets/live/every-user.png" alt="" />
              <span>分组讨论</span>
            </div>
          </el-popover>

          <span class="line"></span>

          <div :class="['operation-item', { active: chatShow }]" @click="toggle(toggleList[0].type)">
            <img src="@/assets/live/communication.png" alt="" />
            <span>聊天</span>
          </div>

          <div :class="['operation-item', { active: memberShow }]" @click="toggle(toggleList[1].type)">
            <img src="@/assets/live/peoples.png" alt="" />
            <span>成员列表</span>
          </div>

          <div class="operation-item">
            <img src="@/assets/live/recording.png" alt="" />
            <span>录制</span>
          </div>
        </div>
        <div class="operation">
          <button class="live-button" @click="() => (liveStat ? closeLiveRoom() : startLive())">
            {{ liveStat ? '结束直播' : '开始直播' }}
          </button>
        </div>
      </div>
    </div>

    <!-- 选择设备 -->
    <SelectDevice
      :dialog-visible-device="dialogVisibleDevice"
      :device="device"
      @dialogDeviceClose="dialogDeviceClose"
    />
    <!-- 推送资料 -->
    <SelectMaterial
      :dialog-visible="dialogVisible"
      :task-id="task_id"
      @dialogClose="dialogClose"
      @dialogPush="dialogPush"
    />

    <!-- 教师查看当前完成列表 -->
    <CompleteList
      :task-id="task_id"
      :material-id="materialId"
      :material-type="materialType"
      :dialog-visible-complete="dialogVisibleComplete"
      @dialogCompleteClose="dialogCompleteClose"
    />
  </BaseLive>
</template>

<script>
export default {
  name: 'TeacherLive'
};
</script>

<script setup>
import { ref, computed, watch, provide, inject } from 'vue';
import { CloseLiveRoom } from '@/api/live';
import { Message, MessageBox } from 'element-ui';
import { useRoute, useRouter } from 'vue-router/composables';
import { useInit, useChat, useMemberList, useLive } from '../common/common';
import { useTeacherLiveRtc, useInitListener, useConnect, useGroup, useWhiteboard, usePushMaterial } from './live';
import { app } from '@/store/mutation-types';

import store from '@/store';

import BaseLive from '../common/BaseLive.vue';
import SelectDevice from '../common/SelectDevice';
import ChatPage from '../common/ChatList.vue';
import MemberList from '../common/MemberList.vue';
import PersonnelList from '../common/PersonnelList.vue';
import SelectMaterial from '@/components/live/SelectMaterial.vue';
import CompleteList from './components/CompleteList.vue';

const router = useRouter();
const route = useRoute();
const task_id = route.query.task_id;
provide('task_id', task_id);
const $t = inject('$t');

let remoteStreamType = ref(-1);
let roomData = ref({
  desc: '直播间标题',
  name: '姓名',
  user: {
    id: '',
    name: '',
    role: 'talker',
    rommid: ''
  },
  max_users: 1,
  allow_chat: true,
  allow_audio: true,
  allow_speak: true
});
let speakData = ref({});
let roomContext = ref({});

const innerWidth = window.innerWidth;

const { dialogClose, dialogCompleteClose, dialogPush, dialogVisible, dialogVisibleComplete, materialId, materialType } =
  usePushMaterial();
// 聊天
let cPage = ref();
const { chatList, chatShow, sendMsg, toggle: chatToggle } = useChat(cPage);
// 成员列表
const { memberShow, toggle: memberToggle } = useMemberList();

// 多个附属界面切换
const toggleList = [
  {
    type: 'chat',
    toggle: chatToggle
  },
  {
    type: 'member',
    toggle: memberToggle
  }
];
function toggle(type) {
  let item = toggleList.find((item) => item.type === type);
  if (item === undefined) return;
  item.toggle();
  toggleList.forEach((item) => {
    if (item.type !== type) {
      item.toggle(false);
    }
  });
}

const { startLive, stopLive, kickOut, publishShareStream, unPubShareStream } = useTeacherLiveRtc();
const { pauseVideo, playVideo, pauseAudio, playAudio, closeVideo, createLocalStream } = useLive();
const { groupForm, startGroup } = useGroup(task_id, router);
// 本地视频流画面、声音
let device = ref({
  video: [],
  audio: []
});
let hasVideo = ref(false);
let hasAudio = ref(false);

let isShowPersonnelList = computed(() => {
  return hasVideo.value || connect.value || callLoading.value || isShowDraw.value;
});

/**
 * 本地流视频开启、关闭
 */
function playOrPauseVideo() {
  if (device.value.video.length === 0) {
    return Message.warning($t('Key399'));
  }

  if (hasVideo.value) {
    pauseVideo({
      streamName: 'main',
      success: () => {
        Message.success($t('Key433'));
        hasVideo.value = false;
      },
      fail: (str) => {
        Message.warning(str);
      }
    });
  } else {
    playVideo({
      streamName: 'main',
      success: () => {
        Message.success($t('Key434'));
        hasVideo.value = true;
      },
      fail: (str) => {
        Message.warning(str);
      }
    });
  }
}

/**
 * 本地流音频开启、关闭
 */
function playOrPauseAudio() {
  if (device.value.audio.length === 0) {
    return Message.warning($t('Key401'));
  }

  if (hasAudio.value) {
    pauseAudio({
      streamName: 'main',
      success: () => {
        Message.success($t('Key435'));
        hasAudio.value = false;
      },
      fail: (str) => {
        Message.warning(str);
      }
    });
  } else {
    playAudio({
      streamName: 'main',
      success: () => {
        Message.success($t('Key436'));
        hasAudio.value = true;
      },
      fail: (str) => {
        Message.warning(str);
      }
    });
  }
}

let dialogVisibleDevice = ref(false);
let isRecreate = ref(false);

// 设置音视频设备
function setDevice(isRec) {
  isRecreate.value = isRec;
  dialogVisibleDevice.value = true;
}

function dialogDeviceClose(device) {
  store.commit(`app/${app.SET_DEVICE}`, device);
  dialogVisibleDevice.value = false;
  if (isRecreate.value) {
    closeVideo({
      streamName: 'main',
      success: () => {
        createLocalStream('main', hasAudio, hasVideo);
      },
      fail: (str) => {
        console.log(str);
      }
    });
  } else {
    createLocalStream('main', hasAudio, hasVideo);
  }
}

const {
  callLoading,
  connect,
  connectStudent,
  connectUid,
  liveStat,
  material_list,
  roomInfo,
  student_list,
  getLiveRoomData_DRTD
} = useInit(useInitListener, {
  roomData,
  chatList,
  device,
  roomContext,
  speakData,
  remoteStreamType,
  setDevice,
  hasAudio,
  hasVideo
});

watch(
  () => roomInfo.value.is_enable_whiteboard,
  (val) => {
    changeWhiteboard(val);
  }
);

const { changeDraw, changeWhiteboard, isShowDraw, curColor, drawColorList, drawThicknessList } = useWhiteboard(
  task_id,
  connect,
  callLoading
);

const { handsDown, invite } = useConnect({
  connect,
  callLoading,
  connectStudent,
  roomInfo,
  connectUid,
  getLiveRoomData_DRTD
});

/**
 * 关闭直播间
 */
function closeLiveRoom() {
  MessageBox.confirm('是否关闭当前直播？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    CloseLiveRoom({ task_id }).then(() => {
      router.push('/');
      Message.success($t('Key426'));
    });
    stopLive();
  });
}
</script>

<style lang="scss" scoped>
.teacher {
  display: flex;
  flex-direction: column;
  height: 100%;

  .middle {
    position: relative;
    flex: 1;
    overflow: hidden;

    .live-main {
      display: flex;
      flex-direction: column;
      width: 100%;
      height: 100%;
      background-color: #434343;

      .live-connection {
        display: flex;
        flex: 1;

        .live {
          flex: 1;
          background-color: #000;

          #live {
            width: 100%;
            height: 100%;
          }
        }

        .call-loading {
          display: flex;
          flex-basis: 50%;
          align-items: center;
          justify-content: center;
          color: #fff;
          background-color: #333;
        }

        .student-video {
          flex-basis: 50%;
        }
      }

      .close {
        display: flex;
        justify-content: center;
        padding: 90px 0 16px;
      }
    }

    .draw {
      position: absolute;
      width: 100%;
      height: 100%;
      overflow: hidden;

      #draw-parent {
        height: 100%;
        margin: auto;

        .draw-setting {
          position: absolute;
          bottom: 13px;
          left: 22px;
          z-index: 9999;
          height: 40px;
          padding: 6px;
          line-height: 28px;
          background-color: #a0a0a0;
          border-radius: 40px;

          > span {
            display: inline-block;
            margin-right: 10px;
            text-align: center;
          }

          > span.brush-shape {
            width: 28px;
            height: 28px;
            cursor: pointer;
            background-color: #fff;
            border-radius: 50%;
          }

          .draw-color {
            position: relative;
            top: 5px;
            width: 18px;
            height: 18px;
            cursor: pointer;
            border-radius: 50%;
          }

          .current::after {
            position: absolute;
            bottom: -7px;
            left: 7px;
            width: 4px;
            height: 4px;
            content: '';
            background-color: #292929;
            border-radius: 50%;
          }

          .draw-thickness {
            display: inline-flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            width: 18px;
            height: 18px;
            vertical-align: middle;
            cursor: pointer;

            span {
              background-color: #000;
              border-radius: 50%;
            }
          }

          > %brush-clear,
          .brush-clear {
            width: 28px;
            height: 28px;
            margin-right: 0;
            cursor: pointer;
            background-color: #666;
            border-radius: 50%;
          }

          > .eraser {
            @extend %brush-clear;

            margin-right: 12px;
          }
        }
      }
    }
  }

  .bottom {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 96px;
    padding: 12px 16px;
    background-color: #f8f8f8;

    .operation {
      display: flex;
      column-gap: 16px;

      &-item {
        display: flex;
        flex-direction: column;
        row-gap: 4px;
        align-items: center;
        width: 80px;
        height: 70px;
        padding: 8px;
        cursor: pointer;
        border-radius: 8px;
        transition: background-color 0.3s;

        &.active,
        &:active {
          background-color: #e5e5e5;
        }

        img {
          width: 32px;
          height: 32px;
        }
      }

      .line {
        width: 2px;
        height: 70px;
        background-color: #d0d0d0;
      }

      .live-button {
        height: 48px;
        padding: 8px 24px;
        font-size: 20px;
        font-weight: 500;
        color: #e52e2e;
        cursor: pointer;
        border: 2px solid #e52e2e;
        border-radius: 4px;
      }
    }
  }
}
</style>

<style lang="scss">
.group-discussion {
  padding: 24px;
  background-color: #fff;

  .el-form {
    &-item:last-child {
      margin-bottom: 0;

      .el-form-item__content {
        display: flex;
        justify-content: flex-end;

        .el-button {
          margin-right: 18px;
          color: #fff;
          background-color: #3fa1fb;
        }
      }
    }
  }

  .el-radio__input.is-checked .el-radio__inner {
    background-color: #0052d9;
    border-color: #0052d9;
  }

  .el-input-number {
    width: 136px;

    .el-input__inner {
      width: 62px;
      height: 33px;
      padding: 0;
      margin-left: 36px;
    }

    &__decrease,
    &__increase {
      border: 1px solid #dcdfe6;
    }
  }

  .el-popover {
    &__title {
      font-weight: 600;
      color: #000;
    }

    &[x-placement^='bottom'] .popper__arrow::after {
      border-bottom-color: #fff;
    }
  }
}
</style>
