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

defineOptions({
  name: "DeviceSelector"
});

interface Device {
  id: number;
  deviceId: string;
  storeName: string;
  status: number;
}

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 devices = ref<Device[]>([]);
const filteredDevices = ref<Device[]>([]);
const loading = ref(false);

async function fetchDevices() {
  loading.value = true;
  try {
    const { data } = await getDeviceList({ page: 1, pageSize: 1000 });
    devices.value = data?.list || [];
    filteredDevices.value = devices.value;
  } catch (error) {
    console.error("获取设备列表失败:", error);
    devices.value = [];
    filteredDevices.value = [];
  } finally {
    loading.value = false;
  }
}

function handleFilter(query: string) {
  if (!query) {
    filteredDevices.value = devices.value;
    return;
  }
  filteredDevices.value = devices.value.filter(device => 
    device.deviceId.toLowerCase().includes(query.toLowerCase()) ||
    device.storeName.toLowerCase().includes(query.toLowerCase())
  );
}

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

onMounted(() => {
  fetchDevices();
});
</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="device in filteredDevices"
      :key="device.id"
      :label="device.storeName"
      :value="device.id"
    >
      <span>{{ device.storeName }}</span>
      <span class="text-gray-400 text-sm ml-2">{{ device.deviceId }}</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>
