<template>
  <div
      ref="editorRef" class="editor" contentEditable="true" v-html="editorText"
      @click="handleClick"
      @input="handleInput"
      @focus="handleFocus"
      @blur="handleBlur"
      style="user-select:text;-webkit-user-select:text;">
  </div>
</template>

<script>
import{onMounted,ref,reactive,toRefs,watch} from "vue";
export default {
  props:{
    modelValue:{type:String,default:''}
  },
  setup(props,{emit}){
    const editorRef=ref(null)

    const data=reactive({
      editorText:props.modelValue,
      isChange:true,
      lastCursor:null,
    })

    watch(()=>props.modelValue,()=>{
      if(data.isChange){
        data.editorText=props.modelValue
      }
    })

    onMounted(()=>{
      editorRef.value.addEventListener('paste',function (e){

      })
    })

    const handleInput=()=>{
      emit('update:modelValue',editorRef.value.innerHTML)

      data.lastCursor=getLastCursor()
    }

    const handleDel=()=>{
      let range
      let sel=window.getSelection()
      if(data.lastCursor){
        sel.removeAllRanges()
        sel.addRange(data.lastCursor)
      }
      range=getLastCursor()
      range.collapse(false)
      document.execCommand('delete')
    }

    const handleClear=()=>{
      editorRef.value.innerHTML=''
      editorRef.value.focus()
    }

    const handleClick=()=>{
      emit('clickFn')

      data.lastCursor=getLastCursor()
    }

    const handleFocus=()=>{
      data.isChange=false
      emit('focusFn')

      data.lastCursor=getLastCursor()
    }

    const handleBlur=()=>{
      data.isChange=true
      emit('blurFn')
    }

    const getLastCursor=()=>{
      let sel=window.getSelection()
      if(sel&&sel.rangeCount>0){
        return sel.getRangeAt(0)
      }
    }

    const insertHtmlAtCursor=(html)=>{

    }

    return{
      ...toRefs(data),
      editorRef,
      handleInput,
      handleDel,
      handleClear,
      handleClick,
    }
  },
  name: "chat"
}
</script>

<style scoped>

</style>