<template>
  <a-select
    show-search
    label-in-value
    :size="size"
    :value="dealerName"
    :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.dealerSn" :value="item.dealerSn">
      {{ item.dealerName }}
    </a-select-option>
  </a-select>
</template>
<script>
import debounce from 'lodash/debounce'
import { dealerSubareaScopeList, dealerDetailBySn, queryTireDealerPage } from '@/api/dealer'
export default {
  props: {
    size: {
      type: String,
      default: 'default'
    },
    placeholder: {
      type: String,
      default: '请输入名称搜索'
    },
    disabled: {
      type: Boolean,
      default: false
    },
    dealertype: {
      type: String,
      default: ''
    }
  },
  data () {
    this.lastFetchId = 0
    this.fetchUser = debounce(this.fetchUser, 800)
    return {
      data: [],
      dealerName: [],
      fetching: false
    }
  },
  methods: {
    fetchUser (dealerName) {
      console.log('fetching user', dealerName)
      if (dealerName == '') return
      this.lastFetchId += 1
      const fetchId = this.lastFetchId
      this.data = []
      this.fetching = true
      const ajaxName = this.dealertype && this.dealertype.length ? queryTireDealerPage : dealerSubareaScopeList
      ajaxName({ nameLike: dealerName.replace(/\s+/g, ''), pageNo: 1, pageSize: 20 }).then(res => {
        if (fetchId !== this.lastFetchId) {
          return
        }
        this.data = res.data && res.data.list ? res.data.list : []
        this.fetching = false
      })
    },
    handleChange (value) {
      if (value && value.key) {
        const obj = this.data.find(item => item.dealerSn == value.key)
        value.name = obj.dealerName
        value.row = obj
      }
      Object.assign(this, {
        dealerName: value,
        data: [],
        fetching: false
      })
      this.$emit('change', value || { key: undefined })
    },
    resetForm () {
      this.dealerName = []
    },
    setData (value) {
      Object.assign(this, {
        dealerName: value,
        data: [],
        fetching: false
      })
    },
    setDufaultVal (itemSn) {
      this.fetchUser(itemSn)
      this.setData({ key: itemSn })
    },
    // 查询详细
    getDetail (sn, flag) {
      dealerDetailBySn({ sn: sn }).then(res => {
        const val = { key: sn }
        val.row = res.data
        if (!flag) {
          Object.assign(this, {
            dealerName: val,
            data: [res.data],
            fetching: false
          })
          this.$emit('change', val)
        }
        this.$emit('dealerDetail', res.data || null)
      })
    }
  }
}
</script>
