<template>
  <FlexCol height="100vh">
    <sp-editor
      :toolbar-config="{
        excludeKeys: ['direction', 'date', 'lineHeight', 'letterSpacing', 'listCheck'],
        iconSize: '18px'
      }"
      :maxlength="maxLength"
      @init="initEditor"
      @input="inputOver"
      @upinImage="upinImage"
      @overMax="overMax"
    />
    
    <FlexRow align="center" :padding="18" :gap="15">
      <Button :innerStyle="{flex:1}" type="danger" @click="cancel">取消</Button>
      <Button :innerStyle="{flex:1}" type="primary" @click="save">保存</Button>
    </FlexRow>
    <XBarSpace />
  </FlexCol>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { confirm } from '@/components/utils/DialogAction';
import { back, backAndCallOnPageBack } from '@/components/utils/PageAction';
import { showError } from '@/common/composeabe/ErrorDisplay';
import spEditor from '@/uni_modules/sp-editor/components/sp-editor/sp-editor.vue';
import XBarSpace from '@/components/layout/space/XBarSpace.vue';
import Button from '@/components/basic/Button.vue';
import CommonContent from '@/api/CommonContent';
import FlexCol from '@/components/layout/FlexCol.vue';
import FlexRow from '@/components/layout/FlexRow.vue';

const maxLength = ref(-1);

function cancel() {
  confirm({
    title: '提示',
    content: '是否放弃编辑？',
  }).then((res) => {
    if (res)
      back();
  })
}
function save() {
  uni.setStorage({
    key: 'editorContent',
    data: currentContent,
    success: () => backAndCallOnPageBack('editor', {}),
    fail: (e) => showError(e),
  })
}

let currentContent = '';

/**
* 获取输入内容
*/
function inputOver(e: { html: string; text: string; }) {
  // 可以在此处获取到编辑器已编辑的内容
  currentContent = e.html;
}
/**
 * 超出最大内容限制
 * @param {Object} e {html,text} 内容的html文本，和text文本
 */
function overMax(e: { html: string; text: string; }) {
  // 若设置了最大字数限制，可在此处触发超出限制的回调
  
}
function initEditor(editor: any) {
  uni.getStorage({
    key: 'editorMaxLength',
    success: (success) => {
      maxLength.value = parseInt(success.data);
    },
  })
  uni.getStorage({
    key: 'editorContent',
    success: (success) => {
      editor.setContents({
        html: success.data
      })
    },
  })
}
/**
 * 直接运行示例工程插入图片无法正常显示的看这里
 * 因为插件默认采用云端存储图片的方式
 * 以$emit('upinImage', tempFiles, this.editorCtx)的方式回调
 * @param {Object} tempFiles
 * @param {Object} editorCtx
 */
function upinImage(tempFiles: any, editorCtx: any) {
  let path;
  // #ifdef MP-WEIXIN
  path = tempFiles[0].tempFilePath; 
  // #endif
  // #ifndef MP-WEIXIN
  path = tempFiles[0].path;
  // #endif

  console.log('==== upinImage :', path);
  
  CommonContent.uploadFile(path, 'image', 'file').then((res) => {
    editorCtx.insertImage({
      src: res.fullurl,
      width: '80%',
      success: function () {}
    })
  }).catch((e) => showError(e));
}
</script>