<template>
  <el-input
    :value="displayText"
    :placeholder="placeholder"
    :disabled="disabled"
    v-bind="$attrs"
    @input="onInput"
    @focus="onFocus"
    @blur="onBlur"
  />
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import Big from 'big.js'
import type { FormattedNumberRounding } from '../utils/formattedNumber'
import {
  applyNumericInputDigitLimits,
  formatWithThousands,
  normalizeNumericValue,
  numberToEditString,
  sanitizeNumericInput,
  stripNumberGrouping,
  toBig,
  toFixedDecimalString,
} from '../utils/formattedNumber'

const props = withDefaults(
  defineProps<{
    value?: unknown
    placeholder?: string
    disabled?: boolean
    /** 整数部分允许的最大位数，默认 6 */
    integerDigits?: number
    /** 小数保留位数，默认 6 */
    decimalPlaces?: number
    /** 进位方式，默认四舍五入 */
    rounding?: FormattedNumberRounding
    /**
     * 为 true 时在输入过程中按 integerDigits / decimalPlaces 限制可输入位数；
     * 为 false 时仅失焦后规范化，输入阶段不截断长度。
     */
    inputLimit?: boolean
  }>(),
  {
    integerDigits: 6,
    decimalPlaces: 6,
    rounding: 'round',
    inputLimit: true,
  }
)

const emit = defineEmits<{ (e: 'input', value: unknown): void }>()

const focused = ref(false)
const displayText = ref('')

const intN = () => Math.max(0, Math.floor(props.integerDigits ?? 6))
const decM = () => Math.max(0, Math.floor(props.decimalPlaces ?? 6))

function parseExternalValue(v: unknown): Big | null {
  if (v === null || v === undefined || v === '') return null
  if (typeof v === 'number') {
    if (!Number.isFinite(v)) return null
    try { return Big(v) } catch { return null }
  }
  const s = stripNumberGrouping(String(v))
  return toBig(s)
}

function syncDisplayFromValue() {
  if (focused.value) return
  const big = parseExternalValue(props.value)
  if (big === null) {
    displayText.value = ''
    return
  }
  displayText.value = formatWithThousands(
    normalizeNumericValue(big, intN(), decM(), props.rounding),
    decM()
  )
}

watch(
  () => [props.value, props.integerDigits, props.decimalPlaces, props.rounding],
  () => syncDisplayFromValue(),
  { immediate: true, deep: true }
)

function emitStoredValue(normalized: Big) {
  emit('input', toFixedDecimalString(normalized, decM()))
}

function onInput(val: string) {
  let clean = sanitizeNumericInput(val)
  if (props.inputLimit !== false) {
    clean = applyNumericInputDigitLimits(clean, intN(), decM())
  }
  displayText.value = clean
  if (clean === '' || clean === '-') return
  const big = toBig(clean)
  if (big === null) return
  const normalized = normalizeNumericValue(big, intN(), decM(), props.rounding)
  emitStoredValue(normalized)
}

function onFocus() {
  focused.value = true
  const raw = stripNumberGrouping(displayText.value)
  const big = parseExternalValue(raw === '' ? props.value : raw)
  if (big === null) {
    displayText.value = ''
    return
  }
  displayText.value = numberToEditString(
    normalizeNumericValue(big, intN(), decM(), props.rounding),
    decM()
  )
}

function onBlur() {
  focused.value = false
  const raw = stripNumberGrouping(displayText.value)
  if (raw === '' || raw === '-') {
    displayText.value = ''
    emit('input', undefined)
    return
  }
  const big = toBig(sanitizeNumericInput(raw))
  if (big === null) {
    displayText.value = ''
    emit('input', undefined)
    return
  }
  const final = normalizeNumericValue(big, intN(), decM(), props.rounding)
  displayText.value = formatWithThousands(final, decM())
  emitStoredValue(final)
}
</script>
