<template>
  <!-- 箭冠产品 -->
  <a-select
    show-search
    label-in-value
    :value="productCode"
    placeholder="请输入产品编码搜索"
    style="width: 100%"
    :filter-option="false"
    :dropdownMatchSelectWidth="false"
    :not-found-content="fetching ? undefined : null"
    @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.productSn" :value="item.productSn">{{ item.code }}</a-select-option>
  </a-select>
</template>
<script>
import debounce from 'lodash/debounce'
import { shelfDealerProductList } from '@/api/shelf'
export default {
  props: {
    itemSn: {
      type: String || Number,
      default: undefined
    },
    params: {
      type: Object,
      default: ()=> {
        return null
      }
    }
  },
  data () {
    this.lastFetchId = 0
    this.fetchUser = debounce(this.fetchUser, 800)
    return {
      data: [],
      productCode: undefined,
      fetching: false
    }
  },
  methods: {
    fetchUser (productCode) {
      console.log('fetching user', productCode)
      if (productCode == '') return
      this.lastFetchId += 1
      const fetchId = this.lastFetchId
      this.data = []
      this.fetching = true
      let params = { code: productCode, pageNo: 1, pageSize: 20 }
      if(this.params){
        params = Object.assign(params, this.params)
      }
      shelfDealerProductList(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.productSn == value.key)
        value.row = ind != -1 ? this.data[ind] : undefined
      }
      Object.assign(this, {
        productCode: value,
        data: [],
        fetching: false
      })
      this.$emit('change', value || { key: undefined, label: '' })
    },
    resetForm () {
      this.productCode = undefined
    },
    setData (value) {
      Object.assign(this, {
        productCode: value,
        data: [],
        fetching: false
      })
    },
    blurSelect () {
      this.data = []
    }
  },
  mounted () {
    if (this.itemSn) {
      this.fetchUser(this.itemSn)
      this.setData({ key: this.itemSn })
    }
  }
}
</script>
