<script setup lang="ts">
import Editor from '@tinymce/tinymce-vue'
import md5 from 'blueimp-md5'
import { getSignature, uploadFile } from '@/api/base'

const props = defineProps({
  height: { type: Number, default: 400 },
  toolbar: { type: Boolean, default: true },
  readonly: { type: Boolean, default: false },
})

const ImageUploadHandler = (blobInfo: any) =>
  new Promise((resolve, reject) => {
    const file = blobInfo.blob()
    getSignature()
      .then((response: any) => {
        const prefix = 'upload/admin/'
        const key = prefix + md5(file.name + new Date().getTime()) + file.name.substr(file.name.lastIndexOf('.'))
        const { accessid, policy, signature, host } = response
        const params = {
          key,
          host,
          OSSAccessKeyId: accessid,
          policy,
          signature,
          success_action_status: '200',
          file,
          url: `${host}/${key}`,
        }
        uploadFile(params)
          .then((res: any) => {
            resolve(res.url)
          })
          .catch(() => {
            reject('上传失败')
          })
      })
      .catch(() => {
        reject('获取Signature失败')
      })
  })

const init = {
  language: 'zh-Hans',
  height: props.height,
  menubar: false,
  statusbar: false,
  plugins: 'table charmap fullscreen lists link code preview quickbars',
  toolbar:
    'undo redo | fontsizeselect lineheight bold italic underline strikethrough forecolor backcolor | link quickimage image media table | align hangingindent indent outdent numlist bullist | charmap  blockquote hr fullscreen | code preview',
  // font_formats:
  //   '微软雅黑=Microsoft YaHei,Helvetica Neue,PingFang SC,sans-serif;苹果苹方=PingFang SC,Microsoft YaHei,sans-serif;宋体=simsun,serif;仿宋体=FangSong,serif;黑体=SimHei,sans-serif;Arial=arial,helvetica,sans-serif;Times New Roman',
  fontsize_formats: '8px 10px 12px 14px 15px 16px 17px 18px 20px 24px',
  lineheight_formats: '0.5 1 1.2 1.5 2',
  images_upload_handler: ImageUploadHandler,
  automatic_uploads: true,
  quickbars_insert_toolbar: false,
  // style_formats: [{ title: '悬挂缩进', block: 'p', styles: { textIndent: '-2em', paddingLeft: '2em' } }],
  content_style: 'img {max-width:100%;}',
}

const init2 = {
  toolbar: false,
  quickbars_insert_toolbar: false,
  menubar: false,
  statusbar: false,
  height: props.height,
  content_style: 'body { font-family:Helvetica,Arial,sans-serif; font-size:13px; }',
  readonly: true,
}
</script>

<template>
  <editor :init="toolbar ? init : init2" v-bind="$attrs" style="width: 100%" />
</template>

<style lang="scss">
.tox-tinymce-aux {
  z-index: 3000 !important;
}
</style>
