<template>
  <div class="safety-platform-container">
    <header class="safety-platform-container__header">
      <div>
        <BreadcrumbBack />
        <span class="breadcrumb-title" style="margin-left: 8px">{{ '演练记录' }}</span>
      </div>
      <el-tabs v-model="activeName">
        <el-tab-pane
          v-for="item in EMERGENCY_DRILL_DETAIL_SUBPAGE"
          :key="item.value"
          :label="item.label"
          :name="item.value"
        />
      </el-tabs>
    </header>
    <main class="safety-platform-container__main">
      <component :is="dynamicComponent" :id="id" ref="dynamicComponentRef" />
    </main>
    <footer class="safety-platform-container__footer" v-if="activeName === EMERGENCY_DRILL_DETAIL_SUBPAGE[1].value">
      <!-- 按钮 -->
      <el-button type="primary" @click="downloadPDF">导出</el-button>
    </footer>
    <UploadLoading :form-loading="formLoading" v-if="formLoading" />
  </div>
</template>

<script setup lang="ts">
  import { ref, computed, defineAsyncComponent } from 'vue';
  import { ElMessage } from 'element-plus';
  import { useRoute } from 'vue-router';
  import UploadLoading from '@/components/UploadLoading.vue';
  import { EMERGENCY_DRILL_DETAIL_SUBPAGE } from './constants';
  import { exportEmergencyDrillRecord } from '@/api/emergency-drill/emergency-drill';
  import { downloadFile } from '@/views/disaster/utils/download';

  const formLoading = ref(false);
  const route = useRoute();
  const id = route.query.id;
  const activeName = ref(route.query.tab || EMERGENCY_DRILL_DETAIL_SUBPAGE[0].value);

  const dynamicComponent = computed(() => {
    switch (activeName.value) {
      case 'activities':
        return defineAsyncComponent(() => import('./components/DrillPlanViewActivities.vue'));
      case 'records':
        return defineAsyncComponent(() => import('./components/DrillPlanViewRecords.vue'));
    }
  });

  const downloadPDF = async () => {
    try {
      const res = await exportEmergencyDrillRecord(id);
      if (res.size === 0) return;
      const blob = new Blob([res], { type: 'application/pdf' });
      const url = window.URL.createObjectURL(blob);
      downloadFile(url, '应急演练记录及评估表.pdf');
    } catch (e) {
      ElMessage.error('下载失败');
      console.log(e);
    }
  };
</script>

<style scoped lang="scss">
  @use '@/styles/page-details-layout.scss' as *;
  .safety-platform-container__header {
    padding-bottom: 0 !important;
  }
  :deep(.el-tabs__header) {
    margin: 0;
  }
  :deep(.el-tabs__item) {
    font-size: 14px !important;
  }
</style>
