<template>
  <div class="hospital-list admin-page-card">
    <el-form :inline="true" :model="filters" class="filter-form">
      <el-form-item :label="$t('label.hospitalSearch')">
        <el-select v-model="filters.keyword" placeholder="全部医院" clearable filterable style="width: 220px">
          <el-option v-for="h in hospitals" :key="h.id" :label="h.name" :value="h.name" />
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('label.category')">
        <el-select v-model="filters.category" :placeholder="$t('common.all')" clearable style="width: 140px">
          <el-option label="A类客户（活跃）" value="A" />
          <el-option label="B类客户（不活跃）" value="B" />
          <el-option label="C类客户（待挽回）" value="C" />
        </el-select>
      </el-form-item>
      <el-button type="primary" plain class="blue-sign" @click="onSearch">{{ $t('btn.query') }}</el-button>
      <el-button @click="onReset">{{ $t('btn.reset') }}</el-button>
      <el-button type="primary" class="add-btn" @click="goAdd">{{ $t('btn.addHospital') }}</el-button>
    </el-form>

    <el-table class="admin-table" :data="list" v-loading="loading" header-cell-class-name="admin-table-header-cell"
      stripe>
      <!-- <el-table-column prop="id" label="ID" width="80" /> -->
      <el-table-column :label="$t('table.hospital')" prop="name" min-width="140" show-overflow-tooltip />
      <el-table-column :label="$t('label.category')" width="auto">
        <template #default="{ row }">
          <div class="cat-tag" :class="`cat-${row.customerCategory}`">
            {{ row.customerCategory || "—" }}类
          </div>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.contact')" prop="contactPerson" width="auto" />
      <el-table-column :label="$t('table.phone')" prop="contactPhone" :min-width="getPhoneMinWidth()"
        show-overflow-tooltip />
      <el-table-column :label="$t('table.manager')" prop="managerName" width="auto" />
      <el-table-column :label="$t('table.signDate')" width="auto">
        <template #default="{ row }">{{ formatDate(row.signDate) }}</template>
      </el-table-column>
      <el-table-column :label="'客户使用年限'" width="auto">
        <template #default="{ row }">{{ formatUsageYears(row.signDate) }}</template>
      </el-table-column>
      <el-table-column :label="$t('table.maintenanceEnd')" width="auto">
        <template #default="{ row }">{{ formatDate(row.maintenanceEnd) }}</template>
      </el-table-column>
      <el-table-column :label="$t('table.acceptanceReport')" width="auto">
        <template #default="{ row }">
          <el-button v-if="row.attachmentPath" plain class="cyan-sign" @click="viewReport(row.attachmentPath)">
            {{ $t('btn.preview') }}
          </el-button>
          <span v-else>—</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.action')" width="160" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" plain class="purple-sign smaller" @click="goEdit(row.id)">{{ $t('btn.edit') }}</el-button>
          <el-button type="primary" plain class="blue-sign smaller" @click="goDetail(row.id)">{{ $t('btn.detail') }}</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <el-pagination v-model:current-page="page" v-model:page-size="pageSize" :page-sizes="[10, 20, 50]" :total="total"
        layout="total, sizes, prev, pager, next, jumper" @size-change="loadList" @current-change="loadList" />
    </div>
    <FilePreviewDialog :visible="previewVisible" :blob-url="previewUrl" :blob="previewBlob" :file-name="previewName"
      :file-type="previewType" @update:visible="(v) => (previewVisible = v)" @close="cleanupPreview"
      @download="onPreviewDownload" />

    <HospitalDetailDialog v-model:visible="detailVisible" :hospital-id="detailId" @edit="onGoEdit" />

    <HospitalEditDialog v-model:visible="editVisible" :hospital-id="editId" @success="loadList" />
  </div>
</template>

<script setup>
import { onMounted, reactive, ref, computed } from "vue";
import { ElMessage } from "element-plus";
import dayjs from "dayjs";
import { useI18n } from "vue-i18n";
import { getAdminHospitals, getUploadFile } from "@/service/modular/admin";
import FilePreviewDialog from "@/components/FilePreviewDialog.vue";
import HospitalDetailDialog from "./components/HospitalDetailDialog.vue";
import HospitalEditDialog from "./components/HospitalEditDialog.vue";

import { useHospitalStore } from "@/stores/api/hospital";
// 通用医院列表（来自 Pinia store，多页面共享缓存）
const hospitalStore = useHospitalStore();
const hospitals = computed(() => hospitalStore.list);


const { t: $t } = useI18n();
const list = ref([]);
const total = ref(0);
const page = ref(1);
const pageSize = ref(10);
const loading = ref(false);
const filters = reactive({ keyword: "", category: "" });

const getPhoneMinWidth = () => {
  const rootStyle = getComputedStyle(document.documentElement);
  const remBase = parseFloat(rootStyle.fontSize) || 16;
  const elFontSizeBase = parseFloat(rootStyle.getPropertyValue('--el-font-size-base')) || 1;
  const minWidthRem = remBase * elFontSizeBase * 12 * 0.56 + 24; // 10个数字 + padding，数字实际更窄
  return `${minWidthRem.toFixed(4)}px`;
};

const formatDate = (v) => (v ? dayjs(v).format("YYYY-MM-DD") : "—");

// 从签约日期到今天的使用年限，按"X年X天"展示
const formatUsageYears = (signDate) => {
  if (!signDate) return "—";
  const start = dayjs(signDate);
  const now = dayjs();
  if (start.isAfter(now)) return "—";
  const totalDays = now.diff(start, "day");
  const years = Math.floor(totalDays / 365);
  const days = totalDays - years * 365;
  return `${years}年${days}天`;
};

const loadList = async () => {
  loading.value = true;
  try {
    const res = await getAdminHospitals({
      page: page.value,
      pageSize: pageSize.value,
      ...filters,
    });
    list.value = res?.list || [];
    total.value = res?.total || 0;
  } finally {
    loading.value = false;
  }
};

const onSearch = () => {
  page.value = 1;
  loadList();
};
const onReset = () => {
  filters.keyword = "";
  filters.category = "";
  onSearch();
};

// 详情 / 新增 / 编辑均通过弹窗打开，不再走路由跳转
const detailVisible = ref(false);
const detailId = ref("");
const editVisible = ref(false);
const editId = ref("");

const goDetail = (id) => {
  detailId.value = id;
  detailVisible.value = true;
};
const goEdit = (id) => {
  editId.value = id;
  editVisible.value = true;
};
const goAdd = () => {
  editId.value = "";
  editVisible.value = true;
};
// 从详情弹窗跳到编辑：先关详情，再开编辑
const onGoEdit = (id) => {
  detailVisible.value = false;
  goEdit(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 = "";
};

// 从路径中提取最后的文件名（含扩展名）作为下载名
const getFileNameFromPath = (path) => {
  if (!path) return "";
  return String(path).replace(/\\/g, "/").split("/").filter(Boolean).pop() || "";
};

// 根据文件名/扩展名+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) => {
  if (!attachmentPath) return;
  const path = String(attachmentPath);
  const downloadName = getFileNameFromPath(path) || path;
  try {
    const blob = await getUploadFile(path);
    const type = getFileType(downloadName, blob);
    // PDF / 图片走预览弹窗（PDF 走 vue-pdf-embed），其他格式直接下载
    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(() => {
  hospitalStore.ensureLoaded();
  loadList();
});
</script>

<style scoped lang="scss">
.hospital-list {
  .filter-form {
    display: flex;
    margin-bottom: 12px;

    .add-btn {
      margin-left: auto;
    }
  }

  .cat-tag {
    width: 48px;
    height: 30px;
    border-radius: 8px 8px 8px 8px;
    line-height: 30px;
    text-align: center;
    font-weight: 500;
    font-size: 14px;

    &.cat-A {
      background: #EAF3FF;
      color: #3289FB;
    }

    &.cat-B {
      background: #E8FFEE;
      color: #34C759;
    }

    &.cat-C {
      background: #FFEFE2;
      color: #FF8D28;
    }
  }
}


.pagination {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}

.preview-iframe {
  width: 100%;
  height: 80vh;
  border: 0;
}

:deep(.contact-phone) {

  // width: 120em !important;
  .cell {
    white-space: nowrap;
  }
}
</style>

<style lang="scss">
@use "@/assets/style/admin-common.scss" as *;
</style>
