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

defineOptions({
  name: "ShopSelector"
});

interface Shop {
  id: number;
  name: string;
  address: 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 shops = ref<Shop[]>([]);
const filteredShops = ref<Shop[]>([]);
const loading = ref(false);

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

function handleFilter(query: string) {
  if (!query) {
    filteredShops.value = shops.value;
    return;
  }
  filteredShops.value = shops.value.filter(shop => 
    shop.name.toLowerCase().includes(query.toLowerCase()) ||
    shop.address.toLowerCase().includes(query.toLowerCase())
  );
}

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

onMounted(() => {
  fetchShops();
});
</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="shop in filteredShops"
      :key="shop.id"
      :label="shop.name"
      :value="shop.id"
    >
      <span>{{ shop.name }}</span>
      <span class="text-gray-400 text-sm ml-2">{{ shop.address }}</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>