<script setup lang="ts">
import { watch } from "vue";
import { useVModel } from "@vueuse/core";

const figure = 20;

const props = withDefaults(
  defineProps<{
    modelValue: string;
    placeholder?: string;
    unit?: string;
    KeepDecimals?: number;
  }>(),
  {
    unit: "元",
    KeepDecimals: 2
  }
);

const modelValue = useVModel(props, "modelValue");

function limitNumTool(value, figure) {
  const { KeepDecimals } = props;

  let str =
    ("" + value)
      .replace(/[^\d^\.]+/g, "")
      .replace(/^0+(\d)/, "$1")
      .replace(/^\./, "0.") //
      .match(/^\d*(\.?\d{0,2})/g)[0] || "";
  if (str.indexOf(".") > -1) {
    str = str.slice(0, Number(figure) + 3);
  } else {
    str = str.slice(0, figure);
  }
  return str;
}

watch(
  () => modelValue.value,
  value => (modelValue.value = limitNumTool(value, figure))
);
</script>

<template>
  <ElInput v-model="modelValue" :placeholder="placeholder">
    <template #append>{{ unit }}</template>
  </ElInput>
</template>
