<template>
  <section class="AiNumber">
    <el-input v-model="num" :size="size" @input.native="validate" @focus="$emit('focus')" @blur="format" clearable
             @change="$emit('change')" :validate-event="isRule"></el-input>
  </section>
</template>

<script>
  export default {
    name: "AiNumber",
    model: {
      prop: "value",
      event: "change"
    },
    props: {
      value: String,
      size: String,
      decimal: {type: [String, Number], default: 2},
      isRule: {type: Boolean, default: true}
    },
    computed: {
      validRegex() {
        let dec = Number(this.decimal || 0),
            regex = `^(\\d*\\.?\\d{0,${dec}}).*`
        return new RegExp(regex)
      }

    },
    data() {
      return {
        num: ""
      }
    },
    methods: {
      validate() {
        let num = JSON.parse(JSON.stringify(this.num))
        this.num = num.replace(this.validRegex, '$1')
      },
      format() {
        this.num = Number(this.num||0).toString()
        this.$emit("blur")
      }
    },
    watch: {
      num(v) {
        this.$emit("change", v)
      }
    },
    mounted() {
      this.num = this.value
    }
  }
</script>

<style lang="scss" scoped>
  .AiNumber {
  }
</style>
