<template>
  <a-select
    show-search
    label-in-value
    :value="dealerName"
    placeholder="请输入下级名称搜索"
    style="width: 100%"
    option-label-prop="label"
    :filter-option="false"
    :not-found-content="fetching ? undefined : null"
    @search="fetchUser"
    @change="handleChange"
  >
    <a-spin v-if="fetching" slot="notFoundContent" size="small" />
    <a-select-option v-for="item in data" :key="item.dealerSn" :value="item.dealerSn" :label="item.dealerName">
      {{ item.dealerName }} - {{ item.parentDealerSn ? '已关联' : '未关联' }}
    </a-select-option>
  </a-select>
</template>
<script>
import debounce from 'lodash/debounce'
import { dealerRelationList } from '@/api/dealerRelation'
export default {
  props: {
    dealerLevelList: {
      type: Array,
      default: function () {
        return []
      }
    }
  },
  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
      dealerRelationList({ 'dealerName': dealerName, 'dealerLevelList': this.dealerLevelList, 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) {
      const ind = this.data.findIndex(item => item.dealerSn == value.key)
      const parentDealerSn = ind != -1 && this.data[ind].parentDealerSn ? this.data[ind].parentDealerSn : ''
      Object.assign(this, {
        dealerName: value,
        data: [],
        fetching: false
      })
      this.$emit('change', value, parentDealerSn)
    },
    resetForm () {
      this.dealerName = []
    }
  }
}
</script>
