<template>
  <el-autocomplete
    v-model="currentValue"
    :fetch-suggestions="getSelectList"
    :placeholder="placeholder"
    @select="selectItem"
    :size="size"
    clearable
    @clear="clear"
    @input="handleInput"
    style="width: 240px"
  />
</template>

<script>
import { onMounted, ref } from "vue";
import api from "../apis/fetch";
import _ from "lodash";
export default {
  props: {
    placeholder: {
      type: String,
      default: "请填写",
    },
    size: {
      type: String,
      default: "small",
    },
    clearable: {
      type: Boolean,
      default: true,
    },
    api: String,
    params: Object,
    value: String,
  },
  emits: ["input", "selectItem"],
  setup(props, { emit }) {
    let currentValue = ref(props.value);
    let selectStr = ref("");
    const getSelectList = _.debounce(
      async (queryString, cb) => {
        if (!queryString) return;
        let res = await api[props.api]({
          ...props.params,
          term: queryString,
        });
        if (res.data.status == 0) {
          cb(res.data.result);
        }
      },
      1000,
      { leading: true }
    );

    const selectItem = (item) => {
      emit("selectItem", item);
    };

    function clear() {
      selectStr.value = "";
    }

    function handleInput(e) {
      emit("input", e);
    }

    onMounted(() => {});
    return {
      selectStr,
      getSelectList,
      clear,
      selectItem,
      handleInput,
      currentValue,
    };
  },
};
</script>

<style></style>
