<template>
  <el-dialog
    :title="title"
    :visible.sync="dialogVisible"
    :width="width"
    :close-on-click-modal="false"
    destroy-on-close
    append-to-body
    @close="handleClose"
  >
    <!-- 图片预览 -->
    <ImagePreview v-if="fileType === 'image'" :src="fileUrl" />
    
    <!-- PDF预览 -->
    <PdfPreview v-else-if="fileType === 'pdf'" :src="fileUrl" />
    
    <!-- Word预览 -->
    <DocxPreview v-else-if="fileType === 'docx'" :src="fileUrl" />
    
    <!-- Excel预览 (xlsx) -->
    <XlsxPreview v-else-if="fileType === 'xlsx'" :src="fileUrl" />
    
    <!-- Excel预览 (xls) -->
    <XlsPreview v-else-if="fileType === 'xls'" :src="fileUrl" />
    
    <!-- 不支持的文件类型 -->
    <div v-else class="preview-not-supported">
      <el-empty description="暂不支持预览此文件类型"></el-empty>
    </div>
  </el-dialog>
</template>

<script>
import ImagePreview from './preview/image/index.vue';
import PdfPreview from './preview/pdf/index.vue';
import DocxPreview from './preview/docx/index.vue';
import XlsxPreview from './preview/xlsx/index.vue';
import XlsPreview from './preview/xls/index.vue';

export default {
  name: "FilePreview",
  components: {
    ImagePreview,
    PdfPreview,
    DocxPreview,
    XlsxPreview,
    XlsPreview
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    fileUrl: {
      type: String,
      required: true
    },
    fileName: {
      type: String,
      default: "文件预览"
    },
    width: {
      type: String,
      default: "80%"
    }
  },
  data() {
    return {
      dialogVisible: false
    };
  },
  watch: {
    visible: {
      handler(val) {
        this.dialogVisible = val;
      },
      immediate: true
    },
    dialogVisible(val) {
      if (!val) {
        this.$emit('update:visible', false);
      }
    }
  },
  computed: {
    title() {
      return this.fileName || "文件预览";
    },
    fileType() {
      const fileName = this.fileName || '';
      const ext = fileName.split('.').pop()?.toLowerCase();
      if (['png', 'jpg', 'jpeg', 'bmp', 'webp'].includes(ext)) {
        return 'image';
      } else if (ext === 'pdf') {
        return 'pdf';
      } else if (ext === 'docx') {
        return 'docx';
      } else if (ext === 'xlsx') {
        return 'xlsx';
      } else if (ext === 'xls') {
        return 'xls';
      } else {
        return 'other';
      }
    }
  },
  methods: {
    handleClose() {
      this.$emit('update:visible', false);
    }
  }
};
</script>

<style scoped>
.preview-not-supported {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 400px;
}
</style>