<script setup lang="ts">
/**
 * 文件职责：次卡二级商品选择抽屉。
 */
import type { PunchCardPickerProductItem } from '../types';

import type { ProductStatus } from '#/api/product';

import { computed } from 'vue';

import { Button, Drawer, Empty, Input, Select, Spin } from 'ant-design-vue';

import { formatCurrency } from '../composables/punch-card-page/helpers';

const props = defineProps<{
  categoryFilterId: string;
  categoryOptions: Array<{ label: string; value: string }>;
  keyword: string;
  loading: boolean;
  open: boolean;
  products: PunchCardPickerProductItem[];
  selectedProductIds: string[];
}>();

const emit = defineEmits<{
  (event: 'close'): void;
  (event: 'search'): void;
  (event: 'setCategoryFilterId', value: string): void;
  (event: 'setKeyword', value: string): void;
  (event: 'toggleProduct', id: string): void;
  (event: 'submit'): void;
}>();

const selectedCount = computed(() => props.selectedProductIds.length);

const allChecked = computed(
  () =>
    props.products.length > 0 &&
    props.products.every((item) => props.selectedProductIds.includes(item.id)),
);

function setKeyword(value: string) {
  emit('setKeyword', value);
}

function setCategoryFilterId(value: unknown) {
  emit('setCategoryFilterId', String(value ?? ''));
}

function toggleAll() {
  if (allChecked.value) {
    const visibleIds = new Set(props.products.map((item) => item.id));
    for (const id of props.selectedProductIds) {
      if (visibleIds.has(id)) {
        emit('toggleProduct', id);
      }
    }
    return;
  }

  for (const item of props.products) {
    if (!props.selectedProductIds.includes(item.id)) {
      emit('toggleProduct', item.id);
    }
  }
}

function resolveProductStatusText(status: ProductStatus) {
  if (status === 'on_sale') {
    return '在售';
  }
  if (status === 'sold_out') {
    return '沽清';
  }
  return '下架';
}

function resolveProductStatusClass(status: ProductStatus) {
  if (status === 'on_sale') {
    return 'is-green';
  }
  if (status === 'sold_out') {
    return 'is-orange';
  }
  return 'is-gray';
}
</script>

<template>
  <Drawer
    :open="open"
    title="选择适用商品"
    width="760"
    class="mpc-picker-drawer"
    @close="emit('close')"
  >
    <div class="mpc-picker-toolbar">
      <Input
        :value="keyword"
        placeholder="搜索商品名称/SPU"
        allow-clear
        @update:value="setKeyword"
        @press-enter="emit('search')"
      />

      <Select
        :value="categoryFilterId"
        :options="categoryOptions"
        class="mpc-picker-category"
        @update:value="setCategoryFilterId"
      />

      <Button @click="emit('search')">搜索</Button>
      <span class="mpc-picker-count">已选 {{ selectedCount }} 个</span>
    </div>

    <Spin :spinning="loading">
      <div v-if="products.length === 0" class="mpc-picker-empty">
        <Empty description="暂无可选商品" />
      </div>

      <div v-else class="mpc-picker-table-wrap">
        <table class="mpc-picker-table">
          <thead>
            <tr>
              <th class="mpc-picker-col-check">
                <input
                  type="checkbox"
                  :checked="allChecked"
                  @change="toggleAll"
                />
              </th>
              <th>商品</th>
              <th>分类</th>
              <th class="mpc-picker-col-price">售价</th>
              <th class="mpc-picker-col-status">状态</th>
            </tr>
          </thead>

          <tbody>
            <tr
              v-for="item in products"
              :key="item.id"
              :class="{ checked: selectedProductIds.includes(item.id) }"
              @click="emit('toggleProduct', item.id)"
            >
              <td class="mpc-picker-col-check">
                <input
                  type="checkbox"
                  :checked="selectedProductIds.includes(item.id)"
                  @change.stop="emit('toggleProduct', item.id)"
                />
              </td>

              <td>
                <div class="mpc-picker-product-name">{{ item.name }}</div>
                <div class="mpc-picker-product-spu">{{ item.spuCode }}</div>
              </td>

              <td>{{ item.categoryName }}</td>
              <td class="mpc-picker-col-price">
                {{ formatCurrency(item.price) }}
              </td>
              <td class="mpc-picker-col-status">
                <span
                  class="mpc-picker-product-status"
                  :class="resolveProductStatusClass(item.status)"
                >
                  {{ resolveProductStatusText(item.status) }}
                </span>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </Spin>

    <template #footer>
      <div class="mpc-picker-footer">
        <span class="mpc-picker-footer-info">
          已选择 {{ selectedCount }} 个商品
        </span>
        <div class="mpc-picker-footer-actions">
          <Button @click="emit('close')">取消</Button>
          <Button type="primary" @click="emit('submit')">确认选择</Button>
        </div>
      </div>
    </template>
  </Drawer>
</template>
