<!--
 * @Author: liuzhenlin 461480418@qq.ocm
 * @Date: 2023-01-10 16:18:28
 * @LastEditors: liuzhenlin
 * @LastEditTime: 2023-01-17 17:44:24
 * @Description: file content
 * @FilePath: \订单全流程管理系统\src\components\currency\index.vue
-->
<template>
  <view>
    <u-input
      v-model="num"
      @blur="inputMoney($event)"
      @change="handleChange"
      @focus="uninputMoney($event)"
      @input="returnNum" />
  </view>
</template>

<script>
  export default {
    name: 'AmountInput',
    props: {
      value: {
        type: [String, Number],
        default: '0',
      },
    },
    data() {
      return {
        num: '',
      }
    },
    watch: {
      value() {
        this.num = this.formatPrice(this.value)
      },
    },
    mounted() {
      this.num = this.formatPrice(this.value)
    },
    methods: {
      returnNum() {
        if (this.num) {
          this.$emit('input', this.CurrencyFomatNumber(this.num))
        }
      },
      handleChange(value) {
        this.$nextTick(() => {
          this.$emit('change', this.CurrencyFomatNumber(value))
        })
      },
      // 失焦显示数字类型
      inputMoney(value) {
        let temp = Number(value) || null
        this.num = this.formatPrice(temp)
      },
      // 获得焦点金额去掉格式
      uninputMoney() {
        this.num = this.CurrencyFomatNumber(this.num)
      },
      //去除千分位中的‘，’
      CurrencyFomatNumber(num, n = 2) {
        let number = num.replace('¥', '')
        if (number != null && number != '' && number != undefined) {
          number = number.replace(/,/g, '') //去除千分位的','
          if (isNaN(number)) {
            //判断是否是数字
            number = '0'
          } else {
            number = Math.round(number * Math.pow(10, n)) / Math.pow(10, n) //n幂
            number = number.toString()
          }
        } else {
          number = '0'
        }
        //a.indexOf(x,y);返回x值在a字符串值中从y位置开始检索首次出现的位置
        var numLength = number.indexOf('.')
        //判断传递的值是整数增加小数点再补"0"
        if (numLength < 0) {
          numLength = number.length
          number += '.'
        }
        //不足n位小数的，循环补"0"
        while (number.length <= numLength + n) {
          number += '0'
        }
        return parseFloat(number)
      },
    },
  }
</script>

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