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

  </el-select>
</template>

<script>
import curdArea, {queryAreaList} from '@/api/area'

export default {
  name: 'AreaCodeSelect',
  props: {
    value: null, // v-model
    placeholder: {
      type: String,
      default: '请选择库区'
    },
    filterable: {
      type: Boolean,
      default: true
    },
    valueKey: {
      type: String,
      default: 'id'
    },
    // 是否禁用
    disabled: {
      type: Boolean,
      default: false
    },
    isEnabled:{
      type: Boolean,
      default: true
    },
    bexb:{
      type: Boolean,
      default: true
    },
    selectStyle: {
      type: String,
      default: 'width: 200px;'
    },
    immediate: {
      type: Boolean,
      default: false
    },
    // 是否可清空
    clearable: {
      type: Boolean,
      default: false
    },
    // 是否支持多选
    multiple: {
      type: Boolean,
      default: false
    },

  },
  data() {
    return {
      items: [],
      selected: this.value,
      loading: false
    }
  },
  computed: {
    // 处理 v-model 双向绑定
    selectedValue: {
      get() {
        return this.value
      },
      set(val) {
        this.$emit('input', val)
      }
    }
  },
  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();
    // }
  },
  // 清空选中值时触发
  handleClear() {
    this.$emit('clear')
  },
  methods: {
     fetchItems() {
      this.loading = true
      if (this.items.length === 0) {
        curdArea.queryAreaList({ bexb: this.bexb }).then(res => {
          this.items = res
        })
      }
    },
    onChange(val) {
      this.$emit('change', val)
    }
  }
}
</script>
