<template>
  <a-select
    show-search
    label-in-value
    :size="size"
    :value="dealerName"
    placeholder="请输入名称搜索"
    style="width: 100%"
    :filter-option="false"
    :not-found-content="fetching ? undefined : null"
    :dropdownMatchSelectWidth="false"
    @blur="blurSelect"
    @search="fetchUser"
    @change="handleChange"
    allowClear
  >
    <a-spin v-if="fetching" slot="notFoundContent" size="small" />
    <a-select-option v-for="item in data" :key="item.customerSn" :value="item.customerSn" :disabled="isValidateEnabled ? item.enabledFlag=='0' : false">
      {{ item.customerName }}
      <span v-if="isValidateEnabled && item.enabledFlag=='0'">(已禁用)</span>
    </a-select-option>
  </a-select>
</template>
<script>
import debounce from 'lodash/debounce'
import { custList } from '@/api/customer'
export default {
  props: {
    isValidateEnabled: {
      type: Boolean,
      default: false
    },
    size: {
      type: String,
      default: 'default'
    },
    itemSn: {
      type: String || Number,
      default: undefined
    },
    isEnabled: { // 是否只查启用状态
      type: Boolean,
      default: false
    }
  },
  data () {
    this.lastFetchId = 0
    this.fetchUser = debounce(this.fetchUser, 800)
    return {
      data: [],
      dealerName: undefined,
      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 params = { pageNo: 1, pageSize: 20 }
      if (this.itemSn) {
        params.customerSn = this.itemSn
      } else {
        params.queryWord = dealerName
      }
      if (this.isEnabled) {
        params.enabledFlag = 1
      }
      custList(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 && value.key) {
        const ind = this.data.findIndex(item => item.customerSn == value.key)
        value.row = ind != -1 ? this.data[ind] : undefined
      }
      Object.assign(this, {
        dealerName: value,
        data: [],
        fetching: false
      })
      this.$emit('change', value || { key: undefined })
    },
    resetForm () {
      this.dealerName = undefined
    },
    setData (value) {
      Object.assign(this, {
        dealerName: value,
        data: [],
        fetching: false
      })
    },
    blurSelect () {
      this.data = []
    }
  },
  mounted () {
    if (this.itemSn) {
      this.fetchUser(this.itemSn)
      this.setData({ key: this.itemSn })
    }
  }
}
</script>
