<template>
  <div id="app" class="app-container">
    <router-view></router-view>
    <el-dialog
      title="告警详情"
      v-model="globalDialogVisible"
      width="50%"
      @close="handleDialogClose">
      <el-row :gutter="30" style="margin-bottom: 2vh;">
        <el-col span="8">告警编号：{{ globalDialogContent.id }}</el-col>
        <el-col span="8">摄像头名称：{{ globalDialogContent.camera?.name }}</el-col>
        <el-col span="8">告警类型：{{ algorithmMap.get(globalDialogContent.types) || '未知类型' }}</el-col>
      </el-row>
      <img :src="globalDialogContent.snapshotUrl" alt="告警图片" v-if="globalDialogContent.snapshotUrl" style="max-width: 100%;" />
      <video v-if="globalDialogContent.videoUrl" :src="globalDialogContent.videoUrl" controls style="max-width: 100%;"></video>
    </el-dialog>     
  </div>
</template>

<script lang="ts">
import { ref, onMounted } from 'vue';
import eventBus from '@/utils/eventBus';
import { BoxApi } from '@/utils/boxApi';

const apiInstance = new BoxApi();

export default {
  setup() {
    const globalDialogVisible = ref(false);
    const globalDialogContent = ref({
      id: null,
      camera_id: null,
      camera: { name: '' },
      types: null,
      started_at: null,
      snapshotUrl: '',
      videoUrl: ''
    });

    const algorithmMap = ref(new Map()); 

    const loadAlgorithms = async () => {
      const token = localStorage.getItem('alertToken');
      const algorithms = await apiInstance.getAlgorithms(token);
      algorithmMap.value = new Map(algorithms.map((algo: { code_name: string, name: string }) => [algo.code_name, algo.name]));
    };

    const showDialog = async (data: any) => {
      const token = localStorage.getItem('alertToken');
      const eventDetails = await apiInstance.getEventById(data.id, token);
      const snapshot = eventDetails.mediums.find((item: any) => item.name === 'snapshot');
      const video = eventDetails.mediums.find((item: any) => item.name === 'video');

      globalDialogContent.value = {
        id: eventDetails.id,
        camera_id: eventDetails.camera_id,
        camera: eventDetails.camera,
        types: eventDetails.types,
        started_at: eventDetails.started_at,
        snapshotUrl: snapshot?.file || '',
        videoUrl: video?.file || ''
      };

      globalDialogVisible.value = true;
    };

    const handleDialogClose = () => {
      globalDialogVisible.value = false;
      globalDialogContent.value = {
        id: null,
        camera_id: null,
        camera: { name: '' },
        types: null,
        started_at: null,
        snapshotUrl: '',
        videoUrl: ''
      };
    };

    onMounted(() => {
      loadAlgorithms();
      eventBus.on('showDialog', showDialog);
    });

    return {
      globalDialogVisible,
      globalDialogContent,
      handleDialogClose,
      algorithmMap
    };
  }
};
</script>

<style scoped>
#app {
  margin: 0px;
  padding: 0px;
  width: 100%;
  height: 100%;
}
</style>
