<template>
  <div class="uif-input-step clearfix" :class="'uif-input-step-' + size">
    <u-icon type="minus" :class="{ available: ma }" @click="onChange(ma, currentValue - step)"></u-icon>
    <u-input :size="size" :disabled="disabled" v-model="currentValue" number @blur="setUpdate" @keyup.enter="setUpdate"></u-input>
    <u-icon type="plus" :class="{ available: pa }" @click="onChange(pa, currentValue + step)"></u-icon>
  </div>
</template>

<script>
import { oneOf } from '@uif/hq/src/utils/assist'
import UInput from '@uif/hq/src/components/input'
import { getStepValue } from '../input/format'

export default {
  name: 'u-input-step',
  components: {
    UInput
  },
  props: {
    size: {
      validator (value) {
        return oneOf(value, ['small', 'default', 'large'])
      },
      default: 'default'
    },
    value: {
      type: [Number, String],
      default: ''
    },
    // 最小值
    min: {
      type: Number,
      default: 0
    },
    // 最大值
    max: {
      type: Number,
      default: 0
    },
    // 步进
    step: {
      type: Number,
      default: 0
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      currentValue: this.value
    }
  },
  computed: {
    ma () {
      return !this.disabled && this.currentValue > this.min
    },
    pa () {
      return !this.disabled && this.currentValue < this.max
    }
  },
  watch: {
    value () {
      if (this.value !== this.currentValue) {
        this.setChange(this.value)
      }
    }
  },
  created () {
    this.setUpdate()
    this.$watch('min', this.setUpdate)
    this.$watch('max', this.setUpdate)
    this.$watch('step', this.setUpdate)
  },
  methods: {
    setUpdate () {
      this.setChange(this.currentValue)
    },
    setChange (value) {
      this.currentValue = getStepValue(value, this.step, this.min, this.max)
      if (this.value !== this.currentValue) {
        this.$emit('input', this.currentValue)
        this.$emit('change', this.currentValue)
      }
    },
    onChange (available, value) {
      if (available) {
        this.setChange(value)
      }
    }
  }
}
</script>
