<template>
  {{ label }}
  <Field
    :name="name"
    :model-value="textValue"
    :type="numberMode ? 'number' : 'text'"
    :show-label="false"
    :show-bottom-border="false"
    :placeholder="placeholder"
    :max-length="maxLength"
    :field-style="mergedFieldStyle"
    :input-style="mergedInputStyle"
    :input-flex="1"
    :auto-update-form-value="false"
    @update:model-value="onUpdate"
  />
  {{ suffix }}
</template>

<script setup lang="ts">
import { computed } from 'vue';
import { useTheme, type ViewStyle, type TextStyle } from '@/components/theme/ThemeDefine';
import Field from '@/components/form/Field.vue';

const props = withDefaults(
  defineProps<{
    /** 绑定值：字符串或与 `number-mode` 搭配的数字 */
    modelValue?: string | number | null;
    /** 为 true 时对外 `update:modelValue` 发出数字（解析失败为 0） */
    numberMode?: boolean;
    placeholder?: string;
    /** 输入框左侧短说明，如「带徒」 */
    label?: string;
    /** 输入框右侧固定文案，如「人」「场」 */
    suffix?: string;
    maxLength?: number;
    /** 与 Form 的 `rules` 键一致，用于联表校验 */
    name?: string;
    /** 主题间距键，默认 sm */
    gap?: string;
    fieldStyle?: ViewStyle;
    inputStyle?: TextStyle;
  }>(),
  {
    modelValue: '',
    numberMode: false,
    placeholder: '请填写',
    label: '',
    suffix: '',
    maxLength: 20,
    gap: 'sm',
    fieldStyle: () => ({}),
    inputStyle: () => ({}),
    name: undefined,
  },
);

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

const themeContext = useTheme();

const mergedFieldStyle = computed<ViewStyle>(() => ({
  display: 'inline-block',
  paddingVertical: themeContext.resolveThemeSize('AgreementPrefillFieldPaddingV', 6),
  paddingHorizontal: themeContext.resolveThemeSize('AgreementPrefillFieldPaddingH', 12),
  borderRadius: themeContext.resolveThemeSize('AgreementPrefillFieldRadius', '10rpx'),
  backgroundColor: themeContext.resolveThemeColor('AgreementPrefillFieldBg', 'light'),
  borderWidth: '1rpx',
  borderStyle: 'solid',
  borderColor: themeContext.resolveThemeColor('AgreementPrefillFieldBorder', 'border.cell'),
  minWidth: themeContext.resolveThemeSize('AgreementPrefillFieldMinWidth', '80rpx'),
  maxWidth: themeContext.resolveThemeSize('AgreementPrefillFieldMaxWidth', '100rpx'),
  ...props.fieldStyle,
}));

const mergedInputStyle = computed<TextStyle>(() => ({
  textAlign: 'center',
  fontSize: themeContext.resolveThemeSize('AgreementPrefillInputFontSize', 28),
  ...props.inputStyle,
}));

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

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