<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> -->

  <el-select
    v-model="params[config.querykey]"
    filterable
    remote
    clearable
    reserve-keyword
    :placeholder="config.placeholder"
    :remote-method="remoteMethod"
    @clear="list = []"
  >
    <el-option
      v-for="(item, index) in list"
      :key="item.id + index"
      :label="item[config.labelKey]"
      :value="item[config.valueKey]"
    >
    </el-option>
  </el-select>
</template>

<script>
export default {
  props: {
    params: Object,
    config: Object,
    // config: {
    //   serveTarget: {}, // 远程搜索接口
    //   autocompleteKey: "", //远程搜索接口参数名
    //   labelKey: "", //接口返回数据label名
    //   valueKey: "", //接口返回数据唯一值
    //   querykey: "", //查询接口参数名
    // },
  },
  data() {
    return {
      text: "",
      list: [],
    };
  },
  watch: {
    "config.echoId": {
      handler(nval, oval) {
        if (nval) {
          console.log(nval);
          this.remoteMethod(this.config.echoName);
        }
      },
      deep: true,
      immediate: true,
    },
  },
  methods: {
    // 远程搜索
    remoteMethod(query) {
      if (query !== "") {
        this.loading = true;
        let params = {};
        params[this.config.autocompleteKey] = query;
        this.config.serveTarget(params).then((res) => {
          let timeInstance = setTimeout(() => {
            this.loading = false;
            clearTimeout(timeInstance);
            if (res.data.length) {
              this.list = res.data;
            } else this.list = [];
          }, 1000 * Math.random());
        });
      } else {
        this.list = [];
      }
    },
    // 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>
