<template>
  <span class="prefill-wrap">
    <span v-if="label" class="prefill-label">{{ label }}</span>
    <a-input
      :value="textValue"
      :type="numberMode ? 'number' : 'text'"
      :placeholder="placeholder"
      :maxlength="maxLength"
      :disabled="disabled"
      class="prefill-input"
      @update:value="onUpdate"
    />
    <span v-if="suffix" class="prefill-suffix">{{ suffix }}</span>
  </span>
</template>

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

const props = withDefaults(
  defineProps<{
    modelValue?: string | number | null;
    numberMode?: boolean;
    placeholder?: string;
    label?: string;
    suffix?: string;
    maxLength?: number;
    disabled?: boolean;
  }>(),
  {
    modelValue: '',
    numberMode: false,
    disabled: false,
    placeholder: '请填写',
    label: '',
    suffix: '',
    maxLength: 20,
  },
);

const emit = defineEmits<{
  'update:modelValue': [value: string | number];
}>();

const textValue = computed(() =>
  props.modelValue === null || props.modelValue === undefined ? '' : String(props.modelValue),
);

function onUpdate(raw: string) {
  if (props.numberMode) {
    const n = parseInt(String(raw).replace(/\D/g, ''), 10);
    emit('update:modelValue', Number.isFinite(n) ? n : 0);
  } else {
    emit('update:modelValue', raw);
  }
}
</script>

<style scoped>
.prefill-wrap {
  display: inline-flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 4px;
  vertical-align: middle;
}
.prefill-label {
  white-space: nowrap;
}
.prefill-input {
  width: 5rem;
  min-width: 4rem;
  text-align: center;
}
.prefill-suffix {
  white-space: nowrap;
}
</style>
