<!--词汇-选择器-->
<template>
  <el-select
    ref="select"
    v-model="currentVal"
    :placeholder="placeholder"
    :disabled="disabled"
    :clearable="clearable"
    filterable
    :allow-create="allowCreate"
    @change="changeNode"
    @clear="onClear"
    @blur="blur"
  >
    <el-option v-for="item in options" :key="item.value" :label="item.name" :value="item.value" />
  </el-select>

</template>

<script>
import { getVocabulary } from '../../api/system/vocabulary'

export default {
  name: 'VocabularySelect',
  props: {
    value: {},
    code: {
      type: String,
      required: true
    },
    placeholder: {
      type: String,
      default: '请选择'
    },
    clearable: Boolean,
    allowCreate: Boolean,
    disabled: Boolean
  },
  data() {
    return {
      options: [],
      currentVal: null
    }
  },
  computed: {
    optionsMap() {
      let data = {}
      this.options.forEach((item) => {
        data[item.value] = item
      })
      return data
    }
  },
  watch: {
    value(val) {
      this.valueToString(val)
    }
  },
  created() {
    this.valueToString(this.value)
    this.getVocabulary()
  },
  methods: {
    getVocabulary() {
      getVocabulary(this.code).then((response) => {
        this.options = response.data
      })
    },
    changeNode(value) {
      let data = this.optionsMap[value]
      this.$emit('input', value)
      this.$emit('change', value, data)
    },
    blur() {
      this.$emit('blur')
    },
    valueToString(val) {
      if (val !== undefined && val !== null) {
        // 因为词汇的value是string类型的，尔value可能会是number类型的，所以需要统一转完为string
        this.currentVal = val + ''
      } else {
        this.currentVal = val
      }
    },
    onClear() {
      this.$emit('clear')
    }
  }
}
</script>

<style scoped>

</style>
