<template>
  <a-select
    show-search
    label-in-value
    :size="size"
    :value="userName"
    :placeholder="placeholder"
    style="width: 100%"
    :filter-option="false"
    :not-found-content="fetching ? undefined : null"
    :dropdownMatchSelectWidth="false"
    @search="fetchUser"
    @change="handleChange"
    allowClear
  >
    <a-spin v-if="fetching" slot="notFoundContent" size="small" />
    <a-select-option v-for="item in data" :key="item.userSn" :value="item.userSn">
      {{ item.userName }}
    </a-select-option>
  </a-select>
</template>
<script>
import debounce from 'lodash/debounce'
import { queryUserList } from '@/api/bizuser'
export default {
  props: {
    id: {
      type: String,
      default: ''
    },
    size: {
      type: String,
      default: 'default'
    },
    itemSn: {
      type: String || Number,
      default: undefined
    },
    placeholder: {
      type: String,
      default: '请输入名称搜索'
    },
    cooperateFlag: {
      type: String,
      default: undefined
    }
  },
  data () {
    this.lastFetchId = 0
    this.fetchUser = debounce(this.fetchUser, 800)
    return {
      data: [],
      userName: [],
      fetching: false
    }
  },
  methods: {
    fetchUser (userName) {
      console.log('fetching user', userName)
      if (userName == '') return
      this.lastFetchId += 1
      const fetchId = this.lastFetchId
      this.data = []
      this.fetching = true
      const params = { pageNo: 1, pageSize: 20 }
      if (this.itemSn) {
        params.dealerSn = this.itemSn
      } else {
        params.userName = userName
        if (this.cooperateFlag) {
          params.cooperateFlag = this.cooperateFlag
        }
      }
      queryUserList(params).then(res => {
        if (fetchId !== this.lastFetchId) {
          return
        }
        this.data = res.data && res.data.list ? res.data.list : []
        this.fetching = false
      })
    },
    handleChange (value) {
      if (value) {
        const row = this.data.filter(item => item.userSn == value.key)
        Object.assign(this, {
          userName: value,
          data: [],
          fetching: false
        })
        this.$emit('change', value || { key: undefined }, row[0], this.id)
        // this.$emit('input', value.key)
      } else {
        this.setDufaultVal('')
        this.resetForm()
        this.$emit('change', value || { key: undefined }, undefined, this.id)
        // this.$emit('input', value.key)
      }
    },
    resetForm () {
      this.userName = []
    },
    setData (value) {
      Object.assign(this, {
        userName: value,
        data: [],
        fetching: false
      })
    },
    setDufaultVal (itemSn) {
      this.fetchUser(itemSn)
      this.setData({ key: itemSn })
    }
  },
  mounted () {
    if (this.itemSn) {
      this.fetchUser(this.itemSn)
      this.setData({ key: this.itemSn })
    }
  }
}
</script>
