<template>
  <div>
    <el-input
      v-show="isEdit"
      class="cms-form__amount"
      v-model="currentValue"
      v-bind="$attrs"
      ref="validInput"
      @blur="handleValueBlur"
    >
      <template slot="prepend">
        <slot name="prepend">
          <i class="fa fa-jpy" style="font-size: 16px"></i>
        </slot>
      </template>
      <template slot="append">
        <slot name="append"></slot>
      </template>
    </el-input>
    <el-input
      v-show="!isEdit"
      class="cms-form__amount"
      v-model="displayValue"
      v-bind="$attrs"
      @focus="handleDisplayFocus">
      <template slot="prepend">
        <slot name="prepend">
          <i class="fa fa-jpy" style="font-size: 16px"></i>
        </slot>
      </template>
      <template slot="append">
        <slot name="append"></slot>
      </template>
    </el-input>
  </div>
</template>
<script>
/** 金额编辑组件 */
export default {
  name: 'CmsFormAmount',
  /**
   * 属性参数
   * @member props
   * @property {number|string} [value] 原始值
   * @property {number} [precision=0] 精度，保留几位小数
   * @property {string} [separator=,] 分隔值的符号，默认值为‘,’（英文逗号）
   * @property {string} [prefix] 前缀内容，也可以用插槽定义
   * @property {string} [suffix] 后缀内容，也可以用插槽定义
   * @property {boolean} [percentage] 按百分比计算显示, 如value=0.2, 显示为 20%
   */
  props: {
    // 数字
    value: [ Number, String ],
    // 精度，保留几位小数
    precision: {
      type: Number,
      default: 2,
    },
    // 分隔符
    separator: {
      type: String,
      default: ',',
    },
    // 按百分比显示
    percentage: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      isEdit: false, // 默认显示格式化后内容
    }
  },
  created() {
    this.handleValueBlur();
  },
  computed: {
    currentValue: {
      get() {
        return this.value;
      },
      set(value) {
        this.$emit('input', value);
      }
    },
    displayValue: {
      get() {
        let thousandsFormat = this.numberFormat(this.currentValue, this.precision, this.separator)
        if (this.percentage) {
          thousandsFormat = this.currentValue * 100 + '%'
        }
        return thousandsFormat;
      },
      set(value) {
        this.currentValue = this.parseAmount(value);
      }
    }
  },
  methods: {
    // 显示格式化的值
    handleValueBlur() {
      let thousandsFormat = this.numberFormat(this.currentValue, this.precision, this.separator)
      if (this.percentage) {
        thousandsFormat = this.currentValue * 100 + '%'
      }
      this.displayValue = thousandsFormat
      this.isEdit = false
    },
    // 开启编辑
    handleDisplayFocus() {
      const me = this
      this.isEdit = true
      this.currentValue = this.parseAmount(this.displayValue);
      setTimeout(() => {
        me.$refs.validInput.focus()
      }, 100)
    },
    /*
     * 金额格式化：
     * number：要格式化的数字
     * decimals：保留几位小数
     * thousandsSep：千分位符号
     * tdecPoint：小数点符号
     * */
    numberFormat(number, decimals = 2, thousandsSep = ',', tdecPoint = '.') {
      if (!number) return undefined;
      number = parseFloat(number + '').toFixed(decimals);
      // 获取整数部分
      const intPart = Math.trunc(number)
      // 整数部分处理，增加,
      const intPartFormat = intPart.toString().replace(/(\d)(?=(?:\d{3})+$)/g, '$1' + thousandsSep)
      // 预定义小数部分
      let floatPart = ''
      // 将数值截取为小数部分和整数部分
      const valueArray = number.toString().split(tdecPoint)
      if (valueArray.length === 2) { // 有小数部分
        floatPart = valueArray[1].toString() // 取得小数部分
        return intPartFormat + '.' + floatPart
      }
      return intPartFormat + floatPart
    },
    parseAmount(val) {
      if (!val) return undefined;
      return val.replace(this.cancelFillReg, '$1').replace(/\$\s?|(,*)/g, '');
    },
  },
}
</script>
<style lang="scss">
.cms-form__amount {
  .el-input__inner {
    text-align: right !important;
  }
}
</style>