<template>
  <el-input-number
    :ref="metadata.columnName"
    v-model="value"
    type="number"
    :min="minValue"
    :max="maxValue"
    :placeholder="metadata.help"
    :disabled="isDisabled"
    :precision="precision"
    controls-position="right"
    :class="'display-type-' + cssClass"
    @change="preHandleChange"
  />
</template>

<script>
import { fieldMixin } from '@/components/ADempiere/Field/FieldMixin'
import { FIELDS_FLOATS } from '@/components/ADempiere/Field/references'

export default {
  name: 'FieldNumber',
  mixins: [fieldMixin],
  data() {
    // value render
    let value = this.metadata.value
    if (this.metadata.inTable) {
      value = this.valueModel
    }
    value = this.validateValue(value)
    return {
      value: value,
      showControls: true
    }
  },
  computed: {
    maxValue() {
      if (this.isEmptyValue(this.metadata.valueMax)) {
        return Infinity
      }
      return Number(this.metadata.valueMax)
    },
    minValue() {
      if (this.isEmptyValue(this.metadata.valueMin)) {
        return -Infinity
      }
      return Number(this.metadata.valueMin)
    },
    cssClass() {
      return this.metadata.referenceType
        .split(/(?=[A-Z])/)
        .join('-').toLowerCase()
    },
    precision() {
      // Amount, Costs+Prices, Number
      if (FIELDS_FLOATS.includes(this.metadata.referenceType)) {
        return 2
      }
      return undefined
    }
  },
  watch: {
    // enable to dataTable records
    valueModel(value) {
      if (this.metadata.inTable) {
        this.value = this.validateValue(value)
      }
    },
    'metadata.value'(value) {
      if (!this.metadata.inTable) {
        this.value = this.validateValue(value)
      }
    }
  },
  methods: {
    validateValue(value) {
      if (this.isEmptyValue(value) || isNaN(value)) {
        return undefined
      }
      return Number(value)
    }
  }
}
</script>

<style lang="scss">
  /* if is controls width 100% in container */
  .el-input-number, .el-input {
    width: 100% !important; /* ADempiere Custom */
  }

  /** Amount reference **/
  .display-type-amount {
    text-align: right !important;
    input, .el-input__inner {
      text-align: right !important;
    }
  }
</style>
