<template>
  <div :class="_className">
    <div :class="_inputClassName">
      <textarea
        ref="curTextarea"
        class="hive-input__input-input"
        :disabled="disabled"
        @input="onChange"
        v-bind="$attrs"
      />
      <span
        class="hive-input-textarea__limit"
        v-if="showLimit&&maxLength "
      >{{ curValue.length }}/{{ maxLength }}</span>
    </div>
  </div>
</template>

<script>
import FormSize from '../scripts/mixins/form-size';
import WatchCurValue from '../scripts/mixins/wacth-cur-value';

export default {
  name: 'HiveInputTextarea',
  components: {},
  mixins: [FormSize, WatchCurValue],
  props: {
    value: {
      type: String,
      default: ''
    },
    disabled: Boolean,
    /**
     * 是否错误状态
     */
    error: Boolean,
    /**
     * 自适应高度
     */
    autosize: Boolean,
    /**
     * 字数限制
     */

    maxLength: Number,
    /**
     * 显示字数限制
     */
    showLimit: Boolean
  },
  data() {
    return {
      curValue: this.value,
      curDisabled: this.disabled,
      setSizeT: null
    };
  },
  computed: {
    _className() {
      return [
        'hive-input hive-input-textarea',
        {
          'hive-input--status-error': this.error,
          'hive-input--disabled': this.disabled
        }
      ];
    },
    _inputClassName() {
      return [
        'hive-input__input',
        {
          'hive-input__input--status-error': this.error,
          'hive-input__input--disabled': this.disabled
        }
      ];
    }
  },
  watch: {
    curValue(value) {
      const textareaElem = this.$refs.curTextarea;
      if (textareaElem) {
        textareaElem.style.height = 'auto';
        textareaElem.style.height = textareaElem.scrollHeight + 'px';
      }
      clearTimeout(this.setSizeT);
      this.setSizeT = setTimeout(() => {
        textareaElem.style.height = textareaElem.scrollHeight + 'px';
      }, 10);
    }
  },

  created() {},

  beforeMount() {},
  beforeDestroy() {
    clearTimeout(this.setSizeT);
  },

  methods: {
    onChange(e) {
      const maxLength = this.maxLength;
      if (maxLength && e.target.value.length > maxLength) {
        e.target.value.substr(0, maxLength);
        e.target.value = e.target.value.substr(0, maxLength);
      }
      this.curValue = e.target.value;
      this.$emit('change', this.curTags);
    }
  }
};
</script>
