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

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