<template>
  <el-select
    v-model="selected"
    @focus="fetchItems"
    :placeholder="placeholder"
    :filterable="filterable"
    :value-key="valueKey"
    :style="styles"
    @change="onChange"
    :filterMethod="filterMethod"
  >
    <el-option
      v-for="item in items"
      :key="item.id"
      :label="item.code"
      :value="item"
    >
      <span>{{ item.code }}</span>
      <span>{{ item.name }}</span>
    </el-option>
  </el-select>
</template>

<script>
import crudItem, {queryBigItemAll} from '@/api/bigItem'

export default {
  name: 'BigItemSelect',
  props: {
    value: null, // v-model
    placeholder: {
      type: String,
      default: '请选择机型'
    },
    filterable: {
      type: Boolean,
      default: true
    },
    valueKey: {
      type: String,
      default: 'id'
    },
    isEnabled:{
      type: Boolean,
      default: true
    },
    styles: {
      type: String,
      default: 'width: 200px;'
    },
    immediate: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      items: [],
      filteredItems: [],
      selected: this.value
    }
  },
  watch: {
    value(val) {
      this.selected = val
    },
    selected(val) {
      this.$emit('input', val)
      this.$emit('change', val)
    }
  },
  created() {
    // 如果设置了immediate属性或已有值，则立即加载数据
    if (this.immediate || (this.value && this.value[this.valueKey])) {
      this.fetchItems();
    }
  },
  methods: {
    fetchItems() {
      if (this.items.length === 0) {
          queryBigItemAll({ enabled: this.isEnabled }).then(res => {
          this.items = res
            this.filteredItems = [...this.items];
        })
      }
    },
    onChange(val) {
      this.$emit('change', val)
    },
    filterMethod(query) {
      console.log(query)
      if (!query) {
        this.filteredItems = [...this.items];
        return;
      }

      const lowerQuery = query.toLowerCase();
      this.items = this.filteredItems.filter(item =>
        item.code.toLowerCase().includes(lowerQuery) ||
        item.name.toLowerCase().includes(lowerQuery)
      );
    },
  }
}
</script>
