<script setup lang="ts">
/**
 * 文件职责：多边形区域列表区块。
 * 1. 展示区域表格信息。
 * 2. 抛出新增、编辑、删除事件。
 */
import type { PolygonZoneDto } from '#/api/store-delivery';

import { Button, Card, Empty, Popconfirm } from 'ant-design-vue';

import { countPolygonsInGeoJson } from '../composables/delivery-page/geojson';

interface Props {
  formatCurrency: (value: number) => string;
  isSaving: boolean;
  zones: PolygonZoneDto[];
}

const props = defineProps<Props>();

const emit = defineEmits<{
  (event: 'add'): void;
  (event: 'delete', zoneId: string): void;
  (event: 'edit', zone: PolygonZoneDto): void;
}>();

function getPolygonCount(geoJson: string) {
  return countPolygonsInGeoJson(geoJson);
}
</script>

<template>
  <Card :bordered="false">
    <template #title>
      <span class="section-title">配送区域</span>
    </template>
    <template #extra>
      <Button type="primary" :disabled="props.isSaving" @click="emit('add')">
        绘制新区域
      </Button>
    </template>

    <div v-if="props.zones.length > 0" class="zone-table-wrap">
      <table class="zone-table">
        <thead>
          <tr>
            <th>区域名称</th>
            <th>配送费</th>
            <th>起送金额</th>
            <th>预计送达</th>
            <th>优先级</th>
            <th class="zone-op-column">操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="zone in props.zones" :key="zone.id">
            <td>
              <span
                class="zone-color"
                :style="{ background: zone.color }"
              ></span>
              {{ zone.name }}
              <span class="zone-shape-count">
                （{{ getPolygonCount(zone.polygonGeoJson) }}块）
              </span>
            </td>
            <td>{{ props.formatCurrency(zone.deliveryFee) }}</td>
            <td>{{ props.formatCurrency(zone.minOrderAmount) }}</td>
            <td>{{ zone.etaMinutes }} 分钟</td>
            <td>{{ zone.priority }}</td>
            <td class="zone-op-cell">
              <div class="zone-actions">
                <Button type="link" size="small" @click="emit('edit', zone)">
                  编辑
                </Button>
                <Popconfirm
                  title="确认删除该配送区域吗？"
                  ok-text="确认"
                  cancel-text="取消"
                  @confirm="emit('delete', zone.id)"
                >
                  <Button type="link" size="small" danger>删除</Button>
                </Popconfirm>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
    <Empty v-else description="暂无区域配置" />
  </Card>
</template>
