<template>
  <div class="ui-textarea" :class="[{'is-worklimit': innerShowWordLimit, 'is-viewable': !editable}]">
    <template v-if="editable">
      <el-input
        class="ui-textarea__input"
        type="textarea"
        ref="input"
        v-model="innerValue"
        :disabled="disabled"
        :autosize="innerAutosize"
        :placeholder="placeholder"
        :show-word-limit="innerShowWordLimit"
        :rows="rows"
        :maxlength="maxlength"
        @change="handleChange"
      >
      </el-input>
    </template>
    <template v-else>{{ innerValue }}</template>
  </div>
</template>
<script>
import Input from 'element-ui/lib/input'
import 'element-ui/lib/theme-chalk/input.css'

export default {
  name: 'UiTextarea',
  components: {
    ElInput: Input
  },
  props: {
    rows: {
      type: Number,
      default: 3
    },
    maxlength: {
      type: [Number, String],
      default: 150
    },
    autosize: {
      type: Boolean,
      default: false
    },
    placeholder: {
      type: String
    },
    value: {
      type: String
    },
    editable: {
      type: Boolean,
      default: true
    },
    disabled: {
      type: Boolean
    }
  },
  computed: {
    innerValue: {
      get() {
        return this.value
      },
      set(val) {
        this.$emit('input', val)
      }
    },
    innerAutosize() {
      return {
        minRows: 4
      }
    },
    innerShowWordLimit() {
      if (this.maxlength) {
        return true
      }
      return false
    }
  },
  methods: {
    handleChange(e) {
      this.$emit('change', {
        value: e
      })
    },
    getSelectionRange() {
      const value = this.value || ''
      let selectionStart = value.length
      let selectionEnd = selectionStart
      if (this.$refs.input && this.$refs.input.$refs.textarea) {
        selectionStart = this.$refs.input.$refs.textarea.selectionStart
        selectionEnd = this.$refs.input.$refs.textarea.selectionEnd
      }
      return {
        start: selectionStart,
        end: selectionEnd
      }
    },
    setSelectionStart(startIndex) {
      if (typeof startIndex !== 'number') {
        return
      }
      if (this.$refs.input && this.$refs.input.$refs.textarea) {
        this.$refs.input.$refs.textarea.setSelectionRange(startIndex, startIndex)
      }
    },
    focus() {
      this.$nextTick(() => {
        this.$refs.input && this.$refs.input.focus && this.$refs.input.focus()
      })
    }
  }
}
</script>
<style lang="less">
.ui-textarea{
  line-height: 1em;
  .el-textarea__inner{
    line-height: 22px;
  }
  &.is-viewable {
    line-height: 22px;
    padding: 5px 0;
    white-space: pre-wrap;
  }
}
</style>
