<template>
  <view class="d-flex flex-column h-100vh">
    <sp-editor
      :toolbar-config="{
        excludeKeys: ['direction', 'date', 'lineHeight', 'letterSpacing', 'listCheck'],
        iconSize: '18px'
      }"
      @init="initEditor"
      @input="inputOver"
      @upinImage="upinImage"
      @overMax="overMax"
    ></sp-editor>
    
    <view class="d-flex flex-row align-center gap-s p-3">
      <Button :innerStyle="{ flex: '1' }" @click="cancel">取消</Button>
      <Button :innerStyle="{ flex: '1' }" type="primary" @click="save">保存</Button>
    </view>
    <XBarSpace />
  </view>
</template>

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

function cancel() {
  confirm({
    title: '提示',
    content: '是否放弃编辑？',
  }).then((res) => {
    if (res)
      back();
  })
}
function save() {
  console.log('save', currentContent);
  
  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; }) {
  // 若设置了最大字数限制，可在此处触发超出限制的回调
  console.log('==== overMax :', e)
}
function initEditor(editor: any) {
  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) {
  CommonContent.uploadFile(
  // #ifdef MP-WEIXIN
  // 注意微信小程序的图片路径是在tempFilePath字段中
    tempFiles[0].tempFilePath
  // #endif
  // #ifndef MP-WEIXIN
    tempFiles[0].path
    // #endif
    , 'image', 'file').then((res) => {
      editorCtx.insertImage({
        src: res.fullurl,
        width: '80%', // 默认不建议铺满宽度100%，预留一点空隙以便用户编辑
        success: function () {}
      })
    }).catch((err) => {
      toast('上传图片失败')
      console.error('uploadFile error', err);
    });
    return;
}
</script>