<template>
  <a-select
    show-search
    label-in-value
    :size="size"
    :value="creatorName"
    :placeholder="placeholder"
    style="width: 100%"
    :filter-option="false"
    :not-found-content="fetching ? undefined : null"
    :dropdownMatchSelectWidth="false"
    @search="fetchUser"
    @change="handleChange"
    allowClear
    :disabled="disabled"
  >
    <a-spin v-if="fetching" slot="notFoundContent" size="small" />
    <a-select-option v-for="item in data" :key="item.creatorId" :value="item.creatorId">
      {{ item.creatorName }}
    </a-select-option>
  </a-select>
</template>
<script>
import debounce from 'lodash/debounce'
import { queryCreatorList } from '@/api/promotion'
export default {
  props: {
    size: {
      type: String,
      default: 'default'
    },
    placeholder: {
      type: String,
      default: '请输入创建人名称搜索'
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data () {
    this.lastFetchId = 0
    this.fetchUser = debounce(this.fetchUser, 800)
    return {
      data: [],
      creatorName: [],
      fetching: false
    }
  },
  methods: {
    fetchUser (likeCreatorName) {
      if (likeCreatorName == '') return
      this.lastFetchId += 1
      const fetchId = this.lastFetchId
      this.data = []
      this.fetching = true
      queryCreatorList({ creatorName: likeCreatorName.replace(/\s+/g, '') }).then(res => {
        if (fetchId !== this.lastFetchId) {
          return
        }
        this.data = res.data ? res.data : []
        this.fetching = false
      })
    },
    handleChange (value) {
      if (value && value.key) {
        const obj = this.data.find(item => item.creatorId == value.key)
        value.name = obj.creatorName
      }
      Object.assign(this, {
        creatorName: value,
        data: [],
        fetching: false
      })
      this.$emit('change', value || { key: undefined })
    },
    resetForm () {
      this.creatorName = []
    },
    setDefaultVal (val) {
      this.creatorName = val
    }
  }
}
</script>
