<template>
<div class="drip-input">
  <textarea
    :placeholder="placeholder || ''"
    :maxlength="maxlength || ''"
    @focus="focus(currentValue)"
    @blur="blur(currentValue)"
    @input="update(currentValue)"
    @click="clickInput(currentValue)"
    v-model="currentValue"
    ref="input"
    v-if="type === 'textarea'"
    :style="style">
  </textarea>
</div>
</template>

<script>
import create from '../utils/create'
import { isObj } from '../utils/index'
export default create({
  name: 'input',
  props: {
    placeholder: {
      type: [String, Number]
    },
    maxlength: {
      type: Number
    },
    value: {
      type: [String, Number],
    },
    type: {
      type: String
    },
    style: {
      type: Object
    },
    autosize: {
      type: [Boolean, Object]
    }
  },
  data () {
    return {
      currentValue: this.value
    }
  },
  watch: {
    currentValue(val) {
      this.$nextTick(this.adjustSize)
      this.$emit('input', val)
    }
  },
  mounted() {
    this.$nextTick(this.adjustSize);
  },
  methods: {
    adjustSize() {
      const { input } = this.$refs;
      if (!(this.type === 'textarea' && this.autosize) || !input) {
        return;
      }

      input.style.height = 'auto';

      let height = input.scrollHeight;

      if (isObj(this.autosize)) {
        const { maxHeight, minHeight } = this.autosize;
        if (maxHeight) {
          height = Math.min(height, maxHeight);
        }
        if (minHeight) {
          height = Math.max(height, minHeight);
        }
      }

      if (height) {
        input.style.height = height + 'px';
      }
    },
    focus (val) {
      this.$emit('focus', val)
    },
    blur (val) {
      this.$emit('blur', val)
    },
    clickInput (val) {
      this.$emit('click', val)
    },
    update (val) {
      this.$emit('input', val)
    }
  }
})
</script>
