<template>
  <el-select :value="selectedValue" placeholder="请选择" @input="inputHandler" clearable style="width:100%" >
    <el-option
      v-for="(item, index) in options"
      :key="index"
      :label="item.value"
      :value="item.key">
    </el-option>
  </el-select>
</template>

<script>
export default {
  props: [
    'value',
    'config'
  ],

  data() {
    return {
      options: [],
      selectedValue: ''
    }
  },

  watch: {
    config(val) {
      this.updateOptions(val)
    },

    value(val) {
      this.selectedValue = val
    }
  },

  created() {
    this.selectedValue = this.value
    this.updateOptions(this.config)
  },

  methods: {
    inputHandler(val) {
      this.selectedValue = val
      this.$emit('input', this.selectedValue)
    },
    async updateOptions(config) {
      if (config.options && config.options.length) {
        this.options = JSON.parse(JSON.stringify(config.options))
        return
      }
      if (config.listOptions) {
        let items = config.listOptions.split(':')
        if (items.length !== 2) {
          this.options = []
          return
        }
        if (items[0] === 'Input') {
          let list = items[1].split('<br>')
          this.options = list.map(val => {
            return { value: val, key: val }
          })
          return
        }
        let res = await axios.get(`/ui/contentextends/fields/options/${items[0]}`, {
          params: {
            method: items[1]
          }
        })
        this.options = res.data.data
      }
    }
  }
}
</script>

<style>

</style>
