import {
	AccessibilityHelp,
	Alignment,
	Autoformat,
	AutoImage,
	AutoLink,
	Autosave,
	BalloonToolbar,
	Base64UploadAdapter,
	BlockQuote,
	Bold,
	Code,
	CodeBlock,
	Essentials,
	FindAndReplace,
	FontBackgroundColor,
	FontColor,
	FontFamily,
	FontSize,
	GeneralHtmlSupport,
	Heading,
	Highlight,
	HorizontalLine,
	ImageBlock,
	ImageCaption,
	ImageInline,
	ImageInsert,
	ImageInsertViaUrl,
	ImageResize,
	ImageStyle,
	ImageTextAlternative,
	ImageToolbar,
	ImageUpload,
	Indent,
	IndentBlock,
	Italic,
	Link,
	LinkImage,
	List,
	ListProperties,
	// Markdown,
	MediaEmbed,
	Mention,
	PageBreak,
	Paragraph,
	PasteFromMarkdownExperimental,
	PasteFromOffice,
	RemoveFormat,
	SelectAll,
	SpecialCharacters,
	SpecialCharactersArrows,
	SpecialCharactersCurrency,
	SpecialCharactersEssentials,
	SpecialCharactersLatin,
	SpecialCharactersMathematical,
	SpecialCharactersText,
	Strikethrough,
	Style,
	Subscript,
	Superscript,
	Table,
	TableCaption,
	TableCellProperties,
	TableColumnResize,
	TableProperties,
	TableToolbar,
	TextTransformation,
	TodoList,
	Underline,
	Undo,

	Plugin,
	ButtonView,
	createDropdown,
	Collection,
	addListToDropdown,
} from 'ckeditor5';
import translations from 'ckeditor5/translations/zh-cn.js';
import { asBlob } from 'html-docx-js-typescript'
import { saveAs } from 'file-saver';
import {
	getStyle,
	getPageContent,
	getUserConfigFromBackend,
	saveData,
	markdown2html,
	html2markdown,
	getUserAILayoutConfig
} from './utils';
import mitt from 'mitt';
// 导出为docx插件
function exportWord() {
	const pageContent = getPageContent();
	const style = getStyle();
	const page = '<!DOCTYPE html><html><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><style>@media print{@page{size:A4 portrait;margin:0cm 3cm}@page:left{margin-left:2.5cm;margin-right:2.7cm;}@page:right{margin-left:2.7cm;margin-right:2.5cm;}}</style>' + style + '</head><body>' + pageContent + '</body></html>'

	// console.log(page);
	asBlob(page).then(data => {
		saveAs(data, 'file.docx') // save as docx file
	}); // asBlob() return Promise<Blob|Buffer>
}
class Export2Word extends Plugin {
	init() {
		const editor = this.editor;

		editor.ui.componentFactory.add('ExportToWord', () => {
			// The button will be an instance of ButtonView.
			const button = new ButtonView();

			button.set({
				label: '导出为docx',
				// withText: true
				tooltip: true,

				// 图标 直接插入svg文件
				icon: '<svg t="1730216969869" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="2612" width="200" height="200"><path d="M576 832H224c-17.6 0-32-14.4-32-32V192h608c17.6 0 32 14.4 32 32v288c0 17.7 14.3 32 32 32s32-14.3 32-32V224c0-52.9-43.1-96-96-96H160c-17.7 0-32 14.3-32 32v640c0 52.9 43.1 96 96 96h352c17.7 0 32-14.3 32-32s-14.3-32-32-32z" p-id="2613"></path><path d="M951.7 757.5c0.2-0.2 0.4-0.5 0.6-0.7 0.1-0.2 0.3-0.3 0.4-0.5 0.2-0.3 0.4-0.6 0.7-0.8 0.1-0.1 0.2-0.3 0.3-0.4l0.6-0.9c0.1-0.1 0.2-0.2 0.3-0.4l0.6-0.9c0.1-0.1 0.2-0.3 0.2-0.4 0.2-0.3 0.4-0.6 0.5-0.9 0.1-0.1 0.2-0.3 0.3-0.4 0.2-0.3 0.3-0.6 0.4-0.9 0.1-0.2 0.2-0.4 0.3-0.5 0.1-0.3 0.2-0.5 0.4-0.8 0.1-0.2 0.2-0.4 0.3-0.7 0.1-0.2 0.2-0.5 0.3-0.7 0.1-0.3 0.2-0.5 0.3-0.8 0.1-0.2 0.1-0.4 0.2-0.6l0.3-0.9c0.1-0.2 0.1-0.4 0.2-0.6 0.1-0.3 0.2-0.6 0.3-1 0-0.2 0.1-0.3 0.1-0.5 0.1-0.3 0.2-0.7 0.2-1 0-0.2 0.1-0.4 0.1-0.5 0.1-0.3 0.1-0.7 0.2-1 0-0.2 0.1-0.4 0.1-0.6 0-0.3 0.1-0.6 0.1-0.9 0-0.3 0-0.5 0.1-0.8 0-0.2 0-0.5 0.1-0.7 0.1-1.1 0.1-2.1 0-3.2 0-0.3 0-0.5-0.1-0.7 0-0.3 0-0.5-0.1-0.8 0-0.3-0.1-0.6-0.1-0.9 0-0.2 0-0.4-0.1-0.6 0-0.3-0.1-0.7-0.2-1 0-0.2-0.1-0.4-0.1-0.5-0.1-0.3-0.1-0.7-0.2-1 0-0.2-0.1-0.3-0.1-0.5-0.1-0.3-0.2-0.6-0.3-1-0.1-0.2-0.1-0.4-0.2-0.6l-0.3-0.9c-0.1-0.2-0.1-0.4-0.2-0.6-0.1-0.3-0.2-0.5-0.3-0.8-0.1-0.2-0.2-0.5-0.3-0.7-0.1-0.2-0.2-0.4-0.3-0.7-0.1-0.3-0.2-0.5-0.4-0.8-0.1-0.2-0.2-0.4-0.3-0.5-0.1-0.3-0.3-0.6-0.4-0.9-0.1-0.2-0.2-0.3-0.3-0.4-0.2-0.3-0.3-0.6-0.5-0.9-0.1-0.1-0.2-0.3-0.2-0.4l-0.6-0.9c-0.1-0.1-0.2-0.2-0.3-0.4l-0.6-0.9c-0.1-0.1-0.2-0.3-0.3-0.4-0.2-0.3-0.4-0.6-0.7-0.8-0.1-0.2-0.3-0.3-0.4-0.5-0.2-0.2-0.4-0.5-0.6-0.7-0.2-0.2-0.4-0.5-0.7-0.7l-0.4-0.4-128-128c-12.5-12.5-32.8-12.5-45.3 0s-12.5 32.8 0 45.3l73.4 73.4H592c-17.7 0-32 14.3-32 32s14.3 32 32 32h258.7l-73.4 73.4c-12.5 12.5-12.5 32.8 0 45.3 6.2 6.2 14.4 9.4 22.6 9.4s16.4-3.1 22.6-9.4l128-128 0.4-0.4c0.4-0.6 0.6-0.9 0.8-1.1z" p-id="2614"></path><path d="M709.3 320.4c-17.4-2.9-33.9 8.9-36.8 26.3l-42.8 256.9-87.3-261.8c-4.4-13-16.6-21.8-30.4-21.8-13.8 0-26 8.8-30.4 21.9l-87.3 261.8-42.8-256.9c-2.9-17.4-19.4-29.2-36.8-26.3-17.4 2.9-29.2 19.4-26.3 36.8l64 384c2.4 14.5 14.4 25.5 29.1 26.6 14.7 1.1 28.2-7.8 32.9-21.8L512 453.2l66.4 199.1c3.9 11.8 15 19.8 27.4 19.8h52.9c14.1 0 26.2-10.2 28.5-24.1l48.4-290.6c2.9-17.6-8.9-34.1-26.3-37z" p-id="2615"></path></svg>',
				keystroke: 'Ctrl+W'
			});

			// Execute a callback function when the button is clicked
			button.on('execute', () => {
				exportWord();
			});

			// 添加快捷键 Ctrl+W 导出为docx
			editor.keystrokes.set('Ctrl+W', (event, cancel) => {
				exportWord();
				cancel();
			});
			return button;
		});

		// 增加菜单栏？ 不显示按钮
		// editor.ui.extendMenuBar({
		// 	menu: {
		// 		menuId: 'export',
		// 		label: '导出',
		// 		groups: [
		// 			{
		// 				groupId: 'export',
		// 				items: [
		// 					'ExportToWord'
		// 				]
		// 			}
		// 		]
		// 	},
		// 	position: 'after:help'
		// }
		// );

	}
}

// 导出为PDF插件
function printPDF() {
	const pageContent = getPageContent();
	console.log(pageContent);
	const style = getStyle();
	// 去掉element中的 ck-focused ck-weight_selected消除页面和图片的蓝边
	const page = '<!DOCTYPE html><html><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><style>@media print{@page{size:A4 portrait;margin:0cm 3cm}@page:left{margin-left:2.5cm;margin-right:2.7cm;}@page:right{margin-left:2.7cm;margin-right:2.5cm;}}</style>' + style + '</head><body>' + pageContent.replaceAll('ck-focused', 'ck-blurred').replaceAll('ck-weight_selected', '') + '</body></html>'
	const newWindow = window.open('', 'PrintDocument', 'height=600,width=700,top=50,left=50');
	newWindow.document.write(page);
	newWindow.document.close();
	newWindow.print();
	newWindow.onafterprint = function () {
		newWindow.close();
	}
}
class Export2PDF extends Plugin {
	init() {
		const editor = this.editor;

		editor.ui.componentFactory.add('ExportToPDF', () => {
			// The button will be an instance of ButtonView.
			const button = new ButtonView();

			button.set({
				label: '导出为PDF',
				// withText: true
				tooltip: true,

				// 图标 直接插入svg文件
				icon: '<svg t="1730309942693" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="2589" width="200" height="200"><path d="M576 832H224c-17.6 0-32-14.4-32-32V192h608c17.6 0 32 14.4 32 32v288c0 17.7 14.3 32 32 32s32-14.3 32-32V224c0-52.9-43.1-96-96-96H160c-17.7 0-32 14.3-32 32v640c0 52.9 43.1 96 96 96h352c17.7 0 32-14.3 32-32s-14.3-32-32-32z" p-id="2590"></path><path d="M960 734.4c0-0.3 0-0.5-0.1-0.7 0-0.3 0-0.5-0.1-0.8 0-0.3-0.1-0.6-0.1-0.9 0-0.2 0-0.4-0.1-0.6 0-0.3-0.1-0.7-0.2-1 0-0.2-0.1-0.4-0.1-0.5-0.1-0.3-0.1-0.7-0.2-1 0-0.2-0.1-0.3-0.1-0.5-0.1-0.3-0.2-0.6-0.3-1-0.1-0.2-0.1-0.4-0.2-0.6l-0.3-0.9c-0.1-0.2-0.1-0.4-0.2-0.6-0.1-0.3-0.2-0.5-0.3-0.8-0.1-0.2-0.2-0.5-0.3-0.7-0.1-0.2-0.2-0.4-0.3-0.7-0.1-0.3-0.2-0.5-0.4-0.8-0.1-0.2-0.2-0.4-0.3-0.5-0.1-0.3-0.3-0.6-0.4-0.9-0.1-0.2-0.2-0.3-0.3-0.4-0.2-0.3-0.3-0.6-0.5-0.9-0.1-0.1-0.2-0.3-0.2-0.4l-0.6-0.9c-0.1-0.1-0.2-0.2-0.3-0.4l-0.6-0.9c-0.1-0.1-0.2-0.3-0.3-0.4-0.2-0.3-0.4-0.6-0.7-0.8-0.1-0.2-0.3-0.3-0.4-0.5-0.2-0.2-0.4-0.5-0.6-0.7-0.2-0.2-0.4-0.5-0.7-0.7l-0.4-0.4-128-128c-12.5-12.5-32.8-12.5-45.3 0s-12.5 32.8 0 45.3l73.4 73.4H592c-17.7 0-32 14.3-32 32s14.3 32 32 32h258.7l-73.4 73.4c-12.5 12.5-12.5 32.8 0 45.3 6.2 6.2 14.4 9.4 22.6 9.4s16.4-3.1 22.6-9.4l128-128 0.4-0.4 0.7-0.7c0.2-0.2 0.4-0.5 0.6-0.7 0.1-0.2 0.3-0.3 0.4-0.5 0.2-0.3 0.4-0.6 0.7-0.8 0.1-0.1 0.2-0.3 0.3-0.4l0.6-0.9c0.1-0.1 0.2-0.2 0.3-0.4l0.6-0.9c0.1-0.1 0.2-0.3 0.2-0.4 0.2-0.3 0.4-0.6 0.5-0.9 0.1-0.1 0.2-0.3 0.3-0.4 0.2-0.3 0.3-0.6 0.4-0.9 0.1-0.2 0.2-0.4 0.3-0.5 0.1-0.3 0.2-0.5 0.4-0.8 0.1-0.2 0.2-0.4 0.3-0.7 0.1-0.2 0.2-0.5 0.3-0.7 0.1-0.3 0.2-0.5 0.3-0.8 0.1-0.2 0.1-0.4 0.2-0.6l0.3-0.9c0.1-0.2 0.1-0.4 0.2-0.6 0.1-0.3 0.2-0.6 0.3-1 0-0.2 0.1-0.3 0.1-0.5 0.1-0.3 0.2-0.7 0.2-1 0-0.2 0.1-0.4 0.1-0.5 0.1-0.3 0.1-0.7 0.2-1 0-0.2 0.1-0.4 0.1-0.6 0-0.3 0.1-0.6 0.1-0.9 0-0.3 0-0.5 0.1-0.8 0-0.2 0-0.5 0.1-0.7-0.1-1.5-0.1-2.5-0.1-3.6zM352 320c-17.7 0-32 14.3-32 32v384c0 17.7 14.3 32 32 32s32-14.3 32-32V576h192c70.6 0 128-57.4 128-128s-57.4-128-128-128H352z m288 128c0 35.3-28.7 64-64 64H384V384h192c35.3 0 64 28.7 64 64z" p-id="2591"></path></svg>',
				keystroke: 'Ctrl+P'
			});

			// Execute a callback function when the button is clicked
			button.on('execute', () => {
				printPDF();
			});

			// 添加快捷键 Ctrl+P 导出为PDF
			editor.keystrokes.set('Ctrl+P', (event, cancel) => {
				printPDF();
				cancel();
			});

			return button;
		});
	}
}


// 智能润色发送消息
function sendDORMsg(type, fullText) {

	// 获取选中的文本，用来进行后续操作
	const selectionText = window.getSelection().toString();
	if (selectionText.trim() === '') return;
	const formData = new FormData();
	formData.append('doc', selectionText);
	formData.append('background', fullText);
	formData.append('type', type);
	const requestOptions = {
		method: 'POST',
		body: formData
	};

	console.log("formData:", formData);
	const store = window.store;
	const res = { oldContent: selectionText, newContent: '...' };
	store.commit('setCurrentTag', type);
	store.commit('addContentToTag', { tag: type, newContent: res });
	const index = store.getters.getCurrentindex;
	console.log("index", index);
	emitter.emit('show-refine-doc-sidebar', type);

	fetch("/web_api/admin/ai_doc/doc_refine", requestOptions)
		.then(response => {
			if (!response.ok) {
				throw new Error("请求出错");
			}

			// 根据返回的数据格式进行相应处理，这里假设返回的数据是JSON格式，所以使用response.json()解析
			return response.json();
		})
		.then(data => {

			// console.log("useStore", store);
			const newRes = { oldContent: selectionText, newContent: data.data.new_doc };
			store.commit('changeContentForTag', { tag: type, index: index, newContent: newRes });
			emitter.emit('show-refine-doc-sidebar', type);
		})
		.catch(error => {
			console.error("POST请求出错：", error);
		});

}


class RefineDoc extends Plugin {
	init() {
		// console.log('Translation initialized!');

		this.editor.ui.componentFactory.add('RefineDoc', (locale) => {
			const dropdownView = createDropdown(locale);
			dropdownView.buttonView.set({
				label: '智能助手',
				withText: true,
			});

			const items = new Collection();
			items.add({
				type: 'button',
				model: {
					id: 'summary',
					withText: true,
					label: '摘要',
				}
			});
			items.add({
				type: 'button',
				model: {
					id: 'decoration',
					withText: true,
					label: '润色'
				}
			});
			items.add({
				type: 'button',
				model: {
					id: 'extension',
					withText: true,
					label: '续写'
				}
			});
			items.add({
				type: 'button',
				model: {
					id: 'correction',
					withText: true,
					label: '修改'
				}
			});
			items.add({
				type: 'button',
				model: {
					id: 'translation',
					withText: true,
					label: '翻译'
				}
			});
			addListToDropdown(dropdownView, items);

			dropdownView.on('execute', (eventInfo) => {
				const id = eventInfo.source.id;
				sendDORMsg(id, '');
			});

			return dropdownView;
		});
	}
}

// 侧边栏按钮
class ToggleSideBar extends Plugin {
	// constructor(toggleSidebar) {
	// 	super();
	// 	this.toggleSidebar = toggleSidebar;
	// }
	init() {
		const editor = this.editor;

		editor.ui.componentFactory.add('SideBar', () => {
			// The button will be an instance of ButtonView.
			const button = new ButtonView();

			button.set({
				label: '侧边栏',
				// withText: true
				tooltip: true,
				// 图标 直接插入svg文件
				icon: '<svg t="1730903613822" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="2614" width="200" height="200"><path d="M849.92 981.333333H175.658667A132.736 132.736 0 0 1 42.666667 848.597333V175.36A132.736 132.736 0 0 1 175.658667 42.666667H849.92C921.898667 42.666667 981.333333 102.016 981.333333 175.402667v673.152C981.333333 922.026667 921.898667 981.333333 849.92 981.333333zM175.658667 136.362667a38.698667 38.698667 0 0 0-39.125334 39.04v673.152c0 21.888 17.194667 39.082667 39.125334 39.082666H849.92a38.698667 38.698667 0 0 0 39.125333-39.04V175.36c-1.578667-21.845333-18.773333-39.04-39.125333-39.04H175.658667z" fill="#172B4D" p-id="2615"></path><path d="M374.314667 957.866667a46.08 46.08 0 0 1-46.933334-46.805334V111.36a46.08 46.08 0 0 1 46.933334-46.890667c26.624 0 46.933333 20.309333 46.933333 46.890667v799.658667a46.08 46.08 0 0 1-46.933333 46.848z" fill="#172B4D" p-id="2616"></path></svg>'

			});

			// Execute a callback function when the button is clicked
			button.on('execute', () => {
				// 打开sidebar
				const bt = document.getElementById("toggleSidebarButton");
				bt.click();
			});

			return button;
		});
	}
}

// 保存按钮
class SaveButton extends Plugin {
	// constructor(toggleSidebar) {
	// 	super();
	// 	this.toggleSidebar = toggleSidebar;
	// }
	init() {
		const editor = this.editor;

		editor.ui.componentFactory.add('SaveButton', () => {
			// The button will be an instance of ButtonView.
			const button = new ButtonView();

			button.set({
				label: '保存',
				// withText: true
				tooltip: true,
				// 图标 直接插入svg文件
				icon: '<svg t="1731573509489" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5448" width="200" height="200"><path d="M933.376 977.066667H89.429333A45.952 45.952 0 0 1 42.666667 930.261333V89.472C42.666667 62.933333 62.933333 42.666667 89.472 42.666667H618.24c26.538667 0 46.805333 20.266667 46.805333 46.805333 0 26.496-20.266667 46.805333-46.805333 46.805333H136.277333v747.178667h750.293334V404.565333c0-26.496 20.309333-46.805333 46.805333-46.805333 26.538667 0 46.805333 20.309333 46.805333 46.805333v525.696a46.933333 46.933333 0 0 1-46.805333 46.805334z" fill="#172B4D" p-id="5449"></path><path d="M933.376 451.370667c-12.458667 0-23.381333-4.693333-32.768-14.08l-315.093333-315.050667c-18.730667-18.773333-18.730667-48.384 0-65.536 18.730667-18.730667 48.384-18.730667 65.536 0l315.093333 313.557333c18.730667 18.730667 18.730667 48.341333 0 65.493334a43.52 43.52 0 0 1-32.768 15.616zM724.352 925.610667a45.952 45.952 0 0 1-46.805333-46.805334v-258.986666H345.301333v258.986666c0 26.496-20.266667 46.762667-46.805333 46.762667a45.952 45.952 0 0 1-46.805333-46.762667V573.013333c0-26.538667 20.266667-46.805333 46.805333-46.805333h425.856c26.538667 0 46.805333 20.266667 46.805333 46.805333v305.749334a46.933333 46.933333 0 0 1-46.805333 46.762666zM724.352 423.253333H298.496a45.952 45.952 0 0 1-46.805333-46.762666V133.162667c0-26.538667 20.266667-46.805333 46.805333-46.805334s46.805333 20.266667 46.805333 46.805334v196.522666h379.050667c26.538667 0 46.805333 20.266667 46.805333 46.805334a46.933333 46.933333 0 0 1-46.805333 46.805333z" fill="#172B4D" p-id="5450"></path></svg>',
				keystroke: 'Ctrl+S'

			});

			// Execute a callback function when the button is clicked
			button.on('execute', () => {
				saveData(getPageContent())
			});

			return button;
		});

		// 添加快捷键 Ctrl+S 保存
		editor.keystrokes.set('Ctrl+S', (event, cancel) => {
			saveData(getPageContent());
			cancel();
		});
	}
}
// AI 自动排版
async function aiformat() {
	console.log("ai formatting")
	const editor = window.editor;
	let doc_content = editor.getData()
	console.log(doc_content);
	// TODO 处理html文件 
	// step 1 - split images and insert text tag
	// match <figure ... </figure>
	const figure_tag = /<figure.*?>(.*?)<\/figure>/g
	const figure_list = doc_content.match(figure_tag)
	console.log(figure_list)
	// replace img tag with text tag
	var figure_listLen = 0
	if (figure_list) {
		console.log("replace figure tag")
		figure_listLen = figure_list.length
		for (let i = 0; i < figure_listLen; i++) {
			const figure = figure_list[i]
			const text = `<text>tag图片${i + 1}</text>`
			doc_content = doc_content.replace(figure, text)
		}
	}
	const img_tag = /<img.*?>/g
	const img_list = doc_content.match(img_tag)
	if(img_list){
		for(let i = 0; i < img_list.length; i++){
			const img = img_list[i]
			const text = `<text>tag图片${i + 1+figure_listLen}</text>`
			doc_content = doc_content.replace(img, text)
		}
	}
	const markdown_content = html2markdown(doc_content)
	console.log(markdown_content)
	// TODO 请求大模型
	// step 2 - convert markdown response to html text and setData
	// 向后端调用API并接受response
	var result = ''
	try {
		// const response = await fetch('/web_api/admin/ai_layout/layout_generate', {
		const response = await fetch('http://localhost:14514/admin/ai_layout/layout_generate', {
			method: 'POST',
			headers: {
				'Content-Type': 'application/json'
			},
			body: JSON.stringify({
				doc_content: markdown_content,
			})
		});

		if (!response.body) {
			throw new Error('No response body');
		}

		const reader = response.body.getReader();
		const decoder = new TextDecoder('utf-8');
		/* eslint-disable no-constant-condition */
		let i = 0;
		while (true) {
			const { done, value } = await reader.read();
			if (done) break;
			const slice = decoder.decode(value, { stream: true });
			result += slice;
			i++;
			if (i % 10 == 0) {
				// 流式展示ai排版后的内容
				const html_content = markdown2html(result)
				editor.setData(html_content)
			}
		}
		/* eslint-enable no-constant-condition */
	} catch (error) {
		console.error('Error:', error);
	}
	// step 3 - recover original images
	const markdown_response = result
	let html_content = markdown2html(markdown_response)

	console.log("html_content:\n\n", html_content)
	// insert original img tag
	if (figure_list) {
		console.log("insert figure tag")
		for (let i = 0; i < figure_listLen; i++) {
			const figure = figure_list[i]
			const text = `tag图片${i + 1}`
			html_content = html_content.replace(text, figure)
		}
	}
	if(img_list){
		for (let i = 0; i < img_list.length; i++) {
			const img = img_list[i]
			const text = `tag图片${i + 1 + figure_listLen}`
			html_content = html_content.replace(text, img)
		}
	}
	editor.setData(html_content)
	// step 4 - fetch users config
	const user_config = getUserAILayoutConfig()

	// step 5 - apply title styles of user
	// get document element
	const pageContent = document.querySelector("#app > div > div > div.editor-container.editor-container_document-editor.editor-container_include-style > div.editor-container__editor-wrapper > div > div > div")
	// 处理title样式
	let title = pageContent.querySelector("h1")
	if (title) {
		title.classList.add(user_config.titleStyle.option)
	}

	// 处理一二三级heading样式
	for (let i = 0; i < 3; i++) {
		const heading = pageContent.querySelectorAll(`h${i + 2}`);
		if (heading.length > 0) {
			const headingTag = user_config.headingStyle.option[i][0];
			const headingClass = user_config.headingStyle.option[i][1];
			console.log("headingTag:\n\n", headingTag)
			console.log("headingClass:\n\n", headingClass)
			// for each element
			heading.forEach((element) => {
				// // reset counter for heading
				// const parentNode = element.parentNode;
				// let currentCounterReset = parentNode.style.counterReset;
				// console.log(element,"\t",parentNode,"\t",currentCounterReset)
				// // TODO 有bug
				// if (currentCounterReset) {
				// 	// currentCounterReset 不存在该counterreset
				// 	if (currentCounterReset.indexOf(headingClass + "counter") == -1) {
				// 		currentCounterReset += " " + headingClass + "counter";
				// 	}
				// } else {
				// 	currentCounterReset = headingClass + "counter";
				// }
				// parentNode.style.setProperty('counter-reset', currentCounterReset);
				const parentNode = element.parentNode;
				let currentCounterReset = new Set(parentNode.style.counterReset.split(/\s+/).filter(Boolean));

				// 添加新的 counter 名称
				currentCounterReset.add(`${headingClass}counter`);

				// 将 Set 转换回字符串
				parentNode.style.setProperty('counter-reset', Array.from(currentCounterReset).join(' '));
				element.classList.add(headingTag, headingClass);
			})
		}
	}

	// 处理正文样式
	const paragraph = pageContent.querySelectorAll("p")
	if (paragraph.length > 0) {
		for (let i = 0; i < paragraph.length; i++) {
			const element = paragraph[i];
			for (let i = 0; i < user_config.bodyStyle.option.length; i++) {
				element.classList.add(user_config.bodyStyle.option[i]);
			}
		}
	}

	// 处理块引用样式
	const blockquote = pageContent.querySelectorAll("blockquote")
	if (blockquote.length > 0) {
		for (let i = 0; i < blockquote.length; i++) {
			const element = blockquote[i];
			for (let i = 0; i < user_config.blockquote.option.length; i++) {
				element.classList.add(user_config.blockquote.option[i]);
			}
		}
	}

	// 处理代码块样式
	const pre = pageContent.querySelectorAll("pre")
	if (pre.length > 0) {
		for (let i = 0; i < pre.length; i++) {
			const element = pre[i];
			for (let i = 0; i < user_config.codeBlockStyle.option.length; i++) {
				element.classList.add(user_config.codeBlockStyle.option[i]);
			}
		}
	}

	// 处理列表样式
	const ul = pageContent.querySelectorAll("ul")
	if (ul.length > 0) {
		for (let i = 0; i < ul.length; i++) {
			ul[i].classList.add(user_config.listStyle.option);
		}
	}


}

class AiFormat extends Plugin {
	init() {
		const editor = this.editor;

		editor.ui.componentFactory.add('AiFormat', () => {
			// The button will be an instance of ButtonView.
			const button = new ButtonView();

			button.set({
				label: '自动排版',
				// withText: true
				tooltip: true,
				// 图标 直接插入svg文件
				icon: '<svg t="1733151966769" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="3854" width="200" height="200"><path d="M85.312 938.688V85.312h59.776v853.376h-59.712z m174.976-118.4a64 64 0 0 1-64-64v-128a64 64 0 0 1 64-64h614.4a64 64 0 0 1 64 64v128a64 64 0 0 1-64 64h-614.4z m0-357.376a64 64 0 0 1-64-64v-128a64 64 0 0 1 64-64h384a64 64 0 0 1 64 64v128a64 64 0 0 1-64 64h-384z" p-id="3855" fill="#2c2c2c"></path></svg>',
				keystroke: 'Shift+F'

			});

			// Execute a callback function when the button is clicked
			button.on('execute', () => {
				aiformat();
			});

			return button;
		});

		// 添加快捷键 Shift+F 保存
		editor.keystrokes.set('Shift+F', (event, cancel) => {
			aiformat();
			cancel();
		});
	}
}

// 智能识别发送消息
function sendRecMsg(type, editor) {
    //const selection = window.getSelection();
    // const editor = this.editor;
	const model = editor.model;
	const imageUtils=editor.plugins.get( 'ImageUtils' );
	const imageElement = imageUtils.getClosestSelectedImageElement( model.document.selection );
	const formData = new FormData();
	var src = '';
	if (type === 'pic_recognition') {
		if (imageElement) {
			var imageSrc = imageElement.getAttribute('src');
			src = imageSrc.replace(/^data:image\/\w+;base64,/, "");
		}
		if (src.trim() === '') return;
		formData.append('pic', src);
	}
	else if (type === 'voc_recognition') {
		return;
	}
	else {
		return;
	}
	const requestOptions = {
		method: 'POST',
		body: formData
	};

	const store = window.store;
	const res = { oldContent: '', newContent: '...' };
	store.commit('setCurrentTag', type);
	store.commit('addContentToTag', { tag: type, newContent: res });
	const index = store.getters.getCurrentindex;
	emitter.emit('show-ai-recg-sidebar', type);

	fetch('/web_api/admin/ai_recognition/' + type, requestOptions)
		.then(response => {
			if (!response.ok) {
				throw new Error("请求出错");
			}

			// 根据返回的数据格式进行相应处理，这里假设返回的数据是JSON格式，所以使用response.json()解析
			return response.json();
		})
		.then(data => {

			// console.log("useStore", store);
			const newRes = { oldContent: '', newContent: data.data.words };
			store.commit('changeContentForTag', { tag: type, index: index, newContent: newRes });
			emitter.emit('show-ai-recg-sidebar', type);
		})
		.catch(error => {
			console.error("POST请求出错：", error);
		});

}


class PicRecog extends Plugin {
	init() {
		// console.log('Translation initialized!');

		this.editor.ui.componentFactory.add('PicRecog', () => {
			const button = new ButtonView();

			button.set({
				label: '图片识别',
				withText: true

			});

			// Execute a callback function when the button is clicked
			button.on('execute', () => {
				sendRecMsg('pic_recognition', this.editor);
			});

			return button;
		});
	}
}


// 配置CKEditor5
// DFZ
// 
function setConfig() {
	// 获取用户的样式配置
	const userConfig = getUserConfigFromBackend();
	return {
		toolbar: {
			items: [
				'undo',
				'redo',
				'|',
				'heading',
				'style',
				'|',
				'fontSize',
				'fontFamily',
				'fontColor',
				'fontBackgroundColor',
				'|',
				'bold',
				'italic',
				'underline',
				'|',
				'link',
				'insertImage',
				'insertTable',
				'highlight',
				'codeBlock',
				'blockquote',
				'|',
				'alignment',
				'bulletedList',
				'numberedList',
				'outdent',
				'indent',
				'|', 'ExportToWord', 'ExportToPDF', 'RefineDoc', 'SideBar', 'SaveButton', 'AiFormat'
			],
			shouldNotGroupWhenFull: true
		},
		plugins: [
			AccessibilityHelp,
			Alignment,
			Autoformat,
			AutoImage,
			AutoLink,
			Autosave,
			BalloonToolbar,
			Base64UploadAdapter,
			BlockQuote,
			Bold,
			Code,
			CodeBlock,
			Essentials,
			FindAndReplace,
			FontBackgroundColor,
			FontColor,
			FontFamily,
			FontSize,
			GeneralHtmlSupport,
			Heading,
			Highlight,
			HorizontalLine,
			ImageBlock,
			ImageCaption,
			ImageInline,
			ImageInsert,
			ImageInsertViaUrl,
			ImageResize,
			ImageStyle,
			ImageTextAlternative,
			ImageToolbar,
			ImageUpload,
			Indent,
			IndentBlock,
			Italic,
			Link,
			LinkImage,
			List,
			ListProperties,
			// Markdown,
			MediaEmbed,
			Mention,
			PageBreak,
			Paragraph,
			PasteFromMarkdownExperimental,
			PasteFromOffice,
			RemoveFormat,
			SelectAll,
			SpecialCharacters,
			SpecialCharactersArrows,
			SpecialCharactersCurrency,
			SpecialCharactersEssentials,
			SpecialCharactersLatin,
			SpecialCharactersMathematical,
			SpecialCharactersText,
			Strikethrough,
			Style,
			Subscript,
			Superscript,
			Table,
			TableCaption,
			TableCellProperties,
			TableColumnResize,
			TableProperties,
			TableToolbar,
			TextTransformation,
			TodoList,
			Underline,
			Undo,
			Export2Word, RefineDoc, Export2PDF, ToggleSideBar, SaveButton, AiFormat, PicRecog
		],
		balloonToolbar: ['bold', 'italic', '|', 'link', 'insertImage', '|', 'bulletedList', 'numberedList'],
		//自定义设置字体
		fontFamily: {
			// 自定义字体
			options: userConfig.fontFamily.options,
			// 启用对所有字体名称的支持
			supportAllValues: true,
		},
		fontSize: {
			// 五号，小四，四号，小三，三号，小二，二号
			options: userConfig.fontSize.options,
			supportAllValues: true
		},
		heading: {
			options: [
				{
					model: 'paragraph',
					title: 'Paragraph',
					class: 'ck-heading_paragraph'
				},
				{
					model: 'heading1',
					view: 'h1',
					title: 'Heading 1',
					class: 'ck-heading_heading1'
				},
				{
					model: 'heading2',
					view: 'h2',
					title: 'Heading 2',
					class: 'ck-heading_heading2'
				},
				{
					model: 'heading3',
					view: 'h3',
					title: 'Heading 3',
					class: 'ck-heading_heading3'
				},
				{
					model: 'heading4',
					view: 'h4',
					title: 'Heading 4',
					class: 'ck-heading_heading4'
				},
				{
					model: 'heading5',
					view: 'h5',
					title: 'Heading 5',
					class: 'ck-heading_heading5'
				},
				{
					model: 'heading6',
					view: 'h6',
					title: 'Heading 6',
					class: 'ck-heading_heading6'
				}
			]
		},
		htmlSupport: {
			allow: [
				{
					name: /^.*$/,
					styles: true,
					attributes: true,
					classes: true
				}
			]
		},
		image: {
			toolbar: [
				'toggleImageCaption',
				'imageTextAlternative',
				'|',
				'imageStyle:inline',
				'imageStyle:wrapText',
				'imageStyle:breakText',
				'|',
				'resizeImage',
				'|',
				'PicRecog'
			]
		},
		initialData:
			'',
		language: 'zh-cn',
		link: {
			addTargetToExternalLinks: true,
			defaultProtocol: 'https://',
			decorators: {
				toggleDownloadable: {
					mode: 'manual',
					label: 'Downloadable',
					attributes: {
						download: 'file'
					}
				}
			}
		},
		list: {
			properties: {
				styles: true,
				startIndex: true,
				reversed: true
			}
		},
		mention: {
			feeds: [
				{
					marker: '@',
					feed: [
						/* See: https://ckeditor.com/docs/ckeditor5/latest/features/mentions.html */
					]
				}
			]
		},
		menuBar: {
			isVisible: true,
			removeItems: ['help'],
		},
		placeholder: 'Type or paste your content here!',
		// 用户可以自定义和管理样式
		style: {
			definitions: userConfig.style.definitions
		},
		table: {
			contentToolbar: ['tableColumn', 'tableRow', 'mergeTableCells', 'tableProperties', 'tableCellProperties']
		},
		autosave: {
			waitingTime: 180000, // (in ms)  3minutes
			save() {
				return saveData(getPageContent());
			}
		},
		translations: [translations]
	}
}
const emitter = new mitt();
export default emitter;
export { Export2Word, Export2PDF, RefineDoc, ToggleSideBar, PicRecog, setConfig };
