<script setup lang="ts">
/**
 * 文件职责：分类商品选择弹窗。
 */
import type { ProductPickerItemDto } from '#/api/product';

import { Input, Modal } from 'ant-design-vue';

import { formatPrice } from '../types';

interface Props {
  keyword: string;
  loading: boolean;
  open: boolean;
  products: ProductPickerItemDto[];
  selectedIds: string[];
  submitting: boolean;
}

interface Emits {
  (event: 'close'): void;
  (event: 'search'): void;
  (event: 'setKeyword', value: string): void;
  (event: 'submit'): void;
  (event: 'toggleProduct', id: string): void;
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

function setKeyword(value: string) {
  emit('setKeyword', value);
}
</script>

<template>
  <Modal
    :open="props.open"
    title="添加商品到分类"
    ok-text="确认添加"
    cancel-text="取消"
    :confirm-loading="props.submitting"
    :ok-button-props="{ disabled: props.selectedIds.length === 0 }"
    @ok="emit('submit')"
    @cancel="emit('close')"
  >
    <div class="pcat-picker-search">
      <Input
        :value="props.keyword"
        placeholder="搜索商品名称/SPU"
        allow-clear
        @update:value="setKeyword"
        @press-enter="emit('search')"
      />
      <button
        type="button"
        class="pcat-btn pcat-btn-sm"
        :disabled="props.loading"
        @click="emit('search')"
      >
        搜索
      </button>
    </div>

    <div class="pcat-picker-list">
      <div v-if="props.loading" class="pcat-picker-empty">加载中...</div>
      <div v-else-if="props.products.length === 0" class="pcat-picker-empty">
        暂无可选商品
      </div>
      <label
        v-for="item in props.products"
        v-else
        :key="`picker-${item.id}`"
        class="pcat-picker-item"
      >
        <input
          :checked="props.selectedIds.includes(item.id)"
          type="checkbox"
          @change="emit('toggleProduct', item.id)"
        />
        <span class="name">{{ item.name }}</span>
        <span class="spu">{{ item.spuCode }}</span>
        <span class="price">{{ formatPrice(item.price) }}</span>
      </label>
    </div>
  </Modal>
</template>
