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

<script>
import crudItem, {getItemsList} from '@/api/item'

export default {
  name: 'ItemSelect',
  props: {
    value: null, // v-model
    placeholder: {
      type: String,
      default: '请选择物料'
    },
    filterable: {
      type: Boolean,
      default: true
    },
    valueKey: {
      type: String,
      default: 'id'
    },
    isEnabled:{
      type: Boolean,
      default: true
    },
    style: {
      type: String,
      default: 'width: 200px;'
    }
  },
  data() {
    return {
      items: [],
      selected: this.value
    }
  },
  watch: {
    value(val) {
      this.selected = val
    },
    selected(val) {
      this.$emit('input', val)
      this.$emit('change', val)
    }
  },
  methods: {
    fetchItems() {
      if (this.items.length === 0) {
        crudItem.getItemsList({ enabled: this.isEnabled }).then(res => {
          this.items = res
        })
      }
    },
    onChange(val) {
      this.$emit('change', val)
    }
  }
}
</script>
