<template>
  <div class="hospital-list">
    <el-card shadow="never">
      <el-form :inline="true" :model="filters" class="filter-form">
        <el-form-item :label="$t('label.hospitalSearch')">
          <el-input
            v-model="filters.keyword"
            :placeholder="$t('placeholder.hospital')"
            clearable
            style="width: 220px"
          />
        </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-form-item>
          <el-button type="primary" @click="onSearch">{{ $t('btn.query') }}</el-button>
          <el-button @click="onReset">{{ $t('btn.reset') }}</el-button>
          <el-button type="success" @click="goAdd">{{ $t('btn.addHospital') }}</el-button>
        </el-form-item>
      </el-form>

      <el-table :data="list" v-loading="loading" border stripe>
        <!-- <el-table-column prop="id" label="ID" width="80" /> -->
        <el-table-column
          :label="$t('table.hospital')"
          prop="name"
          min-width="180"
          show-overflow-tooltip
        />
        <el-table-column :label="$t('label.category')" prop="customerCategory" width="100" />
        <el-table-column :label="$t('table.contact')" prop="contactPerson" width="100" />
        <el-table-column :label="$t('table.phone')" prop="contactPhone" width="140" />
        <el-table-column :label="$t('table.manager')" prop="managerName" width="140" />
        <el-table-column :label="$t('table.usageYears')" width="140">
          <template #default="{ row }">{{ formatUsageYears(row.signDate) }}</template>
        </el-table-column>
        <el-table-column :label="$t('table.acceptanceReport')" width="140">
          <template #default="{ row }">
            <el-button
              v-if="row.attachmentPath"
              link
              type="primary"
              @click="viewReport(row.attachmentPath)"
            >
              {{ $t('btn.preview') }}
            </el-button>
            <span v-else>—</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('table.signDate')" width="120">
          <template #default="{ row }">{{ formatDate(row.signDate) }}</template>
        </el-table-column>
        <el-table-column :label="$t('table.maintenanceEnd')" width="120">
          <template #default="{ row }">{{ formatDate(row.maintenanceEnd) }}</template>
        </el-table-column>
        <el-table-column :label="$t('table.action')" width="160" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="goDetail(row.id)">{{ $t('btn.detail') }}</el-button>
            <el-button link type="primary" @click="goEdit(row.id)">{{ $t('btn.edit') }}</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>
    </el-card>

    <el-dialog
      v-model="previewVisible"
      :title="$t('btn.preview')"
      width="80%"
      top="5vh"
      destroy-on-close
      :before-close="closePreview"
    >
      <iframe
        v-if="previewUrl"
        :src="previewUrl"
        class="preview-iframe"
      />
    </el-dialog>
  </div>
</template>

<script setup>
import { onMounted, reactive, ref } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import dayjs from "dayjs";
import { useI18n } from "vue-i18n";
import { getAdminHospitals, getUploadFile } from "@/service/modular/admin";

const { t: $t } = useI18n();
const router = useRouter();
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 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 goDetail = (id) => router.push(`/admin/hospitals/detail/${id}`);
const goEdit = (id) => router.push(`/admin/hospitals/edit/${id}`);
const goAdd = () => router.push("/admin/hospitals/edit");

const previewVisible = ref(false);
const previewUrl = ref("");

const cleanupPreviewUrl = () => {
  if (previewUrl.value) {
    URL.revokeObjectURL(previewUrl.value);
    previewUrl.value = "";
  }
};

const closePreview = () => {
  previewVisible.value = false;
  cleanupPreviewUrl();
};

const viewReport = async (attachmentPath) => {
  if (!attachmentPath) return;
  const fileName = String(attachmentPath);
  try {
    const blob = await getUploadFile(fileName);
    cleanupPreviewUrl();
    previewUrl.value = URL.createObjectURL(blob);
    previewVisible.value = true;
  } catch (e) {
    ElMessage.error(e?.message || $t('msg.failed'));
  }
};

onMounted(loadList);
</script>

<style scoped lang="scss">
.filter-form {
  margin-bottom: 12px;
}
.pagination {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}
.preview-iframe {
  width: 100%;
  height: 80vh;
  border: 0;
}
</style>
