<template>
  <van-dialog
    class="BaseApp-dialog BaseApp-dialog--large CameraMonitorDilaog-dialog"
    :class="`CameraMonitorDilaog-dialog--${props.cameraType}`"
    v-model:show="cmptVisible"
    :showCancelButton="false"
    :showConfirmButton="false">
    <!-- 头部 -->
    <div slot="title" class="BaseApp-dialog__header">查看视频</div>
    <!-- 实时 -->
    <div v-if="props.cameraType === 'CAMERA_LIVE'" class="CameraMonitor-live-wrapper">
      <img id="CAMERA_LIVE_IMG" style="height: 100%; width: 100%" :src="cameraUrl" />
      <!-- <video
        id="facevideo"
        autoplay
        muted
        style="
          width: 100% !important;
          height: 100% !important;
          object-fit: fill !important;
        "></video>
      <el-button
        v-if="deviceList.length > 1"
        class="header__close-btn"
        type="text"
        @click="choseDevice">
        切换摄像头-[{{ camerahooseIndex + 1 }}]
      </el-button> -->
    </div>
    <!-- 录像 -->
    <div v-if="props.cameraType === 'CAMERA_RECORD'" class="CameraMonitor-record-wrapper">
      <video
        class="CameraMonitor-record-video"
        ref="videoPlayer"
        autoplay
        controls
        controlsList="nodownload nofullscreen">
        <source :src="cameraUrl" type="video/mp4" />
      </video>
      <div class="CameraMonitor-record-history">
        <div
          v-for="item in recordCameraList"
          class="CameraMonitor-record-history-item"
          :class="{ active: cameraUrl == item }"
          :key="item"
          @click="changeVedioSrc(item)">
          <div class="CameraMonitor-record-history-item__name">{{ getCameraFileName(item) }}</div>
        </div>
      </div>
    </div>

    <div class="BaseApp-dialog__footer">
      <div class="BaseApp-btn" @click="close">关闭</div>
      <div
        v-if="props.cameraType === 'CAMERA_RECORD'"
        class="BaseApp-btn BaseApp-btn--blue"
        @click="exportFile">
        导出
      </div>
    </div>
  </van-dialog>
</template>

<script setup>
import { ref, reactive, onMounted, onBeforeUnmount, nextTick } from 'vue';
import { getExperimentVideoApi, exportExperimentVideoApi } from '@/api/experiment';

const props = defineProps({
  cameraType: {
    type: String,
    default: 'CAMERA_LIVE',
    validator: (value) => ['CAMERA_LIVE', 'CAMERA_RECORD'].includes(value)
  },
  bizId: {
    type: String,
    default: ''
  }
});

const emit = defineEmits(['cancel']);
// 录像地址列表
const recordCameraList = reactive([]);
const videoPlayer = ref(null); // 获取 video 元素的引用

const cmptVisible = ref(true);
const video = ref('');
const stopeVideo = ref('');
const camerahooseIndex = ref(0);
const deviceList = ref([]);
const cameraUrl = ref('');

const initCamera = async () => {
  video.value = document.getElementById('facevideo');

  // 获取所有的摄像头的数据信息
  const devices = await navigator.mediaDevices.enumerateDevices();
  console.log('输出所有的设备编号', devices);
  devices.forEach((item) => {
    if (item.kind === 'videoinput') {
      deviceList.value.push({
        label: item.label,
        deviceId: item.deviceId
      });
    }
  });
  console.log('获取到了所有的摄像头设备', deviceList.value);

  // 切换摄像头设备
  camerahooseIndex.value = 0;
  if (localStorage.getItem('CameraMonitor_camerahooseIndex')) {
    camerahooseIndex.value = Number.parseInt(
      localStorage.getItem('CameraMonitor_camerahooseIndex')
    );
  }
  console.log('摄像头选取位置', camerahooseIndex.value, deviceList.value);

  navigator.mediaDevices
    .getUserMedia({
      video: { deviceId: deviceList.value[camerahooseIndex.value].deviceId },
      audio: false
    })
    .then((stream) => {
      video.value.srcObject = stream;
      stopeVideo.value = stream.getTracks()[0];
    });
};

const choseDevice = () => {
  camerahooseIndex.value++;
  if (camerahooseIndex.value >= deviceList.value.length) {
    camerahooseIndex.value = 0;
  }
  localStorage.setItem('CameraMonitor_camerahooseIndex', camerahooseIndex.value);

  navigator.mediaDevices
    .getUserMedia({
      video: { deviceId: deviceList.value[camerahooseIndex.value].deviceId },
      audio: false
    })
    .then((stream) => {
      video.value.srcObject = stream;
      stopeVideo.value = stream.getTracks()[0];
    });
};

const fnClose = () => {
  video.value.pause();
  stopeVideo.value.stop();
};

/**
 * 初始化在线监控
 */
const initCameraLive = async () => {
  cameraUrl.value = `${import.meta.env.VITE_SEVER_URL}/api/camera_img/?id=${props.bizId}`;
};

/**
 * 初始化视频录像
 */
const initCameraRecord = async () => {
  const res = await getExperimentVideoApi({ record_id: props.bizId });
  let { code, data } = res?.data || {};
  if (code !== 200) {
    notify(desc);
    return;
  }
  console.log(data);
  recordCameraList.length = 0;
  data.forEach((item) => {
    recordCameraList.push(item);
  });

  if (recordCameraList.length > 0) {
    changeVedioSrc(recordCameraList[0]);
  }
};

const getCameraFileName = (fileUrl) => {
  let fileName = fileUrl.split('/');
  return fileName[fileName.length - 1];
};

const close = () => {
  console.log('关闭摄像头');
  emit('cancel');
};

const exportFile = async () => {
  const res = await exportExperimentVideoApi({ id: props.bizId });
  let { code, data } = res?.data || {};
  if (code !== 200) {
    notify(desc);
    return;
  }
  notify(desc);
};

const changeVedioSrc = (src) => {
  cameraUrl.value = src;
  videoPlayer.value.load();
  videoPlayer.value.play();
};

onMounted(() => {
  console.log(props.cameraType);
  if (props.cameraType === 'CAMERA_LIVE') {
    initCameraLive();
  } else if (props.cameraType === 'CAMERA_RECORD') {
    initCameraRecord();
  }
});

onBeforeUnmount(() => {
  if (props.cameraType === 'CAMERA_LIVE') {
    cameraUrl.value = '';
    document.getElementById('CAMERA_LIVE_IMG').src = '';
    //fnClose();
  }
});
</script>

<style lang="less">
.CameraMonitorDilaog-dialog--CAMERA_RECORD {
  width: 950px !important;
}
</style>

<style lang="less" scoped>
.CameraMonitorDilaog-dialog {
  .BaseApp-dialog__header {
    display: flex;
    flex-direction: row;
    align-items: center;
    margin: 15px;
    font-size: 20px;
    font-weight: bolder;
  }
  .BaseApp-dialog__footer {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: flex-end;
    margin: 15px;
  }
}
.CameraMonitor-live-wrapper {
  width: 100%;
  height: 500px;
}
.CameraMonitor-record-wrapper {
  display: flex;
  flex-direction: row;
  width: 100%;
  height: 500px;
  .CameraMonitor-record-video {
    width: 750px;
    height: 100%;
    object-fit: cover;
  }
  .CameraMonitor-record-history {
    display: flex;
    flex-direction: column;
    flex: 1;
    height: 100%;
    overflow-y: auto;
    .CameraMonitor-record-history-item {
      display: flex;
      flex-direction: row;
      align-items: center;
      padding: 10px;
      &.active {
        color: #f6f7f9;
        background-color: #409eff;
      }
    }
  }
}
</style>