<template>
	<div class="editor-container" :class="{ 'disabled-editor': disableExceptEmotion }">
		<div ref="editorToolbar" class="editor-toolbar"></div>
		<div ref="editorContent" :style="{ height }" class="editor-content"></div>
	</div>
</template>

<script lang="ts">
import { toRefs, reactive, onMounted, watch, defineComponent, onUnmounted, nextTick } from 'vue';
import { createEditor, createToolbar, IEditorConfig, IToolbarConfig, IDomEditor } from '@wangeditor/editor';
import '@wangeditor/editor/dist/css/style.css';
import { toolbarKeys } from './toolbar';

// 定义接口来定义对象的类型
interface WangeditorState {
	editorToolbar: HTMLDivElement | null;
	editorContent: HTMLDivElement | null;
	editor: IDomEditor | null;
	isInitialized: boolean;
}

export default defineComponent({
	name: 'wngEditor',
	props: {
		// 节点 id
		id: {
			type: String,
			default: () => 'wangeditor',
		},
		// 是否禁用
		isDisable: {
			type: Boolean,
			default: () => false,
		},
		// 是否禁用除表情外的所有功能
		disableExceptEmotion: {
			type: Boolean,
			default: () => false,
		},
		// 内容框默认 placeholder
		placeholder: {
			type: String,
			default: () => '请输入内容',
		},
		// 双向绑定：双向绑定值，字段名为固定，改了之后将不生效
		modelValue: String,
		// 模式，可选 <default|simple>，默认 default
		mode: {
			type: String,
			default: () => 'default',
		},
		// 高度
		height: {
			type: String,
			default: () => '310px',
		},
	},
	setup(props, { emit }) {
		const state = reactive<WangeditorState>({
			editorToolbar: null,
			editor: null,
			editorContent: null,
			isInitialized: false,
		});

		// 富文本配置
		const wangeditorConfig = (): Partial<IEditorConfig> => {
			const editorConfig: Partial<IEditorConfig> = {
				MENU_CONF: {},
				readOnly: props.isDisable,
				placeholder: props.placeholder,
			};

			editorConfig.onChange = (editor: IDomEditor) => {
				emit('update:modelValue', editor.getHtml());
			};

			// 即使编辑器只读，也允许表情插入
			if (props.disableExceptEmotion) {
				editorConfig.readOnly = false; // 允许编辑，但通过CSS禁用其他功能
			}

			(<any>editorConfig).MENU_CONF['uploadImage'] = {
				base64LimitSize: 10 * 1024 * 1024,
			};

			return editorConfig;
		};

		const toolbarConfig = (): Partial<IToolbarConfig> => {
			return {
				toolbarKeys: toolbarKeys,
			};
		};

		// 销毁编辑器
		const destroyEditor = () => {
			if (state.editor) {
				state.editor.destroy();
				state.editor = null;
				state.isInitialized = false;
			}
		};

		// 应用禁用状态（只保留表情）
		const applyDisableState = () => {
			if (!state.editorToolbar || !props.disableExceptEmotion) return;

			nextTick(() => {
				// 获取所有工具栏按钮容器
				const toolbarItems = state.editorToolbar!.querySelectorAll('.w-e-bar-item');
				toolbarItems.forEach((item: Element) => {
					// 尝试找到按钮上的 tooltip
					const button = item.querySelector('button');
					let isEmotionButton = false;
					
					if (button) {
						// 检查 data-tooltip (新版) 或 data-title (旧版)
						const tooltip = button.getAttribute('data-tooltip') || button.getAttribute('data-title') || '';
						// 也检查svg或者特定的class，如果有的话。通常表情按钮会有特定的icon
						// 这里主要依靠 tooltip 文字匹配
						if (tooltip.includes('表情') || tooltip.toLowerCase().includes('emotion')) {
							isEmotionButton = true;
						}
					}
					
					// 也可以尝试检查 menu key，但这通常不在 DOM 上直接体现，除非自己加了属性
					// 下面是一个补充策略：如果 item 内部有 emoji 的 svg 或者特定的结构
					
					if (!isEmotionButton) {
						(item as HTMLElement).style.opacity = '0.4';
						(item as HTMLElement).style.pointerEvents = 'none';
						(item as HTMLElement).style.cursor = 'not-allowed';
					} else {
						(item as HTMLElement).style.opacity = '1';
						(item as HTMLElement).style.pointerEvents = 'auto';
						(item as HTMLElement).style.cursor = 'pointer';
					}
				});
			});
		};

		// 初始化富文本
		const initWangeditor = () => {
			destroyEditor();

			nextTick(() => {
				if (!state.editorContent) return;

				state.editor = createEditor({
					html: props.modelValue || '',
					selector: state.editorContent,
					config: wangeditorConfig(),
					mode: props.mode,
				});

				createToolbar({
					editor: state.editor,
					selector: state.editorToolbar!,
					mode: props.mode,
					config: toolbarConfig(),
				});

				state.isInitialized = true;
				
				// 如果开启了特殊禁用模式，应用样式
				if (props.disableExceptEmotion) {
					applyDisableState();
				}
			});
		};

		// 页面加载时
		onMounted(() => {
			initWangeditor();
		});

		// 组件卸载时销毁编辑器
		onUnmounted(() => {
			destroyEditor();
		});

		// 监听双向绑定值的改变
		watch(
			() => props.modelValue,
			(value) => {
				if (state.editor && state.isInitialized) {
					const currentHtml = state.editor.getHtml();
					if (currentHtml !== value) {
						state.editor.setHtml(value || '');
					}
				}
			}
		);

		// 监听禁用状态变化
		watch(
			() => props.isDisable,
			(disabled) => {
				if (state.editor) {
					state.editor.setDisabled(disabled);
				}
			}
		);

		// 监听禁用除表情外的状态变化
		watch(
			() => props.disableExceptEmotion,
			(val) => {
				// 重新初始化或者直接应用样式
				// 为了稳妥，重新初始化以确保工具栏状态正确
				// 但也可以只调用 applyDisableState 如果只是切换禁用状态
				initWangeditor();
			}
		);

		return {
			...toRefs(state),
		};
	},
});
</script>

<style scoped>
.editor-container {
	position: relative;
}

/* 仅在“只保留表情”模式下应用边框和样式修正 */
.disabled-editor {
	border: 1px solid #dcdfe6;
	border-radius: 4px;
}

.disabled-editor :deep(.w-e-toolbar) {
	border-bottom: 1px solid #dcdfe6;
	background-color: #f5f7fa;
	border-radius: 4px 4px 0 0;
}

.disabled-editor :deep(.w-e-text-container) {
	border-radius: 0 0 4px 4px;
	background-color: #fff;
}
</style>
