<template>
  <el-select
    v-model="currentValue"
    :clearable="clearable"
    :placeholder="placeholder"
    :loading="loading"
    :disabled="disabled"
    :allow-create="allowCreate"
    :filterable="filterable"
    :multiple="multiple"
    :collapse-tags="collapseTags"
    @change="onChange"
    @clear="onClear"
    @visible-change="storeInfo"
  >
    <el-option
      v-for="item in listData"
      :key="item[prop.key ? prop.key:'id']"
      :label="item[prop.label ? prop.label : 'label']"
      :value="item[prop.value ? prop.value : 'value']">
      <slot :item="item" />
    </el-option>
  </el-select>
</template>

<script>
import request from '../../utils/request'

export default {
  name: 'SelectList',
  props: {
    value: {},
    url: {
      type: String,
      required: true
    },
    placeholder: {
      type: String,
      default: '请选择'
    },
    requestMethod: {
      type: String,
      default: 'post'
    },
    clearable: {
      type: Boolean,
      default: false
    },
    prop: {
      type: Object,
      default: function() {
        return { label: 'name', key: 'id', value: 'id' }
      }
    },
    condition: {
      type: Object,
      default: () => {
        return { isEnabled: true }
      }
    },
    disabled: Boolean,
    allowCreate: Boolean,
    filterable: Boolean,
    multiple: Boolean,
    collapseTags: Boolean
  },
  data() {
    return {
      listData: [],
      currentValue: null,
      loading: false
    }
  },
  watch: {
    value(val) {
      this.currentValue = val
    },
    condition() {
      this.getDate()
    }
  },
  created() {
    this.currentValue = this.value
    this.getDate()
  },
  methods: {
    getDate() {
      this.loading = true
      const condition = {}
      for (const key in this.condition) {
        condition[key] = this.condition[key]
      }
      request({
        url: this.url,
        method: this.requestMethod,
        data: condition
      }).then((response) => {
        this.listData = response.data
      }).finally(() => {
        this.loading = false
      })
    },
    onChange(val) {
      this.$emit('input', val)
      this.$emit('change', val)
    },
    onClear() {
      this.$emit('input', null)
      this.$emit('clear')
    },
    storeInfo(e){
      this.$emit('visible-change', e)
    }
  }
}
</script>

<style scoped>

</style>
