<template>
  <el-select
    filterable
    :multiple="multiple"
    :multiple-limit="multiple ? 0 : 1"
    remote
    clearable
    reserve-keyword
    :placeholder="placeholder"
    :remote-method="getSelectList"
    :loading="loading"
    @change="selectItem"
  >
    <el-option
      v-for="item in options"
      :key="item.key"
      :label="item.value"
      :value="{ value: item.key, key: item.value }"
    />
  </el-select>
</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,
    multiple: {
      type: Boolean,
      default: false,
    },
  },

  emits: ["selectItem"],
  setup(props, { emit }) {
    let loading = ref(true);
    const getSelectList = _.debounce(
      async (term) => {
        if (!term) return;
        loading.value = true;
        let res = await api[props.api]({
          ...props.params,
          term,
        });
        if (res.data.status == 0) {
          options.value = res.data.result;
        } else {
          options.value = [];
        }
        loading.value = false;
      },
      1000,
      { leading: true }
    );
    let options = ref([]);
    const selectItem = (item) => {
      emit("selectItem", item);
    };

    onMounted(() => {});
    return {
      getSelectList,
      selectItem,
      options,
      loading,
    };
  },
};
</script>

<style></style>
