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

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

const props = defineProps({
  name: String,
  label: String,
  url: String,
  data: Array<Record<string, string | number>>,
  parse: Function,
});
const optionData = ref<OptionData[]>([]);

const model = defineModel<string | number>({ required: true });

function pushOptionData(data: any[]) {
  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) {
    pushOptionData(await get(props.url).then(res => res.data));
  } else if (props.data !== undefined) {
    pushOptionData(props.data);
  }
};
onMounted(getData);
defineExpose({
  getLabel: () => {
    const option = optionData.value.find(item => item.value === model.value);
    return option?.label;
  },
  getOptions: () => {
    return optionData.value;
  },
});
</script>
<template>
  <el-select :name="name || ''" v-model="model">
    <el-option v-for="o in parse ? parse(optionData) : optionData" :key="o.value" :value="o.value" :label="o.label" />
  </el-select>
</template>
