<template>
  <view class="form-row">
    <view class="form-row__label">
      {{ name }}<text v-if="required" class="form-cell-required">*</text>
    </view>
    <view class="form-row__content runtime">
      <input :disabled="disableChange" class="num" type="number" :value="year" @input="onInput($event, 'year')" />
      <text class="unit">年</text>
      <input :disabled="disableChange" class="num" type="number" :value="month" @input="onInput($event, 'month')" />
      <text class="unit">月</text>
      <input :disabled="disableChange" class="num" type="number" :value="day" @input="onInput($event, 'day')" />
      <text class="unit">日</text>
    </view>
  </view>
</template>

<script setup>
import { computed, ref, watch } from 'vue';

const emits = defineEmits(['change']);
const props = defineProps({
  form: { type: Object, default: () => ({}) },
  name: { default: '' },
  required: { type: Boolean, default: false },
  title: { default: '' },
  disableChange: { type: Boolean, default: false },
});

const raw = computed(() => (props.form && props.form[props.title] ? String(props.form[props.title]) : ''));
const year = ref('');
const month = ref('');
const day = ref('');

watch(
  raw,
  (n) => {
    if (!n) {
      year.value = '';
      month.value = '';
      day.value = '';
      return;
    }
    const yearMatch = n.match(/(\d+)年/);
    const monthMatch = n.match(/(\d+)月/);
    const dayMatch = n.match(/(\d+)日/);
    year.value = yearMatch ? yearMatch[1] : '';
    month.value = monthMatch ? monthMatch[1] : '';
    day.value = dayMatch ? dayMatch[1] : '';
  },
  { immediate: true }
);

function build() {
  const y = year.value && year.value !== '0' ? `${year.value}年` : '';
  const m = month.value && month.value !== '0' ? `${month.value}月` : '';
  const d = day.value && day.value !== '0' ? `${day.value}日` : '';
  emits('change', { title: props.title, value: `${y}${m}${d}` });
}

function onInput(e, key) {
  const v = String(e?.detail?.value || '').replace(/[^\d]/g, '');
  if (key === 'year') year.value = v;
  if (key === 'month') month.value = v;
  if (key === 'day') day.value = v;
  build();
}
</script>

<style lang="scss" scoped>
@import '../cell-style.css';

.runtime {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  gap: 10rpx;
}

.num {
  width: 80rpx;
  text-align: right;
  font-size: 30rpx;
  border-bottom: 1px solid #888;
}

.unit {
  font-size: 28rpx;
  color: #333;
}
</style>
