<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 () {
        console.log('this.value-----', this.inputValue)
        if (this.inputValue) {
            let lastLetter = this.inputValue.charAt(this.inputValue.length - 1) // 获取最后一个字母
            let firstLetter = this.getFirstLetter(this.inputValue)
            console.log('lastLetter--------',lastLetter)
            console.log('firstLetter--------',firstLetter)
            let num = this.inputValue.split(firstLetter)[0].replace(/[a-zA-Z]/g, '') * 1 // 去除字母
            let newValue = null
            if (lastLetter === 'k') {
                newValue = (num * Math.pow(10, 3)).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","); // 转换千分位
            } else if (lastLetter === 'm') {
                newValue = (num * Math.pow(10, 6)).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
            } else if (lastLetter === 'b') {
                newValue = (num * Math.pow(10, 9)).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
            } else {
                newValue = (num * Math.pow(10, 0)).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
            }
            this.inputValue = newValue
            this.inputValueCopy = newValue
        }
    },
    handleFocus () {
        this.inputValue = this.inputValue.replace(/,/g, '')
        this.inputValueCopy = this.inputValue.replace(/,/g, '')
    },
    // 获取第一个字母
    getFirstLetter(str) {
        return str.match(/[a-zA-Z]/)[0];
    }
  }
};
</script>

<style lang="scss" scoped>
</style>