<template>
  <el-input v-model="internalValue" @input="handleInput" @blur="handleBlur" :placeholder="placeholder" :disabled="disabled" type="text" />
</template>

<script>
export default {
  name: 'DecimalInput',
  props: {
    value: {
      type: [Number, String],
      default: ''
    },
    decimalDigits: {
      type: Number,
      default: 0
    },
    placeholder: {
      type: String,
      default: '请输入'
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      internalValue: this.value !== null && this.value !== undefined ? String(this.value) : ''
    };
  },
  watch: {
    value(newVal) {
      // 外部值变化时同步到内部（但不做格式化，避免干扰用户输入）
      if (newVal === '' || newVal == null) {
        this.internalValue = '';
      } else {
        this.internalValue = String(newVal);
      }
    }
  },
  methods: {
    handleInput(val) {
      if (val === '') {
        this.internalValue = '';
        this.$emit('input', '');
        return;
      }

      // 1. 清除非合法字符（只保留数字、小数点、开头的负号）
      let cleaned = val
        .replace(/[^\d.-]/g, '')
        .replace(/^(-)\1+/, '$1'); // 只允许一个开头的负号

      // 2. 处理多个小数点：只保留第一个
      const dotIndex = cleaned.indexOf('.');
      if (dotIndex !== -1) {
        const beforeDot = cleaned.slice(0, dotIndex);
        const afterDot = cleaned.slice(dotIndex + 1).replace(/\./g, ''); // 移除后面所有小数点
        cleaned = beforeDot + '.' + afterDot;
      }

      // 3. 限制小数位数（仅当有小数点时）
      if (this.decimalDigits > 0 && cleaned.includes('.')) {
        const parts = cleaned.split('.');
        let integerPart = parts[0];
        let decimalPart = parts[1] || '';

        // 限制小数位长度
        if (decimalPart.length > this.decimalDigits) {
          decimalPart = decimalPart.slice(0, this.decimalDigits);
        }

        // 关键修复：即使 decimalPart 为空（如 "1."），也要保留小数点！
        cleaned = integerPart + '.' + decimalPart;
      } else if (this.decimalDigits === 0) {
        // 不允许小数，移除小数点及之后内容
        cleaned = cleaned.split('.')[0];
      }

      // 4. 处理以 . 或 -. 开头的情况
      if (cleaned === '.') {
        cleaned = '0.';
      } else if (cleaned === '-.') {
        cleaned = '-0.';
      } else if (cleaned.startsWith('.')) {
        cleaned = '0' + cleaned;
      } else if (cleaned.startsWith('-.')) {
        cleaned = '-0.' + cleaned.slice(2);
      }

      // 5. 去掉整数部分的前导零（但保留单个 0 或负数中的 -0）
      if (cleaned.includes('.')) {
        // 有小数点时，整数部分可以是 0 或 -0
        const parts = cleaned.split('.');
        let intPart = parts[0];
        if (intPart === '' || intPart === '-') {
          intPart = intPart + '0';
        } else if (/^-?0+\d/.test(intPart)) {
          // 如 -0012 → -12，0012 → 12
          intPart = intPart.replace(/^-?0+(\d)/, '$1');
        }
        cleaned = intPart + '.' + parts[1];
      } else {
        // 无小数点
        if (/^-?0+\d/.test(cleaned)) {
          cleaned = cleaned.replace(/^-?0+(\d)/, '$1');
        }
      }

      this.internalValue = cleaned;

      // emit 值（可能是数字、空字符串、或 '-'）
      if (cleaned === '' || cleaned === '-') {
        this.$emit('input', cleaned === '-' ? '-' : '');
      } else {
        const num = parseFloat(cleaned);
        if (!isNaN(num)) {
          this.$emit('input', num);
        } else {
          this.$emit('input', '');
        }
      }
    },

    handleBlur() {
      let finalValue = this.internalValue.trim();

      if (finalValue === '' || finalValue === '-') {
        this.internalValue = '';
        this.$emit('input', '');
        return;
      }

      const num = parseFloat(finalValue);
      if (isNaN(num)) {
        this.internalValue = '';
        this.$emit('input', '');
        return;
      }

      // 在 blur 时才做 toFixed（四舍五入 + 补零）
      const formatted = num.toFixed(this.decimalDigits);
      this.internalValue = formatted;
      // emit 数字类型（也可 emit 字符串，根据需求）
      this.$emit('input', parseFloat(formatted));
      this.$emit('blur', parseFloat(formatted));
    }
  }
};
</script>