<template>
    <div>
        <div style="border: 1px solid #ccc; margin-top: 10px;">
            <Toolbar
                :editor="editorRef"
                :defaultConfig="toolbarConfig"
                :mode="mode"
                style="border-bottom: 1px solid #ccc"
            />
            <Editor
                :defaultConfig="editorConfig"
                :mode="mode"
                v-model="valueHtml"
                :style="editorStyle"
                @onCreated="handleCreated"
                @onChange="handleChange"
                @onDestroyed="handleDestroyed"
                @onFocus="handleFocus"
                @onBlur="handleBlur"
                @customAlert="customAlert"
                @customPaste="customPaste"
            />
        </div>
    </div>
</template>

<script>
import '@wangeditor/editor/dist/css/style.css'
import { onBeforeUnmount, ref, shallowRef, onMounted ,watch, computed} from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'

export default {
  components: { Editor, Toolbar },
  props:["value","myConfig"],
  setup(props, context) {
    // 编辑器实例，必须用 shallowRef，重要！
    const editorRef = shallowRef()
    const readOnly = ref(true);
    // 内容 HTML
    const valueHtml = ref('')

    const myConfig = computed(()=>{
        return  props.myConfig; 
    })
    if (myConfig.value.readOnly !== undefined) {
        readOnly.value = myConfig.value.readOnly;
    }
    // 模拟 ajax 异步获取内容
    onMounted(() => {
        setTimeout(() => {
            const editor = editorRef.value
            if (editor == null) return
            if (readOnly.value) {
                editor.disable()
            } else {
                editor.enable()
            }
        }, 1500)
    })
    const editorStyle = computed(()=>{
        let style = {};
        style['overflow-y'] = 'hidden';
        if (myConfig.value.editorStyle) {
            Object.assign(style,myConfig.value.editorStyle);
        }
        return style;
    })
    const fatherValue = computed(()=>{
        return  props.value; 
    })
    watch(() => fatherValue, (val) => {
        const text = valueHtml.value
        if (text !== val.value) {
            valueHtml.value = val.value;
        }
    },{deep:true, immediate: true})

    const toolbarConfig = {
       excludeKeys:  ["group-image","group-video","codeBlock"]
    }
    const editorConfig = { 
        placeholder: '请输入内容...',
        MENU_CONF:{
            fontSize:  {
                fontSizeList: [
                    { name: '初号', value: '42px' },
                    { name: '小初', value: '36px' },
                    { name: '一号', value: '26px' },
                    { name: '小一', value: '24px' },
                    { name: '二号', value: '22px' },
                    { name: '小二', value: '18px' },
                    { name: '三号', value: '16px' },
                    { name: '小三', value: '15px' },
                    { name: '小四', value: '12px' },
                    { name: '五号', value: '10.5px' },
                    { name: '小五', value: '9px' },
                    { name: '六号', value: '7.5px' },
                    { name: '小六', value: '6.5px' },
                    { name: '七号', value: '5.5px' },
                    { name: '八号', value: '5px' },
                ]
            },
            fontFamily: {
                fontFamilyList:[  
                    { name: '宋体', value: 'SimSun' },
                    { name: '楷体', value: 'KaiTi' },
                    { name: '仿宋', value: 'FangSong' },
                    { name: '黑体', value: 'SimHei' },
                    { name: '微软雅黑', value: 'Microsoft-YaHei' },
                    'PmingLiu',
                    'Impact',
                    'Georgia',
                    'Tahoma',
                    'Arial',
                    'Verdana'
                ]
            } 
        } 
    }

    // 组件销毁时，也及时销毁编辑器，重要！
    onBeforeUnmount(() => {
        const editor = editorRef.value
        if (editor == null) return

        editor.destroy()
    })

    // 编辑器回调函数
    const handleCreated = (editor) => {
      console.log('created', editor);
      editorRef.value = editor // 记录 editor 实例，重要！
    }
    const handleChange = (editor) => {
        const text =  editor.getHtml()
        console.log('change:', text)
        context.emit('updateValue', text)
    }
    const handleDestroyed = (editor) => {
      console.log('destroyed', editor)
    }
    const handleFocus = (editor) => {
        console.log('focus', editor)
    }
    const handleBlur = (editor) => {
        console.log('blur', editor)
        const text =  editor.getHtml()
        console.log('blur:', text)
        context.emit('updateValue', text)
    }
    const customAlert = (info, type) => {
        alert(`【自定义提示】${type} - ${info}`)
    }
    const customPaste = (editor, event, callback) => {
        //console.log('ClipboardEvent 粘贴事件对象', event)
        // 自定义插入内容
        //editor.insertText('xxx')
        // 返回值（注意，vue 事件的返回值，不能用 return）
        //callback(false) // 返回 false ，阻止默认粘贴行为
        callback(true) // 返回 true ，继续默认的粘贴行为
    }

    const insertText = (value) => {
        const editor = editorRef.value
        if (editor == null) return
        editor.focus()
        editor.insertText(value)
    }

    const printHtml = () => {
        const editor = editorRef.value
        if (editor == null) return
        console.log(editor.getHtml())
    }

    const disable = () => {
        const editor = editorRef.value
        if (editor == null) return
        editor.disable()
    }
    const setReadOnly = (value) =>{
        readOnly.value = value;
        const editor = editorRef.value
        if (editor == null) return;
        if (readOnly.value) {
            editor.disable()
        }else {
            editor.enable()
        }
    }
    const getValue = () => {
        const editor = editorRef.value
        if (editor == null) return
        return editor.getHtml();
    }
 
    return {
      editorRef,
      mode: 'default',
      valueHtml,
      toolbarConfig,
      editorConfig,
      handleCreated,
      handleChange,
      handleDestroyed,
      handleFocus,
      handleBlur,
      customAlert,
      customPaste,
      insertText,
      printHtml,
      disable,
      setReadOnly,
      getValue,
      editorStyle
    };
  }
}
</script>
