<template>
  <t-select
    v-model="valueData"
    :options="options"
    :multiple="isMultiple"
    :disabled="!config.writable"
    filterable
    @change="emitChange"
  ></t-select>
</template>
<script setup name="SELECT">
import { ref, onMounted, computed, watch } from 'vue';
import { request } from '@/utils/request.js';

const props = defineProps({
  config: { type: Object },
  modelValue: { type: [String, Array] },
});
const emit = defineEmits(['update:modelValue', 'change']);

const valueData = ref(null);
const isMultiple = computed(() => {
  return props.config.code === 'MULTIPLE_SELECT';
});

const options = ref([]);
const getOptionsApi = () => {
  return request({
    url: props.config.dataGrid,
    method: 'post',
  });
};
const getOptions = async () => {
  if (props.config.options) {
    let data = props.config.options;
    if (typeof data === 'string') {
      data = JSON.parse(data);
    }
    options.value = data;
    return;
  }

  if (!props.config.dataGrid) return;
  const data = await getOptionsApi();
  options.value = data || [];
};

onMounted(() => {
  getOptions();
});

const emitChange = () => {
  emit('update:modelValue', valueData.value);
  emit('change', valueData.value);
};

watch(
  () => props.modelValue,
  (val, oldval) => {
    if (val === oldval) return;
    valueData.value = val || (isMultiple.value ? [] : '');
  },
  {
    immediate: true,
  }
);
</script>
