<script lang="ts" setup>
import { get } from "@/common/http/request";

interface OptionData {
  value: string | number;
  label: string;
}

const props = defineProps({
  name: {
    type: String,
    default: "value",
  },
  label: {
    type: String,
    default: "label",
  },
  url: {
    type: String,
    default: undefined,
  },
  data: {
    type: Array as PropType<Array<Record<string, string | number>>>,
    default: undefined,
  },
  placeholder: {
    type: String,
    default: "请选择",
  },
  disabled: {
    type: Boolean,
    default: false,
  },
  clearable: {
    type: Boolean,
    default: true,
  },
  collapseTags: {
    type: Boolean,
    default: true,
  },
  collapseTagsTooltip: {
    type: Boolean,
    default: true,
  },
});

const optionData = ref<OptionData[]>([]);
const model = defineModel<(string | number)[]>({ required: true });

function pushOptionData(data: any[]) {
  optionData.value = [];
  for (const item of data) {
    optionData.value.push({
      value: props.name !== undefined ? item[props.name] : item["value"],
      label: props.label !== undefined ? item[props.label] : item["label"],
    });
  }
}

const getData = async () => {
  if (props.url !== undefined) {
    const res = await get(props.url);
    pushOptionData(res.data || []);
  } else if (props.data !== undefined) {
    pushOptionData(props.data);
  }
};

onMounted(getData);

const getSelectedLabels = () => {
  return optionData.value.filter(item => model.value?.includes(item.value)).map(item => item.label);
};

defineExpose({
  getSelectedLabels,
  refresh: getData,
});
</script>
<template>
  <el-select
    v-model="model"
    multiple
    :placeholder="placeholder"
    :disabled="disabled"
    :clearable="clearable"
    :collapse-tags="collapseTags"
    :collapse-tags-tooltip="collapseTagsTooltip"
    style="width: 100%"
  >
    <el-option v-for="o in optionData" :key="o.value" :value="o.value" :label="o.label" />
  </el-select>
</template>
