<template>
  <div
    class="edit-div"
    :contenteditable="true"
    @focus="handleFocus"
    @blur="handleBlur"
    @keydown="handleKeyDown"
    @input="changeText"
    v-html="innerText"
    ref="chatInput"
  ></div>
</template>
<script>
import { mapState, mapMutations } from 'vuex'
export default {
  name: 'editDiv',
  props: {
    value: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      innerText: this.value,
      isLocked: true
    }
  },
  watch: {
    value (to, from) {
      if (!this.isLocked || !this.innerText) {
        this.innerText = this.value
      }
    },
    chatInputFocus (val, newval) {
      let ele = this.$refs.chatInput
      if (val) {
        if (document.activeElement !== ele) {
          this.placeEnd(ele)
          ele.focus()
          // hack--<br>标签光标不换行
          if (/(<br>|<\/br>|<\/ br>)$/.test(ele.innerHTML)) {
            document.execCommand('insertParagraph', false)
          }
        }
      } else {
        if (document.activeElement === ele) {
          ele.blur()
        }
      }
    }
  },
  methods: {
    ...mapMutations(['updateChatInputFocus']),
    changeText (e) {
      this.$emit('input', this.$el.innerHTML)
      this.$nextTick(() => {
        var range = window.getSelection()
        range.selectAllChildren(e.target)
        range.collapseToEnd()
      })
    },
    handleFocus () {
      this.isLocked = true
    },
    handleBlur () {
      this.isLocked = false
      this.updateChatInputFocus(false)
    },
    handleKeyDown (e) {
      var ctrlKey = e.ctrlKey || e.metaKey
      if (e.code === 'Enter' && ctrlKey) {
        this.$emit('nextLine')
        this.$nextTick(() => {
          this.placeEnd(e.target)
        })
        return false
      }
      // 发送
      if (e.code === 'Enter') {
        // 阻止换行
        this.innerText = ''
        e.preventDefault()
        this.$emit('sendMsg')
      }
    },
    placeEnd (el) {
      var range = document.createRange()
      range.selectNodeContents(el)
      range.collapse(false)
      var sel = window.getSelection()
      sel.removeAllRanges()
      sel.addRange(range)
    }
  },
  computed: {
    ...mapState({
      chatInputFocus: state => state.group.chatInputFocus
    })
  }
}
</script>
<style lang="scss" scoped>
.edit-div {
  height: 90px;
  line-height: 24px;
  overflow-y: auto;
  overflow-x: hidden;
  padding-left: 20px;
  outline: none;
  border: 0;
  font-size: 14px;
  margin: 0;
  white-space: pre;
}
</style>
