<script lang="ts" setup>
/**
 * 部门财务列表：C 端卡片网格 + ExcelJS 前端导出
 */
import { onMounted, ref } from 'vue';

import { Page } from '@vben/common-ui';

import { Button, Empty, Pagination, Spin, message } from 'ant-design-vue';

import { getDepartmentFinanceReportListApi } from '#/views/finance/department-finance/api';
import { buildAndDownloadDepartmentFinanceExcel } from '#/views/finance/department-finance/utils/exportDepartmentFinanceExcel';

import ConfigModal from './components/ConfigModal.vue';
import GenerateReportModal from './components/GenerateReportModal.vue';
import ReportDetailDrawer from './components/ReportDetailDrawer.vue';

const loading = ref(false);
const list = ref<any[]>([]);
const pagination = ref({ current: 1, pageSize: 12, total: 0 });
/** 当前正在导出的报表 id，用于卡片按钮 loading */
const exportingId = ref<number | null>(null);

const reportDetailDrawerRef = ref<InstanceType<typeof ReportDetailDrawer>>();
const configModalRef = ref<InstanceType<typeof ConfigModal>>();
const generateReportModalRef = ref<InstanceType<typeof GenerateReportModal>>();

/** 金额展示：千分位 + 两位小数 */
function formatMoney(value: unknown): string {
  const n = Number(value);
  if (!Number.isFinite(n)) return '—';
  return n.toLocaleString(undefined, {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2,
  });
}

/** 拉取报表列表 */
async function fetchList(page = pagination.value.current) {
  loading.value = true;
  try {
    const res = await getDepartmentFinanceReportListApi({
      page,
      pageSize: pagination.value.pageSize,
    });
    const data = res.list ?? res;
    list.value = data?.items ?? [];
    pagination.value = {
      current: data?.page ?? page,
      pageSize: data?.size ?? pagination.value.pageSize,
      total: data?.total ?? 0,
    };
  } finally {
    loading.value = false;
  }
}

/** 打开手动生成弹窗 */
function handleGenerate() {
  generateReportModalRef.value?.open();
}

/** 生成成功后刷新列表 */
function onGenerateSuccess() {
  fetchList(1);
}

/** 查看报表详情 */
function openDetail(id: number) {
  reportDetailDrawerRef.value?.open(id);
}

/**
 * 导出报表：拉详情 + 药品明细 → ExcelJS 美化生成 → 下载
 */
async function handleExport(id: number) {
  if (exportingId.value != null) return;
  exportingId.value = id;
  const hide = message.loading('正在生成 Excel…', 0);
  try {
    await buildAndDownloadDepartmentFinanceExcel(id);
    message.success('导出成功');
  } catch (e: any) {
    message.error(e?.message || '导出失败');
  } finally {
    hide();
    exportingId.value = null;
  }
}

function openConfig() {
  configModalRef.value?.open();
}

/** 分页切换 */
function onPageChange(page: number, pageSize: number) {
  pagination.value.pageSize = pageSize;
  fetchList(page);
}

onMounted(() => {
  fetchList();
});
</script>

<template>
  <Page auto-content-height title="部门财务">
    <ReportDetailDrawer ref="reportDetailDrawerRef" />
    <ConfigModal ref="configModalRef" />
    <GenerateReportModal
      ref="generateReportModalRef"
      @success="onGenerateSuccess"
    />
    <div class="mb-4 flex flex-wrap gap-2">
      <Button type="primary" @click="handleGenerate">手动生成报表</Button>
      <Button @click="openConfig">生成配置</Button>
      <Button @click="fetchList()">刷新</Button>
    </div>
    <Spin :spinning="loading">
      <div v-if="list.length" class="df-card-grid">
        <div
          v-for="item in list"
          :key="item.id"
          class="df-card"
        >
          <div class="df-card__main">
            <div class="df-card__title">{{ item.report_no }}</div>
            <div class="df-card__meta">
              <span>统计区间</span>
              <span>{{ item.period_start }} ~ {{ item.period_end }}</span>
            </div>
            <div class="df-card__meta">
              <span>生成时间</span>
              <span>{{ item.generated_at }}</span>
            </div>
            <div class="df-card__amount">
              <span class="df-card__amount-label">开票合计</span>
              <span class="df-card__amount-value">
                ¥{{ formatMoney(item.invoice_total) }}
              </span>
            </div>
          </div>
          <div class="df-card__footer">
            <Button size="small" @click="openDetail(item.id)">详情</Button>
            <Button
              size="small"
              type="primary"
              :loading="exportingId === item.id"
              @click="handleExport(item.id)"
            >
              导出
            </Button>
          </div>
        </div>
      </div>
      <Empty v-else-if="!loading" description="暂无部门财务报表" />
    </Spin>
    <div
      v-if="pagination.total > 0"
      class="mt-4 flex justify-end"
    >
      <Pagination
        :current="pagination.current"
        :page-size="pagination.pageSize"
        :total="pagination.total"
        :page-size-options="['12', '24', '48']"
        show-size-changer
        show-quick-jumper
        @change="onPageChange"
      />
    </div>
  </Page>
</template>

<style scoped>
.df-card-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 16px;
}
.df-card {
  display: flex;
  flex-direction: column;
  overflow: hidden;
  background: #fff;
  border: 1px solid #e5e7eb;
  border-radius: 12px;
  box-shadow: 0 1px 2px rgb(15 23 42 / 4%);
  transition:
    box-shadow 0.2s ease,
    border-color 0.2s ease;
}
.dark .df-card {
  background: #0f172a;
  border-color: #334155;
}
.df-card:hover {
  border-color: #93c5fd;
  box-shadow: 0 6px 16px rgb(15 23 42 / 8%);
}
.df-card__main {
  flex: 1;
  padding: 16px 16px 12px;
}
.df-card__title {
  margin-bottom: 12px;
  font-size: 16px;
  font-weight: 600;
  color: #1f4e79;
  letter-spacing: 0.02em;
}
.dark .df-card__title {
  color: #93c5fd;
}
.df-card__meta {
  display: flex;
  gap: 8px;
  justify-content: space-between;
  margin-bottom: 6px;
  font-size: 13px;
  color: #64748b;
}
.df-card__meta > span:last-child {
  color: #334155;
  text-align: right;
}
.dark .df-card__meta > span:last-child {
  color: #cbd5e1;
}
.df-card__amount {
  display: flex;
  align-items: baseline;
  justify-content: space-between;
  margin-top: 14px;
  padding-top: 12px;
  border-top: 1px dashed #e2e8f0;
}
.dark .df-card__amount {
  border-top-color: #1e293b;
}
.df-card__amount-label {
  font-size: 13px;
  color: #64748b;
}
.df-card__amount-value {
  font-size: 22px;
  font-weight: 700;
  line-height: 1.2;
  color: #2563eb;
}
.dark .df-card__amount-value {
  color: #60a5fa;
}
.df-card__footer {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
  padding: 10px 16px 12px;
  background: #fafafa;
  border-top: 1px solid #f1f5f9;
}
.dark .df-card__footer {
  background: #0b1220;
  border-top-color: #1e293b;
}
</style>
