<template>
  <el-select-v2
    v-model="val"
    :options="options"
    :placeholder="props.set.placeholder"
    :props="props.set.props"
    :multiple="props.set.multiple"
    @change="handleSelect"
  />
</template>

<script setup>
import { ref, onMounted, watch } from 'vue';
import request from '@/utils/axios';
const emit = defineEmits(['update:value']);

const props = defineProps({
  set: {
    type: Object,
    default: () => {
      return {
        url: '',
        options: [
          {
            value: '1',
            label: 'label 1',
          },
          {
            value: '2',
            label: 'label 2',
          },
          {
            value: '3',
            label: 'label 3',
          },
        ],
        props: {
          value: 'value',
          label: 'label',
        },
        multiple: false,
        placeholder: '请选择',
      };
    },
  },

  value: {
    type: String || Array || null,
    default: null,
  },
});

onMounted(async () => {
  if (props.set.multiple) val.value = [];

  if (props.set.url) {
    let res = await request(props.set.url, {
      method: 'get',
      data: { current: 1, size: 9999 },
    });
    if (res.code == 200) {
      options.value = res.data.records;
    }
  } else {
    options.value = props.set.options;
  }
});

/* --------------- data --------------- */
// #region
const val = ref(null);
watch(
  () => props.value,
  () => {
    val.value = props.value;
  },
  {
    deep: true,
    immediate: true,
  }
);
const options = ref([]);

// #endregion

/* --------------- methods --------------- */
// #region
function handleSelect(val_) {
  emit('update:value', val_);
}
// #endregion
</script>

<style lang="scss" scoped></style>
