<script setup lang="ts">
/**
 * 文件职责：经营报表预览抽屉。
 */
import type { FinanceBusinessReportDetailDto } from '#/api/finance';

import { computed } from 'vue';

import { IconifyIcon } from '@vben/icons';

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

import {
  formatCurrency,
  formatPercent,
  formatSignedRate,
} from '../composables/report-page/helpers';

interface Props {
  canExport: boolean;
  detail: FinanceBusinessReportDetailDto | null;
  isDownloadingExcel: boolean;
  isDownloadingPdf: boolean;
  loading: boolean;
  open: boolean;
}

const props = defineProps<Props>();

const emit = defineEmits<{
  (event: 'close'): void;
  (event: 'downloadExcel'): void;
  (event: 'downloadPdf'): void;
}>();

const drawerTitle = computed(() => props.detail?.title || '经营报表预览');

const canDownload = computed(
  () => props.canExport && Boolean(props.detail?.reportId),
);

const incomeIconMap: Record<string, { icon: string; tone: string }> = {
  delivery: { icon: 'lucide:bike', tone: 'primary' },
  dine_in: { icon: 'lucide:utensils', tone: 'warning' },
  pickup: { icon: 'lucide:shopping-bag', tone: 'success' },
};

const costIconMap: Record<string, { icon: string; tone: string }> = {
  fixed_expense: { icon: 'lucide:building-2', tone: 'muted' },
  food_material: { icon: 'lucide:carrot', tone: 'warning' },
  labor: { icon: 'lucide:users', tone: 'primary' },
  packaging_consumable: { icon: 'lucide:package', tone: 'success' },
};

function resolveBreakdownMeta(type: 'cost' | 'income', key: string) {
  const map = type === 'income' ? incomeIconMap : costIconMap;
  return map[key] || { icon: 'lucide:circle', tone: 'muted' };
}

function isPositiveMetric(key: string) {
  return key !== 'refund_rate';
}

function resolveKpiChangeTone(key: string, value: number) {
  if (!Number.isFinite(value) || value === 0) {
    return 'neutral';
  }

  const increaseGood = isPositiveMetric(key);
  const isGood = (value > 0 && increaseGood) || (value < 0 && !increaseGood);
  return isGood ? 'positive' : 'negative';
}

function formatKpiChangeText(prefix: '同比' | '环比', value: number) {
  return `${prefix} ${formatSignedRate(value)}`;
}
</script>

<template>
  <Drawer
    :open="props.open"
    class="frp-preview-drawer"
    width="560"
    :title="drawerTitle"
    @close="emit('close')"
  >
    <Spin :spinning="props.loading">
      <template v-if="props.detail">
        <div class="frp-section">
          <div class="frp-section-hd">关键指标</div>
          <div class="frp-kpi-grid">
            <div
              v-for="item in props.detail.kpis"
              :key="`kpi-${item.key}`"
              class="frp-kpi-item"
            >
              <div class="frp-kpi-label">{{ item.label }}</div>
              <div
                class="frp-kpi-val"
                :class="{ 'is-profit': item.key === 'net_profit' }"
              >
                {{ item.valueText }}
              </div>
              <div class="frp-kpi-change">
                <span
                  :class="`frp-kpi-change-${resolveKpiChangeTone(item.key, item.yoyChangeRate)}`"
                >
                  {{ formatKpiChangeText('同比', item.yoyChangeRate) }}
                </span>
                <span
                  :class="`frp-kpi-change-${resolveKpiChangeTone(item.key, item.momChangeRate)}`"
                >
                  {{ formatKpiChangeText('环比', item.momChangeRate) }}
                </span>
              </div>
            </div>
          </div>
        </div>

        <div class="frp-divider"></div>

        <div class="frp-section">
          <div class="frp-section-hd">收入明细（按渠道）</div>
          <div
            v-for="item in props.detail.incomeBreakdowns"
            :key="`income-${item.key}`"
            class="frp-detail-row"
          >
            <span class="frp-detail-name">
              <IconifyIcon
                :icon="resolveBreakdownMeta('income', item.key).icon"
                class="frp-breakdown-icon"
                :class="`is-${resolveBreakdownMeta('income', item.key).tone}`"
              />
              {{ item.label }}
            </span>
            <div class="frp-detail-right">
              <span class="frp-detail-pct">{{
                formatPercent(item.ratioPercent)
              }}</span>
              <span class="frp-detail-amount">{{
                formatCurrency(item.amount)
              }}</span>
            </div>
          </div>
        </div>

        <div class="frp-divider"></div>

        <div class="frp-section">
          <div class="frp-section-hd">成本明细（按类别）</div>
          <div
            v-for="item in props.detail.costBreakdowns"
            :key="`cost-${item.key}`"
            class="frp-detail-row"
          >
            <span class="frp-detail-name">
              <IconifyIcon
                :icon="resolveBreakdownMeta('cost', item.key).icon"
                class="frp-breakdown-icon"
                :class="`is-${resolveBreakdownMeta('cost', item.key).tone}`"
              />
              {{ item.label }}
            </span>
            <div class="frp-detail-right">
              <span class="frp-detail-pct">{{
                formatPercent(item.ratioPercent)
              }}</span>
              <span class="frp-detail-amount">{{
                formatCurrency(item.amount)
              }}</span>
            </div>
          </div>
        </div>
      </template>
      <Empty v-else description="暂无报表详情" />
    </Spin>

    <template #footer>
      <div class="frp-drawer-footer">
        <Button @click="emit('close')">关闭</Button>
        <Button
          type="primary"
          class="frp-drawer-btn"
          :disabled="!canDownload"
          :loading="props.isDownloadingPdf"
          @click="emit('downloadPdf')"
        >
          <template #icon>
            <IconifyIcon icon="lucide:file-text" />
          </template>
          下载PDF
        </Button>
        <Button
          class="frp-drawer-btn"
          :disabled="!canDownload"
          :loading="props.isDownloadingExcel"
          @click="emit('downloadExcel')"
        >
          <template #icon>
            <IconifyIcon icon="lucide:table" />
          </template>
          下载Excel
        </Button>
      </div>
    </template>
  </Drawer>
</template>
