<template>
  <input v-bind="$attrs" v-model="inputValue" @input="handleInput" />
</template>

<script>
export default {
  name: "NumberInput",
  data() {
    return {
      inputValue: this.value,
    };
  },
  props: {
    value: {
      type: [Number, String],
      default: "",
    },
    decimalPlaces: {
      type: Number,
      default: 2,
    },
    min: {
      type: Number,
      default: -Infinity,
    },
    max: {
      type: Number,
      default: Infinity,
    },
    allowNegative: {
      type: Boolean,
      default: false,
    },
    onlyInteger: {
      type: Boolean,
      default: false,
    },
  },
  watch: {
    // 监听父组件传递的 value 值变化，并同步到 inputValue
    value(newValue) {
      this.inputValue = newValue;
    },
  },
  methods: {
    handleInput(e) {
      let value = e.target.value;
      if (!this.allowNegative) {
        value = value.replace(/-/g, "");
      }
      if (this.onlyInteger) {
        // 只能输入整数时，去除小数点和非数字字符
        value = value.replace(/[^\d-]/g, "");
      } else {
        // 允许小数时，去除非数字、小数点和负号以外的字符
        value = value.replace(/[^\d.-]/g, "");
      }
      // 保证只有一个负号且在开头
      if (value.indexOf("-") > 0) {
        value = value.replace(/-/g, "");
      }
      if (!this.onlyInteger) {
        // 保证只有一个小数点
        const dotCount = (value.match(/\./g) || []).length;
        if (dotCount > 1) {
          value = value.slice(0, value.lastIndexOf("."));
        }
        // 处理小数点后的位数
        if (value.includes(".")) {
          const parts = value.split(".");
          parts[1] = parts[1].slice(0, this.decimalPlaces);
          value = parts.join(".");
        }
      }
      if (value) {
        const numValue = parseFloat(value);
        if (numValue < this.min) {
          value = this.min.toString();
        } else if (numValue > this.max) {
          value = this.max.toString();
        }
      }

      this.$nextTick(() => {
        this.inputValue = value;
      });
      console.log("NumberInput", value);
      this.$emit("input", value);
    },
  },
};
</script>
