<script setup lang="ts">
/**
 * 门店列表表格：
 * - 负责行内容渲染
 * - 通过事件抛出分页/编辑/删除动作
 */
import type {
  StatusTagMeta,
  StoreTablePagination,
  TablePagination,
} from '../types';

import type { StoreListItemDto } from '#/api/store';

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

import {
  GeoLocationStatus as GeoLocationStatusEnum,
  StoreAuditStatus as StoreAuditStatusEnum,
  StoreBusinessStatus as StoreBusinessStatusEnum,
} from '#/api/store';

interface Props {
  auditStatusMap: Record<number, StatusTagMeta>;
  businessStatusMap: Record<number, StatusTagMeta>;
  columns: Array<Record<string, unknown>>;
  geoStatusMap: Record<number, StatusTagMeta>;
  getAvatarColor: (index: number) => string;
  isLoading: boolean;
  pagination: StoreTablePagination;
  serviceTypeMap: Record<number, StatusTagMeta>;
  storeList: StoreListItemDto[];
}

const props = defineProps<Props>();

const emit = defineEmits<{
  (event: 'delete', record: StoreListItemDto): void;
  (event: 'edit', record: StoreListItemDto): void;
  (event: 'retryGeocode', record: StoreListItemDto): void;
  (event: 'toggleBusinessStatus', record: StoreListItemDto): void;
  (event: 'tableChange', pagination: TablePagination): void;
}>();

/** 透传表格分页变化。 */
function handleTableChange(pagination: TablePagination) {
  emit('tableChange', pagination);
}

/** 类型守卫：把表格记录收敛为门店对象。 */
function isStoreRecord(record: unknown): record is StoreListItemDto {
  if (!record || typeof record !== 'object') return false;
  const candidate = record as Partial<StoreListItemDto>;
  return typeof candidate.id === 'string' && typeof candidate.name === 'string';
}

/** 安全触发编辑事件。 */
function emitEdit(record: unknown) {
  if (!isStoreRecord(record)) return;
  emit('edit', record);
}

/** 安全触发删除事件。 */
function emitDelete(record: unknown) {
  if (!isStoreRecord(record)) return;
  emit('delete', record);
}

/** 当前门店是否允许快速切换营业状态。 */
function canQuickToggleBusinessStatus(record: unknown) {
  if (!isStoreRecord(record)) return false;
  return (
    record.auditStatus === StoreAuditStatusEnum.Approved &&
    record.businessStatus !== StoreBusinessStatusEnum.ForceClosed
  );
}

/** 获取快速切换按钮文案。 */
function getToggleBusinessStatusText(record: unknown) {
  if (!isStoreRecord(record)) return '不可切换';
  const status = record.businessStatus;
  if (status === StoreBusinessStatusEnum.Operating) {
    return '设为休息';
  }
  if (status === StoreBusinessStatusEnum.Resting) {
    return '恢复营业';
  }
  return '不可切换';
}

/** 安全触发营业状态切换事件。 */
function emitToggleBusinessStatus(record: unknown) {
  if (!isStoreRecord(record)) return;
  emit('toggleBusinessStatus', record);
}

/** 当前门店是否允许手动重试定位。 */
function canRetryGeocode(record: unknown) {
  if (!isStoreRecord(record)) return false;
  return record.geoStatus !== GeoLocationStatusEnum.Success;
}

/** 安全触发重试定位事件。 */
function emitRetryGeocode(record: unknown) {
  if (!isStoreRecord(record)) return;
  emit('retryGeocode', record);
}

/** 解析定位状态枚举值。 */
function resolveGeoStatus(record: unknown) {
  if (!isStoreRecord(record)) return GeoLocationStatusEnum.Pending;
  return record.geoStatus ?? GeoLocationStatusEnum.Pending;
}

/** 创建时间格式化为 yyyy-MM-dd。 */
function formatCreatedDate(value: string) {
  if (!value) return '--';
  const isoDateMatch = /^(\d{4}-\d{2}-\d{2})/.exec(value.trim());
  if (isoDateMatch) {
    return isoDateMatch[1] ?? '--';
  }
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) {
    return value.slice(0, 10) || '--';
  }
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
}
</script>

<template>
  <Card :bordered="false">
    <Table
      class="store-list-table"
      :columns="props.columns"
      :data-source="props.storeList"
      :loading="props.isLoading"
      :pagination="props.pagination"
      row-key="id"
      :scroll="{ x: 1200 }"
      @change="handleTableChange"
    >
      <template #bodyCell="{ column, record, index }">
        <template v-if="column.key === 'storeInfo'">
          <div class="store-info-cell">
            <div
              class="store-avatar"
              :style="{ background: props.getAvatarColor(index) }"
            >
              <svg
                xmlns="http://www.w3.org/2000/svg"
                width="20"
                height="20"
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                stroke-width="2"
                stroke-linecap="round"
                stroke-linejoin="round"
              >
                <path
                  d="m2 7 4.41-4.41A2 2 0 0 1 7.83 2h8.34a2 2 0 0 1 1.42.59L22 7"
                />
                <path d="M4 12v8a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8" />
                <path d="M15 22v-4a2 2 0 0 0-2-2h-2a2 2 0 0 0-2 2v4" />
                <path d="M2 7h20" />
                <path
                  d="M22 7v3a2 2 0 0 1-2 2a2.7 2.7 0 0 1-1.59-.63.7.7 0 0 0-.82 0A2.7 2.7 0 0 1 16 12a2.7 2.7 0 0 1-1.59-.63.7.7 0 0 0-.82 0A2.7 2.7 0 0 1 12 12a2.7 2.7 0 0 1-1.59-.63.7.7 0 0 0-.82 0A2.7 2.7 0 0 1 8 12a2.7 2.7 0 0 1-1.59-.63.7.7 0 0 0-.82 0A2.7 2.7 0 0 1 4 12a2 2 0 0 1-2-2V7"
                />
              </svg>
            </div>
            <div class="store-info-text">
              <div class="store-name">{{ record.name }}</div>
              <div class="store-code">{{ record.code }}</div>
            </div>
          </div>
        </template>

        <template v-if="column.key === 'serviceTypes'">
          <Tag
            v-for="serviceType in record.serviceTypes"
            :key="serviceType"
            class="service-tag"
            :color="props.serviceTypeMap[serviceType]?.color"
          >
            {{ props.serviceTypeMap[serviceType]?.text }}
          </Tag>
        </template>

        <template v-if="column.key === 'businessStatus'">
          <Tag :color="props.businessStatusMap[record.businessStatus]?.color">
            {{ props.businessStatusMap[record.businessStatus]?.text }}
          </Tag>
        </template>

        <template v-if="column.key === 'auditStatus'">
          <Tag :color="props.auditStatusMap[record.auditStatus]?.color">
            {{ props.auditStatusMap[record.auditStatus]?.text }}
          </Tag>
        </template>

        <template v-if="column.key === 'geoStatus'">
          <Tag
            :color="props.geoStatusMap[resolveGeoStatus(record)]?.color"
            :title="record.geoFailReason || ''"
          >
            {{ props.geoStatusMap[resolveGeoStatus(record)]?.text }}
          </Tag>
        </template>

        <template v-if="column.key === 'createdAt'">
          <span>{{ formatCreatedDate(record.createdAt) }}</span>
        </template>

        <template v-if="column.key === 'action'">
          <div class="store-action-row">
            <Button type="link" size="small" @click="emitEdit(record)">
              编辑
            </Button>
            <Button
              type="link"
              size="small"
              :disabled="!canQuickToggleBusinessStatus(record)"
              @click="emitToggleBusinessStatus(record)"
            >
              {{ getToggleBusinessStatusText(record) }}
            </Button>
            <Button
              type="link"
              size="small"
              :disabled="!canRetryGeocode(record)"
              @click="emitRetryGeocode(record)"
            >
              重试定位
            </Button>
            <Popconfirm
              title="确定要删除该门店吗？"
              ok-text="确定"
              cancel-text="取消"
              @confirm="emitDelete(record)"
            >
              <Button type="link" size="small" danger>删除</Button>
            </Popconfirm>
          </div>
        </template>
      </template>
    </Table>
  </Card>
</template>
