<template>
  <el-input v-model.trim="money" class="el-input-money" :placeholder="placeholder" :disabled="disabled"
            :readonly="readonly" :clearable="!readonly && !disabled && clearable"
            @blur="onBlue" @focus="onFocus" @change="onChange">
    <template slot="append">
      <slot name="append"></slot>
    </template>
  </el-input>
</template>

<script>



export default {
  name: "ElInputMoney",
  model: {
    prop: 'value',
    event: "update"
  },
  props: {
    // 金额
    value: {type: String|Number, required: true},
    // 单位: 1元, 0.1角, 0.01分
    unit: {type: String|Number, default: 1},
    prefix: {type: String, default: '¥ '},
    placeholder: {type: String},
    clearable: {type: Boolean, default: false},
    readonly: {type: Boolean, default: false},
    disabled: {type: Boolean, default: false},
  },
  watch: {
    value: {
      handler(val) {
        if (val != null && val !== '') {
          this.calcMoney(val * this.unit)
        }
      },
      immediate: true
    }
  },
  data() {
    return {
      money: null,
    }
  },
  methods: {
    onBlue() {
      if (this.disabled || this.readonly) return;
      if (/^[+-]?\d+(\.\d+)?$/.test(this.money)) {
        this.$emit("update", this.money / this.unit);
        this.money = this.formatMoney(this.money);
      } else {
        this.money = null;
        this.$emit("update", null);
      }
      this.$emit("blur");
    },
    onChange() {
      if (this.disabled || this.readonly) return;
      setTimeout(() => this.$emit("change", this.value), 100);
    },
    onFocus() {
      if (this.disabled || this.readonly) return;
      this.$emit("focus");
      if (this.value != null && this.value !== '') this.money = this.value * this.unit;
    },
    calcMoney() {
      if (this.value !== '' && this.value != null) {
        this.money = this.formatMoney(this.value * this.unit);
      }
    },
  }
}
</script>

<style scoped>
</style>
