<template>
<div class="aos-money">
  <el-input
    v-if="editable"
    ref="money"
    class="aos-money-input"
    v-model="copyValue"
    :title="copyValue"
    :minlength="minlength"
    :maxlength="maxlength"
    :placeholder="placeholder"
    :clearable="clearable"
    :size="size"
    :disabled="disabled"
    text-align="right"
    @change="handleChange"
    @blur="handleBlur"
    @focus="handleFocus"
    @clear="handleClear">
    <!-- @input="handleInput" -->
    <template v-if="suffixString || icon" slot="append">
      <span>{{suffixString}}</span>
      <span :title="iconTitle" class="aos-money__icon" @click="handleIconClick" :class="{'aos-money__icon--active': iconActive}">
        <i :class="'el-icon-' + icon"></i>
      </span>
    </template>
  </el-input>
  <div v-else class="el-form-item__content aos-form-input-text">
    <span>{{copyValue}}</span>
    <span style="margin-left: 8px;">{{suffixString}}</span>
  </div>  
</div>
</template>
<script>
import debounce from 'throttle-debounce/debounce';
export default {
  name: 'AosMoney',
  props: {
    editable: {
      type: Boolean,
      default: true
    },
    minlength: {
      type: Number
    },
    maxlength: {
      type: Number
    },
    placeholder: {
      type: String,
      default: '请输入'
    },
    clearable: {
      type:Boolean,
      default: true
    },
    size: {
      type: String,
      default: 'small'
    },
    disabled: {
      type: Boolean,
      default: false
    },
    value: {
      type: [String,Number],
      default: 0
    },
    decimal: {
      type: Number,
      default: 2
    },
    debounce: {
      type: Number,
      default: 300
    },
    suffixString: {
      type: String,
      default: ''
    },
    icon: {
      type: String
    },
    iconTitle: {
      type: String,
      default: ''
    },
    iconActive: {
      type: Boolean,
      default: false
    }
  },
  data(){
    return {
      showIcon: false,
      copyValue: '',
      handleInput(){}
    }
  },
  methods: {
    handleIconClick () {
      this.$emit('icon-click', this.copyValue, this.iconActive)
    },
    unFormatMoney(value){
      if (!value) {
        return ''
      }
      if(value === '0.00'){
          return '0';
      } else {
        return value.split(',').join('');
    }
    },
    formatMoney(value){
      if(!value ){
        if (value === 0) {
          return '0.00'
        } else {
          return ''
        }
      }
      if (value === '0.00') {
        return '0.00'
      }
      if(value.indexOf(',') > -1) return value;
      let floatValue = parseFloat(value)
      if (isNaN(floatValue)) {
        return '0.00'
      }
      floatValue = floatValue + ''
      let isMinus = false
      if (floatValue.startsWith('-')) {
        floatValue = floatValue.split('-')[1]
        isMinus = true
      }
      let formatData;
      // 判断初始值是否有小数点位，以及小数点位数量
      if(floatValue.indexOf('.') > -1){
        let intPart = floatValue.split('.')[0];
        let decPart = floatValue.split('.')[1];
        formatData = this.formatIntPart(intPart) + '.' + this.formatDecPart(decPart);
      } else {
        if(!!floatValue){
          formatData = this.formatIntPart(floatValue) + '.';
          for(let i = 0; i< this.decimal;i++){
            formatData = formatData+'0';
          }
        } else {
          formatData = '0.';
          for(let i = 0; i< this.decimal;i++){
            formatData = formatData+'0';
          }
        }
      }
      if (isMinus) {
        formatData = '-' + formatData
      }
      return formatData;
    },
    formatIntPart(intPart){
      let newIntPart = ''; 
      if(intPart.length > 3){
        let reverseIntStr = intPart.split('').reverse().join('');
        let partArr = reverseIntStr.match(/\d{3}/ig);
        let lastStr = reverseIntStr.split(partArr.join(''))[1];
        if(lastStr !== '' && lastStr !== undefined && lastStr !== null){
          newIntPart = (partArr.join(',') + ',' + lastStr).split('').reverse().join('');
        } else {
          newIntPart = partArr.join(',').split('').reverse().join('');
        }
        if(newIntPart.substring(0,1) === ','){
          newIntPart = newIntPart.substring(1);
        }
      } else {
        newIntPart = intPart;
      }
      return newIntPart;
    },
    formatDecPart(decPart){
      if(decPart.length){
        let length = decPart.length;
        let addLength;
        if(this.decimal > length){
          addLength = this.decimal - length;
          for(let i = 0;i<addLength;i++){
            decPart += '0'
          }
        } else if(this.decimal < length) {
          decPart = parseFloat('0.'+decPart).toFixed(this.decimal).toString().split('.')[1];
        }
      } else {
        for(let i = 0; i< this.decimal;i++){
          decPart += '0';
        }
      }
      return decPart;
    },
    handleChange(){
      this.$emit('change',this.unFormatMoney(this.copyValue),this.copyValue);
    },
    handleBlur(event){
      this.copyValue = this.formatMoney(event.target.value);
      let money = this.getInput();
      this.$nextTick(() => {
        money.value = this.copyValue;
        this.$emit('blur',this.unFormatMoney(this.copyValue), this.copyValue);
      })
    },
    handleFocus(event){
      this.copyValue = this.unFormatMoney(event.target.value);
      this.$emit('focus',this.copyValue);
    },
    handleClear(){
      this.copyValue = this.formatMoney(event.target.value);
      let money = this.getInput();
      this.$nextTick(() => {
        money.value = this.copyValue;
        this.$emit('clear',this.unFormatMoney(this.copyValue), this.copyValue);
      })
    },
    getInput() {
      return this.$refs.money;
    },
  },
  watch: {
    value: {
      handler: function(value, oldVal){
        if (value !== oldVal) {
          if(!value){
            if (value === 0) {
              this.copyValue = '0.00'
            } else {
              this.copyValue = ''
            }
          }
          if(typeof value === 'number'){
            this.copyValue = this.formatMoney(value + '')
          } else if(typeof value === 'string'){
            this.copyValue = this.formatMoney(value)
          }
          this.handleChange()
        }
      },
      immediate: true
    }
  },
  created(){
    this.handleInput = debounce(this.debounce,value => {
      this.copyValue = this.formatMoney(value);
      let money = this.getInput();
      this.$nextTick(() => {
        money.value = this.copyValue;
      })
    });
  }
}
</script>

