<template>
  <div class="material-actions">
    <el-button v-if="material && previewable" class="material-button" @click="previewVisible = true">
      <el-icon><View /></el-icon>预览案例资料
    </el-button>
    <el-button class="material-button" :plain="!material?.url" @click="handleDownload">
      <el-icon><Download /></el-icon>下载案例资料
    </el-button>
  </div>

  <el-dialog v-model="previewVisible" :title="material?.name || '案例资料预览'" width="min(920px, 92vw)" destroy-on-close append-to-body>
    <div v-if="isImage" class="image-preview"><img :src="material.url" :alt="material.name" /></div>
    <iframe v-else-if="isPdf" class="pdf-preview" :src="material.url" :title="material.name"></iframe>
  </el-dialog>
</template>

<script setup>
import { computed, ref } from "vue";
import { ElMessage } from "element-plus";
import { Download, View } from "@element-plus/icons-vue";

const props = defineProps({ materialName: { type: String, default: "" }, materialUrl: { type: String, default: "" } });
const previewVisible = ref(false);
const material = computed(() => {
  const name = String(props.materialName || "").trim();
  const url = String(props.materialUrl || "").trim();
  if (!name || !url || (name === "案例资料.rar" && url === "/file/example.rar")) return null;
  return { name, url };
});
const extension = computed(() => String(material.value?.name || material.value?.url || "").split(/[?#]/)[0].split(".").pop().toLowerCase());
const isImage = computed(() => ["jpg", "jpeg", "png", "gif", "webp", "bmp", "svg"].includes(extension.value));
const isPdf = computed(() => extension.value === "pdf");
const previewable = computed(() => isImage.value || isPdf.value);

function handleDownload() {
  if (!material.value?.url) { ElMessage.warning("暂无案例资料"); return; }
  const link = document.createElement("a");
  link.href = material.value.url;
  link.target = "_blank";
  link.rel = "noopener";
  link.download = material.value.name;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
  if (!previewable.value) ElMessage.info("该文件类型暂不支持在线预览，已为您打开下载。");
}
</script>

<style lang="scss" scoped>
.material-actions{display:flex;flex-wrap:wrap;gap:10px}.material-button{display:inline-flex;align-items:center;justify-content:center;gap:8px;min-height:40px;padding:0 16px;border-color:rgba(99,217,255,.55);border-radius:9px;color:#e9fbff;background:rgba(17,126,178,.36);font-size:14px;font-weight:800}.material-button:hover{color:#e9fbff;border-color:rgba(116,235,255,.85);background:rgba(18,146,204,.5)}.image-preview{display:flex;justify-content:center;max-height:68vh;overflow:auto;background:#0b1720}.image-preview img{display:block;max-width:100%;height:auto;object-fit:contain}.pdf-preview{width:100%;height:68vh;border:0;background:#fff}
</style>
