<script setup lang="ts">
import type { ProductPickerItemDto } from '#/api/product';

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

defineProps<{
  keyword: string;
  loading: boolean;
  open: boolean;
  rows: ProductPickerItemDto[];
  selectedId: string;
}>();

const emit = defineEmits<{
  (event: 'close'): void;
  (event: 'search'): void;
  (event: 'select', value: string): void;
  (event: 'setKeyword', value: string): void;
  (event: 'submit'): void;
}>();
</script>

<template>
  <Modal
    :open="open"
    title="选择兑换商品"
    width="760px"
    ok-text="确认选择"
    cancel-text="取消"
    @ok="emit('submit')"
    @cancel="emit('close')"
  >
    <div class="mpm-picker-toolbar">
      <Input
        :value="keyword"
        allow-clear
        placeholder="搜索商品名称/SPU"
        @update:value="(value) => emit('setKeyword', String(value ?? ''))"
        @press-enter="emit('search')"
      />
      <button type="button" class="g-btn g-btn-sm" @click="emit('search')">
        搜索
      </button>
    </div>

    <Spin :spinning="loading">
      <div v-if="rows.length === 0" class="mpm-picker-empty">
        <Empty description="暂无可选商品" />
      </div>
      <div v-else class="mpm-picker-table-wrap">
        <table class="mpm-picker-table">
          <thead>
            <tr>
              <th class="col-radio"></th>
              <th>商品</th>
              <th>分类</th>
              <th class="col-price">售价</th>
              <th class="col-status">状态</th>
            </tr>
          </thead>
          <tbody>
            <tr
              v-for="item in rows"
              :key="item.id"
              :class="{ checked: selectedId === item.id }"
              @click="emit('select', item.id)"
            >
              <td class="col-radio">
                <input
                  type="radio"
                  name="mpm-product-picker"
                  :checked="selectedId === item.id"
                  @change.stop="emit('select', item.id)"
                />
              </td>
              <td>
                <div class="name">{{ item.name }}</div>
                <div class="spu">{{ item.spuCode }}</div>
              </td>
              <td>{{ item.categoryName }}</td>
              <td class="col-price">¥{{ item.price.toFixed(2) }}</td>
              <td class="col-status">{{ item.status }}</td>
            </tr>
          </tbody>
        </table>
      </div>
    </Spin>
  </Modal>
</template>
