/**
 *
 * WangEditor5的使用
 * 2022年6月21日
 * TODO pdfMenu 插入 的时候 无法插入 <embed 标签 需要求助 2022年7月14日
 * */

import styles from './css/style.less';
import React, { useEffect, useState, useRef } from 'react';
import compressImage from '@/webPublic/zyd_public/WangEditor/compressImage';
import { queryApiActionPath } from '@/webPublic/one_stop_public/utils/queryConfig';
import { uploadFile as uploadOnestopFile } from '@/webPublic/one_stop_public/libs/PictureSignature/ShowItem';
import loadCss from '@/webPublic/zyd_public/WangEditor/WangEditor5/css/cssLoader';
import myMenuConf from '@/webPublic/zyd_public/WangEditor/WangEditor5/DiyMenu/pdfMenu';
let editor = null;

export default function PrepareShow(props) {
	const [show, setShow] = useState(false);
	const WangEditor5 = useRef();
	useEffect(() => {
		import('./index.esm').then((res) => {
			// 异步加载这个js。 因为js 过大影响性能
			loadCss().then((cssRes) => {
				// 异步加载这个 wangEditor5 的css 文件
        console.log('123');
				WangEditor5.current = res;
        WangEditor5.current.Boot.registerMenu(myMenuConf);
				setShow(true);
			});
		});
		// setShow(true);
	}, []);
	// console.log(show, WangEditor5);
	if (show) {
		return <WangEditorReactComponent {...props} WangEditor5={WangEditor5.current} />;
	} else {
		return null;
	}
}

function WangEditorReactComponent(props) {
	const { WangEditor5 } = props;
	const { domKey = 'cmsContent', height = '450px', value, onChange } = props;
	useEffect(() => {
		let htmlDefault = '';
		if (value && value.indexOf('wangEditorHtml') > -1) {
			htmlDefault = value;
		} else {
			htmlDefault = '<div class="wangEditorHtml">' + value + '</div>';
		}
		const editorConfig = {
			placeholder: '请输入内容',
			html: htmlDefault,
			MENU_CONF: {
				uploadImage: {
					customUpload: (file, insertFn) => {
						compressImage(file, (fileNew) => {
							uploadOnestopFile(fileNew).then((y) => {
								// 使用一站式的文件上传接口
								if (y && y.length) {
									insertFn(queryApiActionPath() + y, file.name);
								}
							});
						});
					},
				},
			},

			onChange: (editor) => {
				// console.log('content', editor.children);
				onChange(editor.getHtml());
				// console.log('html', editor.getHtml());
			},
		};
		const toolbarConfig = {
			excludeKeys: [
				'codeBlock',
				'emotion',
				'group-video',
				'undo',
				'redo',
				'bulletedList',
				'numberedList',
			],
			insertKeys: {
				index: 0, // 插入的位置，基于当前的 toolbarKeys
				keys: ['myMenu'],
			},
		};
		editor = WangEditor5.createEditor({
			selector: '#' + domKey,
			config: editorConfig,
			mode: 'default',
		});
		const toolBar = WangEditor5.createToolbar({
			editor,
			selector: '#wangEditorToolBar',
			config: toolbarConfig,
			mode: 'default',
		});
		return () => {
			editor.destroy(); // 销毁编辑器
		};
	}, []);

	return (
		<div className={styles.wangEditor5} style={{ zIndex: '149' }}>
			<div id={'wangEditorToolBar'} style={{ zIndex: '150' }} />
			<div id={domKey} style={{ zIndex: '149' }} />
		</div>
	);
}
