<template>
  <TMagicSelect
    :model-value="model[name]"
    clearable
    filterable
    :size="size"
    :disabled="disabled"
    @change="fieldChangeHandler"
  >
    <component
      v-for="option in options"
      class="tmagic-design-option"
      :key="option.value"
      :is="optionComponent?.component || 'el-option'"
      v-bind="
        optionComponent?.props({
          label: option.text,
          value: option.value,
        }) || {
          label: option.text,
          value: option.value,
        }
      "
    >
    </component>
  </TMagicSelect>
</template>

<script setup lang="ts">
import { computed } from 'vue';

import { getDesignConfig, TMagicSelect } from '@tmagic/design';
import type { CondOpSelectConfig, FieldProps } from '@tmagic/form';

import { useServices } from '@editor/hooks/use-services';
import { arrayOptions, eqOptions, getFieldType, numberOptions } from '@editor/utils';

defineOptions({
  name: 'MFieldsCondOpSelect',
});

const emit = defineEmits<{
  change: [value: string];
}>();

const { dataSourceService } = useServices();

const props = defineProps<FieldProps<CondOpSelectConfig>>();

const optionComponent = getDesignConfig('components')?.option;

const options = computed(() => {
  const [id, ...fieldNames] = [...(props.config.parentFields || []), ...props.model.field];

  const ds = dataSourceService.getDataSourceById(id);

  const type = getFieldType(ds, fieldNames);

  if (type === 'array') {
    return arrayOptions;
  }

  if (type === 'boolean' || type === 'null') {
    return [
      { text: '是', value: 'is' },
      { text: '不是', value: 'not' },
    ];
  }

  if (type === 'number') {
    return [...eqOptions, ...numberOptions];
  }

  if (type === 'string') {
    return [...arrayOptions, ...eqOptions];
  }

  return [...arrayOptions, ...eqOptions, ...numberOptions];
});

const fieldChangeHandler = (v: string) => {
  emit('change', v);
};
</script>
