<script setup>
import { onBeforeUnmount, onMounted, ref, watch } from 'vue'
import tinymce from 'tinymce'
import { REQUEST } from '~/utils/request'

const props = defineProps({
  id: {
    type: String,
    default: `tiny-${Date.now()}-${~~(Math.random() * 10000)}`,
  },
  htmlClass: { default: '', type: String },
  modelValue: String,
  o: {
    default() {
      return {}
    },
    type: Object,
  },
})

const emits = defineEmits(['update:modelValue', 'click:audio', 'click:video', 'click:submit'])

const content = ref('')


let editor = null
let checkerTimeout = null
let isTyping = false

function init() {
  const options = {
    selector: `#${props.id}`,
    base_url: '/tiny',
    language: 'zh-Hans',
    // height: 40,
    // min_height: 40,
    max_height: 200,
    menubar: false,
    statusbar: false,
    // inline: true,
    resize: true,
    body_class: 'tinymce-area',
    toolbar1: 'emoticons',
    plugins: 'image emoticons autoresize',
    autosave_restore_when_empty: false,
    content_style: 'body { margin: 0.4rem; line-height: 1;min-height: 1rem } p { margin: 0; } ',
    setup(_editor) {
      _editor?.on('KeyDown', (e) => {
        if (e.ctrlKey && e.keyCode === 13) {
          e.preventDefault();
          emits('click:submit')
          return
        }
      })
    },
    init_instance_callback: (_editor) => {
      // console.log('init_instance_callback :>> ', _editor?.isNas);

      _editor?.on('KeyUp', (e) => {
        submitNewContent()
      })
      _editor?.on('Change', (e) => {
        if (_editor?.getContent() !== props.modelValue)
          submitNewContent()
      })
      _editor?.on('init', (e) => {
        _editor?.setContent(content.value)
        // emits('input', content.value);
      })
      editor = _editor
    },
    automatic_uploads: true,
    images_upload_handler: (blobInfo, progress) => {
      const file = blobInfo.blob()
      return REQUEST.upload({
        url: '/upload/main/file',
        data: {
          filedata: file,
        },
        onUploadProgress(progressEvent) {
          progress(~~(progressEvent.loaded / progressEvent.total * 100 | 0))
        },
      }).then((res) => {
        if (res.code === '1')
          return window.GLOBAL_CONFIG.oss + (res.data.url)
        else
          return ('')
      })
    },
    // to solve a third party URL
    // paste_preprocess: (editor, args) => {
    //   if (/^https?\:\/\/.+(png|jpg)$/.test(args.content)) {
    //     args.content = uploadByThirdPartyUrl(args.content);
    //   }
    // }
  }
  tinymce.init(Object.assign(options, props.o))
}

function submitNewContent() {
  isTyping = true
  if (checkerTimeout !== null)
    clearTimeout(checkerTimeout)
  checkerTimeout = setTimeout(() => {
    isTyping = false
  }, 300)
  emits('update:modelValue', editor?.getContent())
}

onMounted(() => {
  content.value = props.modelValue
  init()
})

onBeforeUnmount(() => {
  editor?.destroy()
})

defineExpose({
  clear(v = '') {
    editor?.resetContent(v)
  },
})

function handleClickAudioCall() {
  emits('click:audio')
}

function handleClickVideoCall() {
  emits('click:video')
}


const handleAfterRead = (fileProxy) => {
  // const file = blobInfo.blob()
  const { file } = fileProxy
  console.log('file : ', file)
  return REQUEST.upload({
    url: '/upload/main/file',
    data: {
      filedata: file,
    },
    // onUploadProgress(progressEvent) {
    //   progress(~~(progressEvent.loaded / progressEvent.total * 100 | 0))
    // },
  }).then((res) => {
    if (res.code === '1') {   // return window.GLOBAL_CONFIG.oss + (res.data.url)
      editor?.selection.setContent(`<img src="${window.GLOBAL_CONFIG.oss + (res.data.url)}" width="150" />`)
      emits('update:modelValue', editor?.getContent())
    }
    else {
      fileProxy.status = 'failed'
      fileProxy.message = '上传失败'
    }
  })
}

</script>

<template>
  <div class="relative">
    <textarea :id="id" class="tinyarea w-full min-h-42px" v-model="content"></textarea>

    <div class="absolute left-14 top-0 flex z-1000 text-hex-222f3e space-x-1px">

      <div class="cursor-pointer flex_center box-content tbtn">
        <van-uploader :after-read="handleAfterRead" class=" w-6 h-6">
          <i:uil:image-upload class=" w-6 h-6" />
        </van-uploader>
      </div>

      <div @click="handleClickAudioCall" class="cursor-pointer flex_center box-content tbtn ">
        <i:material-symbols:call class="w-6 h-6" />
      </div>
      <div @click="handleClickVideoCall" class="cursor-pointer flex_center box-content tbtn ">
        <i:material-symbols:video-call-outline class=" w-6 h-6" />
      </div>
    </div>
  </div>
</template>

<style lang="scss">
.tinyarea+.tox-tinymce {
  border: none;
  border-radius: 0;
  // height: 42px !important;

  // .tox-editor-header{
  //   display: none;
  // }

  &.tox:not(.tox-tinymce-inline) .tox-editor-header {
    box-shadow: none;
    padding: 0 0;

    .tox-toolbar-overlord .tox-toolbar {
      background: #e4e6eb;
    }
  }

  .tox-tbtn {
    margin-top: 0;
    margin-bottom: 0;
    cursor: pointer;
    width: 40px;
    height: 40px;
    // background: #f3f4f6;
    box-shadow: inset 0 0 0 1px #e4e6eb;
    border-radius: 2px;
  }


}

.tbtn {
  width: 40px;
  height: 40px;
  // background: #f3f4f6;
  box-shadow: inset 0 0 0 1px #e4e6eb;
  border-radius: 2px;
}
</style>
