<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 crudBillType, {queryBillTypeList} from '@/api/billType'

export default {
  name: 'BillTypeSelect',
  props: {
    value: null, // v-model
    placeholder: {
      type: String,
      default: '请选择单据类型'
    },
    filterable: {
      type: Boolean,
      default: true
    },
    valueKey: {
      type: String,
      default: 'id'
    },
    isEnabled:{
      type: Boolean,
      default: true
    },
    bill_code:{
      type: String, // 修正类型定义
      default: ''   // 修正默认值
    },
    styles: {
      type: String,
      default: 'width: 200px;'
    },
    immediate: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      items: [],
      filteredItems: [],
      selected: this.value
    }
  },
  watch: {
    value: {
      handler(val) {
        this.selected = val;
      },
      immediate: true // 确保初始化时也能正确设置 selected 值
    },
    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) {
        queryBillTypeList({ code: this.bill_code }).then(res => {
          this.items = res;
          this.filteredItems = [...this.items];
        });
      }
    },
    onChange(val) {
      console.log(val);
      this.$emit('change', val);
    },
    filterMethod(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>
