<template>
  <a-select
    show-search
    label-in-value
    :value="dealerName"
    :placeholder="placeholderInfo"
    style="width: 100%"
    :filter-option="false"
    :not-found-content="fetching ? undefined : null"
    @search="fetchUser"
    @change="handleChange"
    allowClear
  >
    <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 { dealerRelationList } from '@/api/dealerRelation'
export default {
  props: {
    dealerLevelList: {
      type: Array,
      default: function () {
        return []
      }
    },
    placeholderInfo: {
      type: String,
      default: '请输入上级名称搜索'
    },
    isShowSn: {
      type: String,
      default: null
    }
  },
  data () {
    this.lastFetchId = 0
    this.fetchUser = debounce(this.fetchUser, 800)
    return {
      data: [],
      dealerName: [],
      fetching: false,
      itemSn: null
    }
  },
  methods: {
    fetchUser (dealerName) {
      console.log('fetching user', dealerName)
      if (dealerName == '') return
      this.lastFetchId += 1
      const fetchId = this.lastFetchId
      this.data = []
      this.fetching = true
      const params = { 'dealerLevelList': this.dealerLevelList, pageNo: 1, pageSize: 20 }
      if (this.itemSn && !dealerName) {
        params.dealerSn = this.itemSn
      } else {
        params.dealerName = dealerName
      }
      dealerRelationList(params).then(res => {
        if (fetchId !== this.lastFetchId) {
          return
        }
        if (res.data && res.data.list && res.data.list.length > 0) {
          if (!this.isShowSn) {
            this.data = res.data.list
          } else {
            const newData = res.data.list.filter(con => con.dealerSn != this.isShowSn)
            this.data = newData
          }
        } else {
          this.data = []
        }
        this.fetching = false
      })
    },
    handleChange (value) {
      console.log(value)
      Object.assign(this, {
        dealerName: value,
        data: [],
        fetching: false
      })
      if (!value) {
        this.itemSn = null
      }
      this.$emit('change', value)
    },
    setVal (value, label) {
      if (value) {
        this.itemSn = value
        this.fetchUser()
        this.handleChange({ key: this.itemSn, label: label })
      }
    },
    resetForm () {
      this.itemSn = null
      this.dealerName = []
    }
  }
}
</script>
