<template>
  <el-autocomplete
    v-model="text"
    :fetch-suggestions="querySearchAsync"
    :value-key="config.valueKey"
    :placeholder="config.placeholder"
    clearable
    @select="selectAutocomplete"
    @clear="params[config.querykey] = ''"
  ></el-autocomplete>
</template>

<script>
export default {
  props: {
    params: Object,
    config: Object,
    // config: {
    //   serveTarget: {}, // 接口
    //   autocomplateKey: "", //远程搜索接口参数名
    //   querykey: "", //查询接口参数名
    // },
  },
  data() {
    return {
      text: "",
    };
  },
  created() {
    console.log("params", this.params);
  },
  methods: {
    // 远程搜索
    querySearchAsync(queryString, cb) {
      if (queryString) {
        let params = {};
        params[this.config.autocompleteKey] = queryString;
        this.config.serveTarget(params).then((res) => {
          let timeInstance = setTimeout(() => {
            clearTimeout(timeInstance);
            if (res.data.length) {
              cb(res.data);
            } else cb([]);
          }, 1000 * Math.random());
        });
      } else cb([]);
    },
    selectAutocomplete(item) {
      this.params[this.config.querykey] = item.id;
    },
  },
};
</script>

<style lang="scss" scoped></style>
