<template>
  <div class="ymd-block">
    <a-space wrap align="center">
      <span v-if="prefix" class="text-secondary">{{ prefix }}</span>
      <a-input-number
        :value="modelValue.year"
        :max-length="4"
        size="small"
        class="w-12!"
        @update:value="(v: any) => patch('year', v)"
      />
      <span class="text-secondary">年</span>
      <a-input-number
        :value="modelValue.month"
        :max-length="2"
        size="small"
        class="w-12!"
        @update:value="(v: any) => patch('month', v)"
      />
      <span class="text-secondary">月</span>
      <a-input-number
        :value="modelValue.day"
        :max-length="2"
        size="small"
        class="w-12!"
        @update:value="(v: any) => patch('day', v)"
      />
      <span class="text-secondary">日</span>
    </a-space>
    <div v-if="hint" class="text-secondary hint">{{ hint }}</div>
  </div>
</template>

<script setup lang="ts">
import AgreementPrefillInline from './AgreementPrefillInline.vue';

export type AgreementYmdParts = {
  year: string;
  month: string;
  day: string;
};

const props = withDefaults(
  defineProps<{
    modelValue: AgreementYmdParts;
    prefix?: string;
    hint?: string;
  }>(),
  {
    prefix: '时间：',
    hint: '',
  },
);

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

function digitsOnly(v: string | number, maxLen: number) {
  const str = String(v ?? '').replace(/\D/g, '');
  return str.slice(0, maxLen);
}

function patch(key: keyof AgreementYmdParts, v: string | number) {
  const max = key === 'year' ? 4 : 2;
  const next = digitsOnly(v, max);
  emit('update:modelValue', {
    ...props.modelValue,
    [key]: next,
  });
}
</script>

<style scoped>
.ymd-block {
  margin-top: 8px;
}
.hint {
  margin-top: 6px;
  font-size: 13px;
}
</style>
