<template>
  <div class="order-detail" v-loading="loading">
    <el-page-header :icon="ArrowLeft" :content="$t('common.back')" @back="goBack" class="page-header">
      <template #content>
        <span class="page-title">{{ $t('modal.detail') }}</span>
      </template>
    </el-page-header>

    <el-card shadow="never" v-if="detail.id" class="detail-card">
      <template #header>
        <div class="card-header">
          <span class="title">{{ detail.title }}</span>
          <el-tag :type="priorityType(detail.priority)" size="small">{{ detail.priority }}</el-tag>
          <el-tag :type="statusType(detail.status)" size="small">{{ detail.status }}</el-tag>
          <el-button
            v-if="detail.status !== '已完成' && detail.status !== '已取消'"
            type="primary"
            size="small"
            style="margin-left:auto"
            @click="goEdit"
          >
            {{ $t('btn.edit') }}
          </el-button>
        </div>
      </template>

      <el-descriptions :column="3" border>
        <el-descriptions-item :label="$t('table.id')">{{ detail.orderNo }}</el-descriptions-item>
        <el-descriptions-item :label="$t('table.type')">{{ detail.serviceType }}</el-descriptions-item>
        <el-descriptions-item :label="$t('table.time')">{{ formatTime(detail.createdAt) }}</el-descriptions-item>
        <el-descriptions-item :label="$t('table.submitter')">{{ detail.submitter }}</el-descriptions-item>
        <el-descriptions-item :label="$t('label.dept')">{{ detail.department }}</el-descriptions-item>
      </el-descriptions>

      <div class="section">
        <div class="section-title">{{ $t('label.description') }}</div>
        <div class="html-content" v-html="detail.description || '—'" />
      </div>

      <div class="section">
        <div class="section-title">{{ $t('label.attachment') }} ({{ (detail.attachments || []).length }})</div>
        <el-empty v-if="!detail.attachments?.length" :description="$t('orderDetail.noAttachment')" :image-size="80" />
        <div v-else class="files">
          <el-button
            v-for="(f, i) in detail.attachments"
            :key="i"
            link
            type="primary"
            class="file-item"
            @click="viewReport(f.filePath, f.fileName)"
          >
            <el-icon><Document /></el-icon>{{ f.fileName }}
          </el-button>
        </div>
      </div>

      <div class="section">
        <div class="section-title">{{ $t('orderDetail.statusChange') }}</div>
        <el-timeline>
          <el-timeline-item
            v-for="(log, i) in detail.logs || []"
            :key="i"
            :timestamp="log.createdAt"
            placement="top"
          >
            <div class="log-title">{{ log.action }} · {{ log.operator }}</div>
            <div class="log-remark" v-html="log.remark"></div>
          </el-timeline-item>
        </el-timeline>
      </div>
    </el-card>

    <FilePreviewDialog
      :visible="previewVisible"
      :blob-url="previewUrl"
      :blob="previewBlob"
      :file-name="previewName"
      :file-type="previewType"
      @update:visible="(v) => (previewVisible = v)"
      @close="cleanupPreview"
      @download="onPreviewDownload"
    />
  </div>
</template>

<script setup>
import { onMounted, onBeforeUnmount, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ArrowLeft, Document } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import { useI18n } from "vue-i18n";
import { getHospitalOrderDetail } from "@/service/modular/hospital";
import { getUploadFile } from "@/service/modular/upload";
import FilePreviewDialog from "@/components/FilePreviewDialog.vue";
import { useOrderDialogStore } from "@/stores/orderDialog";

const { t: $t } = useI18n();
const route = useRoute();
const router = useRouter();
const loading = ref(false);
const detail = ref({});

const priorityType = (p) => (p === "高" ? "danger" : p === "中" ? "warning" : "info");
const statusType = (s) =>
  ({ 待处理: "warning", 处理中: "primary", 已完成: "success", 已取消: "info" })[s] || "info";

const formatTime = (val) => (val ? String(val).split("T").join(" ") : "");

const loadDetail = async () => {
  loading.value = true;
  try {
    detail.value = await getHospitalOrderDetail(route.params.id);
  } finally {
    loading.value = false;
  }
};

const goBack = () => router.back();
const orderDialogStore = useOrderDialogStore();
const goEdit = () => {
  orderDialogStore.openEdit(route.params.id);
};

// ============== 附件预览/下载 ==============
const previewVisible = ref(false);
const previewUrl = ref("");
const previewBlob = ref(null);
const previewName = ref("");
const previewType = ref(""); // 'pdf' | 'image' | ''

const cleanupPreview = () => {
  if (previewUrl.value) {
    URL.revokeObjectURL(previewUrl.value);
    previewUrl.value = "";
  }
  previewBlob.value = null;
  previewName.value = "";
  previewType.value = "";
};

// 根据文件名/扩展名+blob 的 mime 判断文件类型
const getFileType = (fileName, blob) => {
  const name = String(fileName || "");
  const ext = name.split(".").pop()?.toLowerCase() || "";
  const mime = blob?.type || "";
  if (ext === "pdf" || mime === "application/pdf") return "pdf";
  if (
    ["jpg", "jpeg", "png", "gif", "bmp", "webp", "svg"].includes(ext) ||
    (mime && mime.startsWith("image/"))
  ) {
    return "image";
  }
  return "other";
};

// 浏览器直接下载 blob（指定文件名）
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);
};

// FilePreviewDialog 下载按钮回调
const onPreviewDownload = ({ blob, fileName }) => {
  if (!blob) return;
  downloadBlob(blob, fileName);
};

const viewReport = async (attachmentPath, originalName) => {
  if (!attachmentPath) return;
  const path = String(attachmentPath);
  const downloadName = originalName || path;
  try {
    const blob = await getUploadFile(path);
    const type = getFileType(downloadName, blob);
    // PDF / 图片走预览弹窗，其他格式直接下载
    if (type === "pdf" || type === "image") {
      cleanupPreview();
      previewBlob.value = blob;
      previewUrl.value = URL.createObjectURL(blob);
      previewName.value = downloadName;
      previewType.value = type;
      previewVisible.value = true;
    } else {
      downloadBlob(blob, downloadName);
    }
  } catch (e) {
    ElMessage.error(e?.message || $t('msg.failed'));
  }
};

onMounted(loadDetail);
// 监听全局事件，编辑/快速提交后刷新详情
const onOrderSaved = () => loadDetail();
onMounted(() => {
  window.addEventListener("hospital-order-saved", onOrderSaved);
});
onBeforeUnmount(() => {
  window.removeEventListener("hospital-order-saved", onOrderSaved);
});
</script>

<style scoped lang="scss">
.page-header {
  margin-bottom: 12px;
  .page-title {
    font-size: 16px;
    font-weight: 600;
  }
}
.detail-card {
  .card-header {
    display: flex;
    align-items: center;
    gap: 8px;
    .title {
      font-size: 16px;
      font-weight: 600;
      margin-right: 8px;
    }
  }
  .section {
    margin-top: 20px;
    .section-title {
      font-size: 14px;
      font-weight: 600;
      color: #303133;
      margin-bottom: 10px;
    }
  }
  .html-content {
    background: #fafafa;
    padding: 12px;
    border-radius: 4px;
    min-height: 60px;
    line-height: 1.6;

    :deep(img) {
      max-width: 100% !important;
    }
  }
  .files {
    display: flex;
    flex-direction: column;
    gap: 8px;
    .file-item {
      display: inline-flex;
      align-items: center;
      gap: 4px;
    }
  }
  .log-title {
    font-weight: 600;
  }
  .log-remark {
    color: #606266;
    margin-top: 4px;
  }
}
</style>
