<script setup lang="ts">
/**
 * 文件职责：规格做法模板卡片。
 * 1. 展示模板基础信息、选项与关联商品数。
 * 2. 提供编辑、复制、删除操作入口。
 */
import type { ProductSpecDto } from '#/api/product';

const props = defineProps<{
  item: ProductSpecDto;
}>();

const emit = defineEmits<{
  copy: [item: ProductSpecDto];
  edit: [item: ProductSpecDto];
  remove: [item: ProductSpecDto];
}>();

function formatPrice(extraPrice: number) {
  if (!extraPrice) return '';
  const abs = Math.abs(extraPrice);
  const absText = Number.isInteger(abs)
    ? String(abs)
    : abs.toFixed(2).replace(/\.?0+$/, '');
  return `${extraPrice > 0 ? '+' : '-'}${absText}元`;
}

function handleEdit() {
  emit('edit', props.item);
}

function handleCopy() {
  emit('copy', props.item);
}

function handleRemove() {
  emit('remove', props.item);
}
</script>

<template>
  <div class="psp-card" :class="{ disabled: item.status === 'disabled' }">
    <div class="psp-card-hd">
      <span class="name">{{ item.name }}</span>
      <span
        class="g-tag"
        :class="item.type === 'spec' ? 'g-tag-blue' : 'g-tag-orange'"
      >
        {{ item.type === 'spec' ? '规格' : '做法' }}
      </span>
      <span v-if="item.status === 'disabled'" class="g-tag g-tag-gray">
        已停用
      </span>
    </div>

    <div class="psp-card-meta">
      {{ item.selectionType === 'single' ? '单选' : '多选' }} ·
      {{ item.isRequired ? '必选' : '可选' }}
    </div>

    <div class="psp-pills">
      <span
        v-for="value in item.values"
        :key="value.id || value.name"
        class="psp-pill"
      >
        {{ value.name }}
        <span v-if="value.extraPrice" class="price">
          {{ formatPrice(value.extraPrice) }}
        </span>
      </span>
    </div>

    <div class="psp-card-assoc">已关联 {{ item.productCount }} 个商品</div>

    <div class="psp-card-ft">
      <button type="button" class="g-action" @click="handleEdit">编辑</button>
      <button type="button" class="g-action" @click="handleCopy">复制</button>
      <button
        type="button"
        class="g-action g-action-danger"
        @click="handleRemove"
      >
        删除
      </button>
    </div>
  </div>
</template>
