<template>
  <div class="auto-prompt">
    <div class="chat-textarea">
      <div class="chat-bar">
        <div>
          <img
            src="../assets/emojiSmiles-v1-light.png"
            class="icon emoji pointer"
            @click.stop="showEmotion = true"
          />
          <img
            src="../assets/icon_image_s1_01.png"
            @click="upImgfile"
            class="icon emoji pointer"
            alt=""
          />

          <img
            src="../assets/icon_folder_s1_01.png"
            @click="upfile"
            class="icon emoji pointer"
            alt=""
          />
        </div>
        <!-- <div class="chat-bar-right">
          <img
            src="../assets/icon_folder_s1_01.png"
            @click="upfile"
            class="icon emoji"
            alt=""
          />
          快捷回复
        </div> -->
      </div>
      <div
        class="el-autocomplete textarea"
        id="el-autocomplete"
        ref="elAutocomplete"
        contenteditable="true"
        style="outline: none;"
        @paste.prevent="handlePaste"
        @focus="removeDefaultContent"
        @input="handleSelect"
        @blur="addDefaultContent"
      ></div>
    </div>
    <emotion
      v-if="showEmotion"
      style="position: absolute; top:-220px;left:19px; background: #fff;"
      :height="200"
      @emotion="handleEmotion"
    />
    <input
      ref="file"
      style="display: none;"
      type="file"
      @change="fileImgChange"
    />
    <input
      ref="imgFile"
      style="display: none;"
      accept="image/bmp,image/jpeg,image/jpg,image/png"
      type="file"
      @change="fileImgChange"
    />
  </div>
  <!-- accept="image/bmp,image/jpeg,image/jpg,image/png" -->
</template>
<script lang="ts" setup>
import emotion from './IndexComponent.vue'
import { ElLoading } from 'element-plus'
import { ref, watch, defineEmits, defineExpose } from 'vue'
import { upLoadFilesHander } from '../minxins/UploadMixin'
const inputVal = ref('')
const elAutocomplete = ref<any>(null)
const file = ref<any>(null)
const imgFile = ref<any>(null)
const imgShowWidth = ref<number>(50)
const imgShowHeight = ref<number>(50)
const showEmotion = ref<boolean>(false)
const handleEmotion = (i: any) => {
  elAutocomplete.value.innerHTML += i
  inputVal.value = elAutocomplete.value.innerHTML
  showEmotion.value = false
  elAutocomplete.value.focus()
}
const upfile = () => {
  file.value.click()
}
const upImgfile = () => {
  imgFile.value.click()
}
//上传的数据
const fileImgChange = async () => {
  var e: any = window.event || event
  var oFile = e.target.files[0]
  await setfileEvent(oFile)
  const loading: any = ElLoading?.service({
    lock: true,
    text: '上传中...',
    spinner: 'el-icon-loading',
  })
  loading.close()
}
const setfileEvent = async (file: any) => {
  var html = ''
  const { result }: any = await upLoadFilesHander(file)
  const uploadRes = result
  if (!uploadRes) return
  if (file.type.includes('image')) {
    html = await getImageObject(
      uploadRes,
      imgShowWidth.value,
      imgShowHeight.value,
    )
  } else {
    html = await getFileObject(uploadRes, file)
  }
  console.log(html, 'html打印')
  elAutocomplete.value.innerHTML += html.outerHTML
  inputVal.value += html.outerHTML
  elAutocomplete.value.focus()
}

const handleSelect = (value: any) => {
  inputVal.value = value.target.innerHTML
}
const getFileObject = (url: any, oFile: any) => {
  var aTag = document.createElement('a')
  aTag.href = url
  aTag.download = oFile.name
  aTag.target = 'view_window'
  aTag.textContent = oFile.name
  return aTag
}
const emit = defineEmits(['updateState'])
watch(inputVal, async (newValue) => {
  if (!newValue) elAutocomplete.value.innerHTML = ''
  // else elAutocomplete.value.innerHTML = newValue
  emit('updateState', newValue)
})
// 去文本粘贴
const handlePaste = async (event: any) => {
  event.preventDefault()
  const pasteResult = handlePastePlainText(event.clipboardData)
  if (pasteResult) return
  await handlePasteImageFile(event.clipboardData)
}
// 去格式粘贴 文本
const handlePastePlainText = (clipboardData: any) => {
  const text = clipboardData.getData('text/plain')
  if (text) {
    const textNode = document.createTextNode(text)
    cursorInsert(textNode)
    return true
  }
  return false
}
//改变光标位置
const cursorInsert = (node: any) => {
  // 获取光标范围
  const selObj: any = window.getSelection()
  const range = selObj.getRangeAt(0)
  // 光标处插入节点
  range.insertNode(node)
  // 取消insert node 后的选中状态，将光标恢复到 insert node 后面
  range.collapse(false)
  inputVal.value = elAutocomplete.value.innerHTML
}
//粘贴图片
const handlePasteImageFile = async (clipboardData: any) => {
  const img = getPasteImageFile(clipboardData.files)
  if (!img) {
    return
  }
  const uploadRes = await fileToBase64(img)
  if (!uploadRes) {
    return
  }
  const oImage = await getImageObject(
    uploadRes,
    imgShowWidth.value,
    imgShowHeight.value,
  )
  cursorInsert(oImage)
  inputVal.value = elAutocomplete.value.innerHTML
}

// 获取一个 image object
const getImageObject = (uploadRes: any, showWidth: any, showHeight: any) => {
  const oImage = new Image(showWidth, showHeight)
  const datasetFields = ['width', 'height']
  const datasetSizes: any = {
    width: '200',
    height: '200',
  }
  datasetFields.forEach((field) => {
    oImage.setAttribute(`data-${field}`, datasetSizes[field])
  })
  oImage.src = uploadRes
  return oImage
}
const getPasteImageFile = (clipboardDataFiles: any) => {
  if (!clipboardDataFiles.length) {
    return null
  }
  // 剪切版中选择的(用户第一个点的在尾)第一张图片
  const clipboardDataFileList = Array.from(clipboardDataFiles || [])
  let firstSelectedImage = null
  clipboardDataFileList.forEach((file: any) => {
    if (!file.type.match(/image\//i)) {
      return
    }
    firstSelectedImage = file
  })
  return firstSelectedImage
}
//将文件流转base64
const fileToBase64 = function (file: any) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.onload = (event: any) => {
      resolve(event.target.result)
    }
    reader.onerror = (error) => {
      reject(error)
    }
    reader.readAsDataURL(file)
  })
}
const removeDefaultContent = function (event: any) {
  elAutocomplete.value.classList.remove('textarea')
  cursorIn()
}
const addDefaultContent = function (event: any) {
  if (!event.target.innerHTML && event.target.innerText.length == 0) {
    elAutocomplete.value.classList.add('textarea')
  }
}
const cursorIn = function () {
  var divElement: any = document.querySelector('div[contenteditable="true"]')
  var range = document.createRange()
  range.selectNodeContents(divElement)
  range.collapse(false)
  var selection: any = window.getSelection()
  selection.removeAllRanges()
  selection.addRange(range)
}
defineExpose({
  setState(res: any) {
    inputVal.value = res
    elAutocomplete.value.innerHTML = res
  },
  getState() {
    return inputVal.value
  },
})
</script>
<style lang="scss" scoped>
.auto-prompt {
  padding: 12px 28px;
}
.textarea {
  &:after {
    content: attr(placeholder);
    display: inline-block;
    color: #999;
    font-size: 13px;
    vertical-align: middle;
    line-height: 16px;
  }
}
.icon {
  width: 20px;
  height: 20px;
  margin-right: 32px;
}
.chat-bar {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  justify-content: space-between;
}
.el-autocomplete {
  width: 100%;
  max-width: 100%;
  height: calc(100vh - 60vh - 130px);
  overflow: auto;
  font-size: 14px;
}
.el-autocomplete img {
  max-width: 100%; /* 设置图片最大宽度为容器宽度 */
  max-height: 100%; /* 设置图片最大高度为容器高度 */
}
.chat-bar-right {
  font-family: 'PingFang SC';
  font-size: 14px;
  font-style: normal;
  font-weight: 400;
  color: #384860;
  display: flex;
  align-items: center;
  .icon {
    margin-right: 8px;
  }
}


</style>
