<template>
    <div>
      <input type="text" v-model="inputValue" @input="handleInput" @blur="handleBlur" @focus="handleFocus">
    </div>
</template>

<script>
export default {
  name: 'x-input',
  data() {
    return {
        inputValue: '',
        inputValueCopy: ''
    };
  },
  mounted() {
  },
  methods: {
    handleInput(event) {
        let value = event.target.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
            }
            let newValue = (num * Math.pow(10, unit)).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","); // 转换千分位
            this.inputValue = newValue
        }
    },
    handleFocus () {
        this.inputValue = this.inputValue.replace(/,/g, '')
        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>