<template>
  <el-input
    :value="innerValue"
    :placeholder="placeholder"
    :size="size"
    :disabled="disabled"
    clearable
    inputmode="decimal"
    @input="onInput"
    @blur="onBlur"
  />
</template>

<script>
export default {
  name: "DecimalInput",
  props: {
    value: {
      type: [String, Number, null],
      default: null,
    },
    precision: {
      type: Number,
      default: 0,
    },
    min: {
      type: Number,
      default: 0,
    },
    max: {
      type: Number,
      default: 99999999,
    },
    placeholder: {
      type: String,
      default: "",
    },
    size: {
      type: String,
      default: "",
    },
    disabled: {
      type: Boolean,
      default: false,
    },
  },
  computed: {
    innerValue() {
      return this.value === null || this.value === undefined ? "" : String(this.value);
    },
  },
  methods: {
    normalizeDecimalString(raw) {
      const s = raw === null || raw === undefined ? "" : String(raw);
      if (s === "") return "";

      const cleaned = s
        .replace(/[^\d.]/g, "")
        .replace(/^(\.)/, "0.")
        .replace(/(\..*)\./g, "$1");

      const parts = cleaned.split(".");
      if (parts.length === 2) {
        const intPart = parts[0] === "" ? "0" : parts[0];
        const decPart = parts[1].slice(0, this.precision);
        return `${intPart}.${decPart}`;
      }
      return parts[0];
    },
    onInput(val) {
      const normalized = this.normalizeDecimalString(val);
      this.$emit("input", normalized === "" ? null : normalized);
    },
    onBlur() {
      const v = this.value === null || this.value === undefined ? "" : String(this.value);
      if (v === "") {
        this.$emit("input", null);
        this.$emit("change", null);
        this.$emit("blur");
        return;
      }
      let n = Number(v);
      if (Number.isNaN(n)) {
        this.$emit("input", null);
        this.$emit("change", null);
        this.$emit("blur");
        return;
      }
      if (n < this.min) n = this.min;
      if (this.max !== null && this.max !== undefined && n > this.max) n = this.max;
      const fixed = n.toFixed(this.precision);
      this.$emit("input", fixed);
      this.$emit("change", fixed);
      this.$emit("blur");
    },
  },
};
</script>
