<template>
  <div class="report-page" v-loading="exporting" :element-loading-text="exporting ? `正在生成 ${exportTypeLabel}…` : ''" element-loading-background="rgba(255,255,255,0.7)">
    <div class="admin-page-card">
      <div class="filter-row">
        <el-form :inline="true" :model="filters" class="admin-filter-form">
          <el-form-item label="医院名称">
            <el-select v-model="filters.hospitalId" placeholder="全部医院" clearable filterable style="width: 200px">
              <el-option v-for="h in hospitals" :key="h.id" :label="h.name" :value="h.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="报告类型">
            <el-select v-model="filters.type" placeholder="全部类型" clearable style="width: 140px">
              <el-option label="季度报告" value="quarterly" />
              <el-option label="年度报告" value="annual" />
            </el-select>
          </el-form-item>

          <el-button class="blue-sign" type="primary" plain @click="onSearch">查询</el-button>
          <el-button @click="onReset">重置</el-button>
          <el-button class="blue-sign" type="primary" @click="generateVisible = true">生成报告</el-button>
        </el-form>
      </div>

      <el-table class="admin-table" :data="list" v-loading="loading" stripe
        header-cell-class-name="admin-table-header-cell">
        <el-table-column label="序号" type="index" width="80" />
        <el-table-column label="医院名称" prop="hospital" min-width="100" show-overflow-tooltip />
        <el-table-column label="报告类型" width="110">
          <template #default="{ row }">
            <div class="type-tag" :class="row.type">{{ typeLabel(row.type) }}</div>
          </template>
        </el-table-column>
        <el-table-column label="报告周期" prop="period" width="140" />
        <el-table-column label="生成时间" prop="date" width="170" />
        <el-table-column label="发送状态" width="120">
          <template #default="{ row }">
            <div class="status-dot" :class="row.sent ? 'success' : 'pending'">
              {{ row.sent ? "已发客户" : "待发客户" }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="备注/内容" prop="remark" min-width="160" show-overflow-tooltip>
          <template #default="{ row }">
            <span>{{ row.remark || "—" }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="240" fixed="right">
          <template #default="{ row }">
            <el-button class="op-btn purple-sign smaller" plain type="primary" @click="openView(row)">查看</el-button>
            <el-button class="op-btn rosein-sign smaller" plain type="warning" @click="openDownload(row)">下载</el-button>
            <el-button class="op-btn blue-sign smaller" plain type="success" @click="openRemark(row)">备注</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="admin-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>
    </div>

        <!-- 下载格式选择 -->
    <ReportDownloadDialog v-model="downloadVisible" :report-id="currentReportId" @downloaded="onDownloaded" @exportPdf="onExportPdf" @exportDocx="onExportDocx" />

    <!-- 编辑备注 -->
    <ReportRemarkDialog v-model="remarkVisible" :report-row="currentReportRow" @saved="loadList" />

    <!-- 报告详情 (silent 模式下不可见,仅供 PDF 截图使用) -->
    <ReportDetailDialog ref="detailDialogRef" v-model="detailVisible" :silent="silentExport" :report-row="currentReportRow" :report-id="currentReportId" @download="openDownloadById" @exportDocx="onExportDocx" />

    <!-- 生成报告 -->
    <ReportGenerateDialog v-model="generateVisible" @generated="onGenerated" />
  </div>
</template>

<script setup>
import { computed, nextTick, onMounted, reactive, ref } from "vue";
import { ElMessage } from "element-plus";
import { QuestionFilled } from "@element-plus/icons-vue";
import { useI18n } from "vue-i18n";
import { getAdminReports, toggleAdminReportSendStatus } from "@/service/modular/admin";
import { useHospitalStore } from "@/stores/api/hospital";
import ReportDownloadDialog from "./components/ReportDownloadDialog.vue";
import ReportRemarkDialog from "./components/ReportRemarkDialog.vue";
import ReportDetailDialog from "./components/ReportDetailDialog.vue";
import ReportGenerateDialog from "./components/ReportGenerateDialog.vue";

const { t: $t } = useI18n();
const hospitalStore = useHospitalStore();
const hospitals = computed(() => hospitalStore.list);

const list = ref([]);
const total = ref(0);
const page = ref(1);
const pageSize = ref(10);
const loading = ref(false);
const filters = reactive({ type: "", hospitalId: undefined });

// type / status 文本
const typeLabel = (t) => (t === "annual" ? "年度报告" : "季度报告");
const loadList = async () => {
  loading.value = true;
  try {
    const params = {
      page: page.value,
      pageSize: pageSize.value,
      type: filters.type || undefined,
      hospitalId: filters.hospitalId || undefined,
    };
    const res = await getAdminReports(params);
    list.value = res?.list || [];
    total.value = res?.total || list.value.length;
  } catch (e) {
    list.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};

const onSearch = () => {
  page.value = 1;
  loadList();
};

const onReset = () => {
  filters.type = "";
  filters.hospitalId = undefined;
  onSearch();
};

const onGenerated = () => {
  loadList();
};

// 弹窗状态
const currentReportId = ref("");
const currentReportRow = ref(null);
const detailVisible = ref(false);
const downloadVisible = ref(false);
const remarkVisible = ref(false);
const generateVisible = ref(false);

// PDF 静默导出:打开详情框但不展示给用户,DOM 在屏幕外渲染供 html2canvas 截图
const detailDialogRef = ref(null);
const silentExport = ref(false);
const exporting = ref(false);
const exportTypeLabel = ref("PDF");

/**
 * 处理 PDF 导出(由 ReportDownloadDialog 在选中 PDF 时触发)
 * 流程:静默打开详情框 -> 等待数据加载 -> 截图导出 -> 仅关闭 silent 触发的打开
 */
const onExportPdf = async ({ reportId } = {}) => {
  const targetId = reportId || currentReportId.value;
  if (!targetId) {
    ElMessage.warning("报告不存在");
    return;
  }
  // 找到对应行(用于生成文件名)
  const row =
    list.value.find((r) => r.id === targetId) ||
    currentReportRow.value ||
    null;
        currentReportId.value = targetId;
  currentReportRow.value = row;
    // 记录导出前的可见状态:如果原本就是开的,导出后不要关掉它
  const wasDetailVisible = detailVisible.value;
  // silent 仅在原本不可见时才开启(用户看不见弹窗),避免把已打开的详情框藏起来
  silentExport.value = !wasDetailVisible;
  if (!wasDetailVisible) {
    detailVisible.value = true;
  }
  // 全屏 loading
  exportTypeLabel.value = "PDF";
  exporting.value = true;
  await nextTick();
  // 等待 ref 与组件内部 loadDetail 就绪(详情框 onOpen 触发 loadDetail 是异步的)
  for (let i = 0; i < 20 && !detailDialogRef.value?.handleExportPdf; i++) {
    await new Promise((r) => setTimeout(r, 50));
  }
  try {
    if (detailDialogRef.value?.handleExportPdf) {
      await detailDialogRef.value.handleExportPdf(targetId, row);
    } else {
      ElMessage.error("报告组件未就绪,请重试");
    }
  } catch (e) {
    console.error("[report] PDF 导出失败:", e);
  } finally {
    silentExport.value = false;
    exporting.value = false;
    // 只有原本就是关闭状态(silent 触发的打开)才关掉
    if (!wasDetailVisible) {
      detailVisible.value = false;
    }
  }
};

const openView = (row) => {
  currentReportId.value = row.id;
  currentReportRow.value = row;
  detailVisible.value = true;
};

/**
 * 处理 Word(docx)导出(由 ReportDownloadDialog 在选中 WORD 时触发)
 * 流程与 onExportPdf 完全一致:静默打开详情框 -> 等待数据加载 -> 截图导出 -> 关闭
 */
const onExportDocx = async ({ reportId } = {}) => {
  const targetId = reportId || currentReportId.value;
  if (!targetId) {
    ElMessage.warning("报告不存在");
    return;
  }
  const row =
    list.value.find((r) => r.id === targetId) ||
    currentReportRow.value ||
    null;
  currentReportId.value = targetId;
  currentReportRow.value = row;
    const wasDetailVisible = detailVisible.value;
  silentExport.value = !wasDetailVisible;
  if (!wasDetailVisible) {
    detailVisible.value = true;
  }
  exportTypeLabel.value = "Word";
  exporting.value = true;
  await nextTick();
  for (let i = 0; i < 20 && !detailDialogRef.value?.handleExportDocx; i++) {
    await new Promise((r) => setTimeout(r, 50));
  }
  try {
    if (detailDialogRef.value?.handleExportDocx) {
      await detailDialogRef.value.handleExportDocx(targetId, row);
    } else {
      ElMessage.error("报告组件未就绪,请重试");
    }
  } catch (e) {
    console.error("[report] Word 导出失败:", e);
  } finally {
    silentExport.value = false;
    exporting.value = false;
    if (!wasDetailVisible) {
      detailVisible.value = false;
    }
  }
};
const openDownload = (row) => {
  currentReportId.value = row.id;
  downloadVisible.value = true;
};
const openDownloadById = (row) => {
  if (row?.id) {
    currentReportId.value = row.id;
    downloadVisible.value = true;
  }
};
const openRemark = (row) => {
  currentReportRow.value = row;
  currentReportId.value = row?.id || "";
  remarkVisible.value = true;
};

const onDownloaded = async () => {
  // 下载成功后尝试切换发送状态为"已发送"
  try {
    await toggleAdminReportSendStatus(currentReportId.value);
    ElMessage.success("已切换为已发送");
    loadList();
  } catch (_) {
    // 即便后端未支持也不阻塞下载流
  }
};

onMounted(() => {
  hospitalStore.ensureLoaded();
  loadList();
});
</script>

<style scoped lang="scss">
.report-page {
  padding: 0;
}

.page-title-row {
  display: flex;
  align-items: center;
  gap: 6px;
  margin-bottom: 16px;

  .page-title {
    font-size: 18px;
    font-weight: 600;
    color: #1d2129;
  }

  .title-tip {
    color: #86909c;
    font-size: 16px;
    cursor: help;
  }
}

.filter-row {
  margin-bottom: 12px;

  .filter-row-label {
    font-size: 14px;
    color: #1d2129;
    margin-bottom: 8px;
    font-weight: 500;
    border-left: 3px solid #4f8cff;
    padding-left: 8px;
  }
}

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

  &.quarterly {
    background: #DEFEFF;
    color: #00C8B3;
  }

  &.annual {
    background: #EAF3FF;
    color: #3289FB;
  }
}

.status-dot {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  width: 92px;
  height: 30px;
  border-radius: 8px 8px 8px 8px;
  font-weight: 500;
  font-size: 14px;

  &::before {
    content: "";
    display: block;
    width: 8px;
    height: 8px;
    border-radius: 50%;
    background-color: var(--dot-bg);
  }

  &.success {
    background: #E8FFEE;
    color: #34C759;
    --dot-bg: #34C759;
  }

  &.pending {
    background: #FFEFE2;
    color: #FF8D28;
    --dot-bg: #FF8D28;
  }
}

.op-btn {
  margin-left: 12px;

  &:first-child {
    margin-left: 0;
  }
}
</style>

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