<template>
  <el-autocomplete
    class="inline-input"
    v-model="inputValue"
    @input="$emit('input', inputValue)"
    :fetch-suggestions="querySearch"
    :placeholder="placeholder"
    clearable
    @select="handleSelect"
    style="margin-right:10px;margin-bottom:5px"
  ></el-autocomplete>
</template>

<script>
export default {
  props: {
    url: String,
    inputSearchValue: String,
    placeholder: String,
    value: String
  },
  data() {
    return {
      restaurants: [],
      inputValue: ''
    }
  },
  methods: {
    handleSelect(item) {
      this.inputValue = item.value
    },
    querySearch(queryString, cb) {
      var restaurants = this.restaurants
      var results = queryString
        ? restaurants.filter(this.createFilter(queryString))
        : restaurants
      // 调用 callback 返回建议列表的数据
      cb(results)
    },
    createFilter(queryString) {
      return restaurant => {
        return (
          restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) ===
          0
        )
      }
    },
    loadAll() {
      let arr = []
      let params = {
        pageBean: {
          page: 1,
          pageSize: -1,
          showTotal: true
        }
      }
      this.$http.post('${yhxt}' + this.url, params).then(res => {
        res.data.rows.forEach(item => {
          arr.push({
            value: item[this.inputSearchValue],
            id: item.id
          })
        })
        arr = this.unlink(arr)
      })
      return arr
    },
    unlink(arr) {
      for (var i = 0; i < arr.length - 1; i++) {
        for (var j = i + 1; j < arr.length; j++) {
          if (arr[i].value == arr[j].value) {
            arr.splice(j, 1)
            //因为数组长度减小1，所以直接 j++ 会漏掉一个元素，所以要 j--
            j--
          }
        }
      }
      return arr
    }
  },
  watch: {
    value(newValue, oldValue) {
      this.inputValue = newValue
    }
  },
  mounted() {
    this.restaurants = this.loadAll()
  }
}
</script>

<style></style>
