<template>
    <el-input type="text" v-model="inputValue" :disabled="disabled" @input="handleInput" @blur="handleBlur" @focus="handleFocus" />
  </template>
  
  <script>
  export default {
  name: 'numberInput',
  props: {
    value: {
        type: [Number, String],
        default: null
    },
    digit: {
        type: Number,
        default: 0
    },
    disabled: {
        type: Boolean,
        default: false
    }
  },
  data() {
    return {
        inputValue: '',
        inputValueCopy: ''
    };
  },
  mounted() {
    this.inputValue = this.value ? this.value.toLocaleString('en-US', {
                minimumFractionDigits: this.digit,
                maximumFractionDigits: this.digit
            }) : '' // 转换千分位
  },
  methods: {
    handleInput(value) {
        // 使用正则表达式限制只能输入数字、指定英文和一个小数点
        const regex = /^[0-9bkmBKM]*\.?[0-9bkmBKM]*$/
        // 如果输入的值不符合正则规则，则回退到上一次的值
        if (!regex.test(value)) {
            this.inputValue = this.inputValueCopy
        } else {
            this.inputValue = value
            this.inputValueCopy = value
        }
    },
    handleBlur () {
        if (this.inputValue) {
            let lastLetter = this.getLastLetter(this.inputValue)
            let firstLetter = this.getFirstLetter(this.inputValue)
            let num = firstLetter ? (this.inputValue.split(firstLetter)[0].replace(/[a-zA-Z]/g, '') * 1) : (this.inputValue.replace(/[a-zA-Z]/g, '') * 1) // 去除字母
            let unit = 0
            if (lastLetter === 'k') {
                unit = 3
            } else if (lastLetter === 'm') {
                unit = 6
            } else if (lastLetter === 'b') {
                unit = 9
            }
            this.inputValue = (num * Math.pow(10, unit)).toLocaleString('en-US', {
                minimumFractionDigits: this.digit,
                maximumFractionDigits: this.digit
            }) // 转换千分位
        }
        this.$emit('getNumberValue', this.inputValue)
    },
    handleFocus () {
        this.inputValue = this.inputValueCopy = this.inputValue.replace(/,/g, '')
    },
    // 获取第一个字母
    getFirstLetter(str) {
        return str.match(/[a-zA-Z]/)?.[0] || ''
    },
    // 获取最后一个字母
    getLastLetter(str) {
        const letters = str.match(/[a-zA-Z]/g) // 使用正则表达式匹配所有字母
        if (letters) {
            return letters[letters.length - 1] // 返回最后一个字母
        }
        return ''
    }
  }
  };
  </script>
  
  <style lang="scss" scoped>
  </style>