<script setup lang="ts">
import { ref, onMounted } from "vue";
import { getProductList } from "@/api/product";

defineOptions({
  name: "ProductSelector"
});

interface Product {
  id: number;
  name: string;
  price: number;
  categoryName: string;
}

const props = defineProps({
  modelValue: {
    type: Array as () => number[],
    default: () => []
  },
  multiple: {
    type: Boolean,
    default: true
  },
  placeholder: {
    type: String,
    default: "请选择商品"
  }
});

const emit = defineEmits(["update:modelValue", "change"]);

const products = ref<Product[]>([]);
const filteredProducts = ref<Product[]>([]);
const loading = ref(false);

async function fetchProducts() {
  loading.value = true;
  try {
    // 这里应该调用实际的商品API
    const { data } = await getProductList({ page: 1, pageSize: 1000 });
    products.value = data?.list || [];
    filteredProducts.value = products.value;
  } catch (error) {
    console.error("获取商品列表失败:", error);
    products.value = [];
    filteredProducts.value = [];
  } finally {
    loading.value = false;
  }
}

function handleFilter(query: string) {
  if (!query) {
    filteredProducts.value = products.value;
    return;
  }
  filteredProducts.value = products.value.filter(product => 
    product.name.toLowerCase().includes(query.toLowerCase()) ||
    product.categoryName.toLowerCase().includes(query.toLowerCase())
  );
}

function handleChange(value: number[]) {
  emit("update:modelValue", value);
  emit("change", value);
}

onMounted(() => {
  fetchProducts();
});
</script>

<template>
  <el-select
    :model-value="modelValue"
    :multiple="multiple"
    :placeholder="placeholder"
    :loading="loading"
    :filterable="true"
    :filter-method="handleFilter"
    @change="handleChange"
    class="w-full"
  >
    <el-option
      v-for="product in filteredProducts"
      :key="product.id"
      :label="product.name"
      :value="product.id"
    >
      <span>{{ product.name }}</span>
      <span class="text-gray-400 text-sm ml-2">¥{{ product.price }}</span>
      <span class="text-gray-400 text-xs ml-2">{{ product.categoryName }}</span>
    </el-option>
  </el-select>
</template>

<style lang="scss" scoped>
:deep(.el-select-dropdown__item) {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>