<template>
  <FlexCol gap="gap.xs" padding="space.md">
    <FlexRow align="center" wrap :gap="'sm'" :inner-style="rowOuterStyle">
      <Text v-if="prefix" font-config="p" color="text.second" :inner-style="prefixStyle">
        {{ prefix }}
      </Text>
      <AgreementPrefillInline
        :model-value="modelValue.year"
        placeholder="YYYY"
        suffix="年"
        :max-length="4"
        :field-style="yearFieldStyle"
        @update:model-value="(v) => patch('year', v)"
      />
      <AgreementPrefillInline
        :model-value="modelValue.month"
        placeholder="MM"
        suffix="月"
        :max-length="2"
        :field-style="mdFieldStyle"
        @update:model-value="(v) => patch('month', v)"
      />
      <AgreementPrefillInline
        :model-value="modelValue.day"
        placeholder="DD"
        suffix="日"
        :max-length="2"
        :field-style="mdFieldStyle"
        @update:model-value="(v) => patch('day', v)"
      />
    </FlexRow>
    <Text v-if="hint" font-config="p" color="text.second" :inner-style="hintStyle">
      {{ hint }}
    </Text>
  </FlexCol>
</template>

<script setup lang="ts">
import type { ViewStyle, TextStyle } from '@/components/theme/ThemeDefine';
import FlexCol from '@/components/layout/FlexCol.vue';
import FlexRow from '@/components/layout/FlexRow.vue';
import Text from '@/components/basic/Text.vue';
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];
}>();

const rowOuterStyle: ViewStyle = {
  marginTop: '8rpx',
};

const prefixStyle: TextStyle = {
  flexShrink: 0,
};

const hintStyle: TextStyle = {
  marginTop: '4rpx',
};

const yearFieldStyle: ViewStyle = {
  minWidth: '120rpx',
  maxWidth: '130rpx',
};

const mdFieldStyle: ViewStyle = {
  minWidth: '78rpx',
  maxWidth: '100rpx',
};

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>
