<template>
  <el-dialog :model-value="visible" class="file-preview-dialog" top="5vh" destroy-on-close :before-close="handleClose"
    @update:model-value="(v) => !v && handleClose()">
    <!-- <template #header> -->
    <!-- <div class="body-header">
      <div class="body-title">{{ fileName || $t('btn.preview') }}</div>
      <img src="@/assets/image/close-btn.svg" alt="" class="close-btn" @click="closeDialog" />
    </div> -->
    <!-- </template> -->
    <div class="body-wrap">
      <div class="file-preview-header">
        <span class="file-preview-title" :title="fileName">{{ fileName || $t('btn.preview') }}</span>
        <div class="file-preview-tools">
          <template v-if="fileType === 'pdf'">
            <el-button size="small" :disabled="pageScale <= 0.5" @click="scaleDown">
              <el-icon>
                <ZoomOut />
              </el-icon>
            </el-button>
            <span class="scale-text">{{ Math.round(pageScale * 100) }}%</span>
            <el-button size="small" :disabled="pageScale >= 2.5" @click="scaleUp">
              <el-icon>
                <ZoomIn />
              </el-icon>
            </el-button>
            <el-button size="small" :disabled="currentPage <= 1" @click="prevPage">
              <el-icon>
                <ArrowLeft />
              </el-icon>
            </el-button>
            <span class="page-text">{{ currentPage }} / {{ totalPages }}</span>
            <el-button size="small" :disabled="currentPage >= totalPages" @click="nextPage">
              <el-icon>
                <ArrowRight />
              </el-icon>
            </el-button>
          </template>
          <el-button type="primary" size="small" @click="handleDownload">
            <el-icon>
              <Download />
            </el-icon>
            <span style="margin-left: 4px">{{ $t('btn.download') || '下载' }}</span>
          </el-button>
          <img src="@/assets/image/close-btn.svg" alt="" class="close-btn" @click="handleClose"/>
        </div>
      </div>

      <div v-loading="loading" class="file-preview-body">
        <VuePdfEmbed v-if="fileType === 'pdf' && blobUrl" :source="blobUrl" :page="currentPage" :scale="pageScale"
          class="pdf-viewer" @loaded="onPdfLoaded" @loading-failed="onPdfError" />
        <img v-else-if="fileType === 'image' && blobUrl" :src="blobUrl" class="image-viewer" />
        <div v-else class="file-preview-empty">
          {{ $t('msg.noPreview') || '暂不支持预览该类型' }}
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<script setup>
import { ref, watch } from "vue";
import VuePdfEmbed from "vue-pdf-embed";
import { ArrowLeft, ArrowRight, Download, ZoomIn, ZoomOut } from "@element-plus/icons-vue";

const props = defineProps({
  visible: { type: Boolean, default: false },
  blobUrl: { type: String, default: "" },
  fileName: { type: String, default: "" },
  fileType: { type: String, default: "" }, // 'pdf' | 'image' | 'other'
  // 用于下载：传完整 Blob（推荐），不传则用 blobUrl 抓
  blob: { type: Blob, default: null },
});

const emit = defineEmits(["update:visible", "close", "download"]);

const loading = ref(false);
const currentPage = ref(1);
const totalPages = ref(0);
const pageScale = ref(1);

// 弹窗关闭时清理状态
const handleClose = () => {
  emit("update:visible", false);
  emit("close");
};

// 接收父组件传来的下载动作（由父组件负责 downloadBlob + 文件名）
const handleDownload = () => {
  emit("download", { blob: props.blob, blobUrl: props.blobUrl, fileName: props.fileName });
};

// PDF 加载完成回填总页数
const onPdfLoaded = (pdfDoc) => {
  loading.value = false;
  totalPages.value = pdfDoc?.numPages || 0;
  currentPage.value = 1;
};

const onPdfError = (err) => {
  loading.value = false;
  console.error("PDF 加载失败:", err);
};

const prevPage = () => {
  if (currentPage.value > 1) currentPage.value -= 1;
};

const nextPage = () => {
  if (currentPage.value < totalPages.value) currentPage.value += 1;
};

const scaleDown = () => {
  if (pageScale.value > 0.5) pageScale.value = Math.round((pageScale.value - 0.25) * 100) / 100;
};

const scaleUp = () => {
  if (pageScale.value < 2.5) pageScale.value = Math.round((pageScale.value + 0.25) * 100) / 100;
};

// visible 变化时控制 loading
watch(
  () => props.visible,
  (v) => {
    if (v) {
      loading.value = props.fileType === "pdf";
      currentPage.value = 1;
      totalPages.value = 0;
      pageScale.value = 1;
    }
  },
);
</script>

<style scoped lang="scss">
.file-preview-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
  width: 100%;
  padding-right: 8px;
  margin-bottom: 12px;
}

.file-preview-title {
  flex: 1;
  font-size: 16px;
  font-weight: 500;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.file-preview-tools {
  display: flex;
  align-items: center;
  gap: 6px;
  flex-shrink: 0;
}

.scale-text,
.page-text {
  min-width: 48px;
  text-align: center;
  font-size: 13px;
  color: #606266;
}

.file-preview-body {
  min-height: 60vh;
  max-height: 80vh;
  overflow: auto;
  background: #f5f7fa;
  border-radius: 4px;
  padding: 8px;
  display: flex;
  justify-content: center;
  align-items: flex-start;
}

.pdf-viewer {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
}

.image-viewer {
  max-width: 100%;
  max-height: 75vh;
  object-fit: contain;
  display: block;
  margin: auto;
}

.file-preview-empty {
  width: 100%;
  text-align: center;
  color: #909399;
  padding: 60px 0;
}
</style>
<style>
.file-preview-dialog {
  width: 80% !important;

  .close-btn {
    width: 30px;
    height: 30px;
    margin-left: 30px;
    cursor: pointer;
  }
}
</style>