<template>
  <el-select
    filterable
    :multiple="multiple"
    :multiple-limit="multiple ? 0 : 1"
    clearable
    :placeholder="placeholder"
    :loading="loading"
    @change="selectItem"
    @focus="getSelectList"
  >
    <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(false);
    let options = ref([]);
    const getSelectList = async () => {
      if (options.value.length > 0) {
        return;
      }
      loading.value = true;
      try {
        let res = await api[props.api]({
          ...props.params,
          term: "",
        });
        if (res.data.status == 0) {
          options.value = res.data.result;
        } else {
          options.value = [];
        }
      } catch (error) {
        console.error("Failed to fetch select list:", error);
        options.value = [];
      } finally {
        loading.value = false;
      }
    };

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

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

<style></style>
