<template>
  <div class="preview-online-container" v-if="showPreviewOnline">
    <el-icon class="close-icon" @click="close"><CloseBold /></el-icon>
    <component
      v-if="dynamicComponent[documentType as keyof typeof dynamicComponent]"
      :is="dynamicComponent[documentType as keyof typeof dynamicComponent]"
      :src="documentUrl"
    />
    <template v-else>
      <div class="preview-img">
        <img :alt="documentUrl" :src="documentUrl" />
      </div>
    </template>
  </div>
</template>

<script lang="ts" setup>
  import { ref, computed, defineAsyncComponent } from 'vue';
  import { CloseBold } from '@element-plus/icons-vue';
  import { FILE_TYPE_ICON } from '@/components/UploadFiles/constants';
  import '@vue-office/docx/lib/index.css';
  import '@vue-office/excel/lib/index.css';

  const showPreviewOnline = ref(false);
  const documentUrl = ref('');
  const documentType = ref<keyof typeof FILE_TYPE_ICON>();
  const open = (url: string, type: keyof typeof FILE_TYPE_ICON) => {
    showPreviewOnline.value = true;
    documentUrl.value = url;
    documentType.value = type;
  };
  const close = () => {
    showPreviewOnline.value = false;
  };
  const dynamicComponent = computed(() => {
    return {
      word: defineAsyncComponent(() => import('@vue-office/docx')),
      excel: defineAsyncComponent(() => import('@vue-office/excel')),
      pdf: defineAsyncComponent(() => import('@vue-office/pdf')),
      ppt: defineAsyncComponent(() => import('@vue-office/pptx')),
    };
  });
  defineExpose({
    open,
  });
</script>

<style lang="scss" scoped>
  .preview-online-container {
    position: fixed;
    top: 0;
    left: 0;
    width: 100vw;
    height: 100vh;
    background-color: rgba(0, 0, 0, 0.3);
    z-index: 9999;
  }
  .close-icon {
    position: absolute;
    top: 20px;
    right: 20px;
    cursor: pointer;
    font-size: 30px;
    color: $text-color;
    z-index: 9999;
  }
  .preview-img {
    position: fixed;
    top: 0;
    left: 0;
    width: 100vw;
    height: 100vh;
    background-color: rgba(0, 0, 0, 0.3);
    z-index: 9998;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  :deep(.docx-wrapper) {
    background: $white-color;
    padding: 0;
  }
  :deep(.slide-master-wrapper) {
    height: 100vh;
  }
  :deep(.vue-office-pdf) {
    height: 100% !important;
    overflow-y: auto !important;
  }
  :deep(.vue-office-pptx) {
    height: 100vh !important;
    overflow-y: auto !important;
  }
  :deep(.pptx-preview-wrapper) {
    height: 100% !important;
    overflow-y: auto !important;
  }
</style>
