<template>
  <div class="kole-numrange" :class="{ 'is-error': !!errorMsg }">
    <input type="number" :value="value[0]" :step="step" :min="min" :max="max"
           :placeholder="placeholder[0]" @input="onMin" />
    <span class="kole-numrange-sep">{{ separator }}</span>
    <input type="number" :value="value[1]" :step="step" :min="min" :max="max"
           :placeholder="placeholder[1]" @input="onMax" />
    <span class="kole-numrange-unit" v-if="unit">{{ unit }}</span>
    <span class="kole-numrange-msg" v-if="errorMsg">{{ errorMsg }}</span>
  </div>
</template>

<script>
export default {
  name: 'KoleNumberRangeInput',
  props: {
    value: { type: Array, default: function () { return ['', '']; } },
    step: { type: Number, default: 1 },
    min: { type: Number, default: -Infinity },
    max: { type: Number, default: Infinity },
    separator: { type: String, default: '—' },
    unit: { type: String, default: '' },
    placeholder: { type: Array, default: function () { return ['最小', '最大']; } }
  },
  data: function () { return { errorMsg: '' }; },
  methods: {
    emit: function (arr) { this.$emit('input', arr); },
    onMin: function (e) {
      var arr = [e.target.value, this.value[1]];
      this.validate(arr);
      this.emit(arr);
    },
    onMax: function (e) {
      var arr = [this.value[0], e.target.value];
      this.validate(arr);
      this.emit(arr);
    },
    validate: function (arr) {
      var a = parseFloat(arr[0]), b = parseFloat(arr[1]), err = '';
      if (arr[0] !== '' && (a < this.min || a > this.max)) err = '最小值需在 ' + this.min + '~' + this.max;
      else if (arr[1] !== '' && (b < this.min || b > this.max)) err = '最大值需在 ' + this.min + '~' + this.max;
      else if (arr[0] !== '' && arr[1] !== '' && a > b) err = '最小值不能大于最大值';
      this.errorMsg = err;
      this.$emit('error', err);
    }
  }
};
</script>

<style src="./NumberRangeInput.css"></style>
