<template>
  <el-dialog :model-value="modelValue" class="report-download-dialog" top="20vh" :close-on-click-modal="true"
    @update:model-value="(v) => $emit('update:modelValue', v)" @closed="onClosed">
    <div class="body-wrap">
      <div class="body-header">
        <div class="body-title">选择下载格式</div>
        <img src="@/assets/image/close-btn.svg" alt="" class="close-btn" @click="closeDialog" />
      </div>

      <div class="format-grid">
        <div v-for="fmt in formats" :key="fmt.key" class="format-card" :class="{ active: selected === fmt.key }"
          @click="onPick(fmt)">
          <div class="format-icon">
            <img :src="fmt.icon" :alt="fmt.label" />
          </div>
          <div class="format-label">{{ fmt.label }}</div>
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<script setup>
import { ref } from "vue";
import { ElMessage } from "element-plus";
import { downloadAdminReport } from "@/service/modular/admin";
import iconWord from "@/assets/image/admin/reports/word-icon.svg";
import iconPdf from "@/assets/image/admin/reports/pdf-icon.svg";

const props = defineProps({
  modelValue: { type: Boolean, default: false },
  reportId: { type: [String, Number], default: "" },
});
const emit = defineEmits(["update:modelValue", "downloaded", "exportPdf", "exportDocx"]);

const formats = [
  { key: "word", label: "下载WORD格式", icon: iconWord, ext: "doc" },
  { key: "pdf", label: "下载PDF格式", icon: iconPdf, ext: "pdf" },
];

const selected = ref("");
const downloading = ref(false);

const closeDialog = () => emit("update:modelValue", false);
const onClosed = () => {
  selected.value = "";
};

const downloadBlob = (blob, fileName) => {
  const url = URL.createObjectURL(blob);
  const a = document.createElement("a");
  a.href = url;
  a.download = fileName || "download";
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  setTimeout(() => URL.revokeObjectURL(url), 0);
};

/**
 * 选中某个格式:
 *  - pdf: 触发 exportPdf 事件,由父组件调用详情框(ref)执行前端截图导出
 *  - word: 走后端 blob 下载,保持原逻辑不变
 */
const onPick = (fmt) => {
  selected.value = fmt.key;
  if (fmt.key === "pdf") {
    if (!props.reportId) {
      ElMessage.warning("报告不存在");
      return;
    }
    emit("exportPdf", { reportId: props.reportId });
    closeDialog();
    return;
  }
  onConfirm();
};

const onConfirm = async () => {
  if (!props.reportId) {
    ElMessage.warning("报告不存在");
    return;
  }
  const fmt = formats.find((f) => f.key === selected.value);
  downloading.value = true;
  try {
    // Word 格式:改用前端截图导出(emit 给父组件,由 ReportDetailDialog 处理)
    if (selected.value === "word") {
      emit("exportDocx", { reportId: props.reportId });
      closeDialog();
      return;
    }
    const blob = await downloadAdminReport(props.reportId, selected.value);
    const fileName = `report-${props.reportId}.${fmt?.ext || selected.value}`;
    downloadBlob(blob, fileName);
    ElMessage.success("下载已开始");
    emit("downloaded", { format: selected.value });
    closeDialog();
  } catch (e) {
    ElMessage.error(e?.message || "下载失败");
  } finally {
    downloading.value = false;
  }
};
</script>

<style lang="scss">
.report-download-dialog {
  overflow: hidden;

  .format-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 24px;
  }

  .format-card {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    gap: 12px;
    width: 358px;
    height: 158px;
    background: #F9FAFF;
    border-radius: 16px 16px 16px 16px;
    border: 1px solid #E0E0E0;
    cursor: pointer;
    transition: all 0.2s ease;

    &:hover {
      border-color: #4f8cff;
      background: #f0f6ff;
    }

    &.active {
      border-color: #4f8cff;
      background: #f0f6ff;
      box-shadow: 0 4px 14px rgba(79, 140, 255, 0.18);
    }

    .format-icon {
      width: 70px;
      height: 70px;
      display: flex;
      align-items: center;
      justify-content: center;

      img {
        width: 100%;
        height: 100%;
        object-fit: contain;
      }
    }

    .format-label {
      font-weight: 600;
      font-size: 16px;
      color: #1D2129;
    }
  }
}
</style>