<template>
  <FlexView :direction="vertical ? 'column' : 'row'" align="center" :gap="10" wrap>
    <RadioGroup
      :value="selectValue"
      @update:value="onUpdateValue"
      :disabled="disabled"
      v-bind="$attrs"
    >
      <Radio
        v-for="it in options"
        :key="(it.value as string)"
        :name="(it.value as string)"
        :text="it.text"
      />
    </RadioGroup>
  </FlexView>
</template>

<script lang="ts" setup>
import { type PropType, ref, watch, onMounted } from 'vue';
import RadioGroup from '@/components/form/RadioGroup.vue';
import Radio from '@/components/form/Radio.vue';
import type { RadioValueOption } from './RadioValue';
import FlexView from '@/components/layout/FlexView.vue';

const props = defineProps({
  /**
   * 是否禁用
   */
  disabled: {
    type: Boolean,
    default: false
  },
  /**
   * 是否垂直方向
   */
  vertical: {
    type: Boolean,
    default: false
  },
  /**
   * 选项数据
   */
  options: {
    type: Object as PropType<RadioValueOption[]>,
    default: null,
  },
  modelValue: {
  },
});

const emits = defineEmits([
  'update:modelValue',
]);

const selectValue = ref<string|null>('');

function setRadioValue() {
  selectValue.value = props.options.find(k => (k.value === props.modelValue))?.text || null;
  if (selectValue.value === null)
    selectValue.value = props.options.find(k => (typeof k.value === typeof props.modelValue))?.text || null;
}

watch(() => props.modelValue, () => {
  setRadioValue();
});
onMounted(() => {
  setRadioValue();
});

function onUpdateValue(v : unknown) {
  emits('update:modelValue', props.options.find(k => k.text === v)?.value);
}

</script>