<template>
  <el-input
    ref="input"
    v-model="value"
    v-bind="trimAttrs($attrs)"
    :class="isUnderline ? 'underline' : ''"
    :show-word-limit="hasLengthLimitHint"
    @focus="$emit('focus')"
    @blur="$emit('blur')"
    @clear="$emit('clear')"
    @input="$emit('input')"
  >
    <template slot="prepend">
      <slot name="prepend" />
    </template>
    <template slot="prefix">
      <slot name="prefix" />
    </template>
    <slot />
    <template slot="suffix">
      <slot name="suffix" />
    </template>
    <template slot="append">
      <slot name="append" />
    </template>
  </el-input>
</template>

<script>
import { Input } from 'element-ui';
export default {
  name: 'JskInput',
  components: {
    ElInput: Input
  },
  inheritAttrs: false,
  model: {
    prop: 'vModel',
    event: 'change'
  },
  props: {
    vModel: [String, Number],
    isUnderline: {
      type: Boolean,
      default: false
    },
    hasLengthLimitHint: {
      type: Boolean,
      default: false
    }
  },
  data: function() {
    return {
      value: ''
    };
  },
  watch: {
    value: function() {
      this.$emit('change', this.value);
      this.$nextTick(() => {
        if (this.value !== this.vModel) {
          this.value = this.vModel;
        }
      });
    },
    vModel: function() {
      this.value = this.vModel;
    }
  },
  created: function() {
    this.value = this.vModel;
  },
  methods: {
    trimAttrs: function(attrs) {
      Object.keys(attrs).forEach((key) => {
        let prefixes = ['is-', 'has-', 'input-'];
        prefixes.forEach((prefix) => {
          if (key.substr(0, prefix.length) === prefix) {
            attrs[key.substr(prefix.length)] = attrs[key];
          }
        })
      })
      return attrs;
    },
    focus: function() {
      this.$refs.input.focus()
    },
    blur: function() {
      this.$refs.input.blur()
    },
    select: function() {
      this.$refs.input.select()
    }
  }
}
</script>

<style lang="scss" src="../../theme/input.scss"></style>
