<template>
	<div class="script-edit-dialog">
		<el-dialog title="" v-model="isShowDialog" width="769px" @close="onDialogClose">
			<el-form ref="formRef" :model="formData" :rules="rules" size="default" label-width="90px">
				<el-row :gutter="35">
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="标签" prop="tag">
							<el-input v-model="formData.tag" placeholder="请输入标签" clearable />
						</el-form-item>
					</el-col>
					<!-- 富文本编辑器 -->
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="话术" prop="content">
							<Editor v-model="formData.content" height="400px" :key="editorKey" placeholder="请输入产品详情" :disableExceptEmotion="true" />
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="onCancel" size="default">取 消</el-button>
					<el-button type="primary" @click="onSubmit" size="default" :loading="loading">
						{{ formData.id === 0 ? '新 增' : '修 改' }}
					</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script lang="ts" setup>
import { ref, reactive, toRefs, nextTick } from 'vue';
import { ElMessage, type FormInstance, type FormRules } from 'element-plus';
import Editor from '/@/components/editor/index.vue';
import { addScript, updateScript } from '/@/api/customerService/script';

// 定义类型接口
interface DialogRow {
	id: number;
	tag: string;
	creator: string;
	content: string;
	modifier: string;
}

// 定义事件
const emit = defineEmits<{
	(e: 'refresh'): void;
}>();

// 响应式数据
const state = reactive({
	loading: false,
	isShowDialog: false,
	editorKey: 0, // 用于强制重新渲染编辑器
	formData: {
		id: 0,
		tag: '',
		content: '',
		creator: '',
		modifier: '',
	} as DialogRow,
});

// 表单验证规则
const rules: FormRules = {
	tag: [
		{ required: true, message: '标签名称不能为空', trigger: 'blur' },
		{ max: 64, message: '标签长度最多 64 个字符', trigger: 'blur' },
	],
	content: [
		{ required: true, message: '产品详情不能为空', trigger: 'blur' },
		{ max: 8126, message: '产品名称长度最多 8126 个字符', trigger: 'blur' },
	],
};

// 模板引用
const formRef = ref<FormInstance>();

// 解构状态数据
const { loading, isShowDialog, formData, editorKey } = toRefs(state);

/**
 * 打开对话框
 * @param row - 可选的编辑数据
 */
const openDialog = (row?: DialogRow) => {
	resetForm();

	if (row) {
		// 深拷贝数据，避免引用问题
		state.formData = { ...row };
	} else {
		// 新增模式，确保清空数据
		state.formData = {
			id: 0,
			tag: '',
			content: '',
			creator: '',
			modifier: '',
		};
	}

	// 更新编辑器 key 强制重新渲染
	state.editorKey++;

	state.isShowDialog = true;

	// 确保 DOM 更新后处理
	nextTick(() => {
		if (formRef.value) {
			formRef.value.clearValidate();
		}
	});
};

/**
 * 对话框关闭时的处理
 */
const onDialogClose = () => {
	resetForm();
};

/**
 * 取消操作
 */
const onCancel = () => {
	state.isShowDialog = false;
};

/**
 * 提交表单
 */
const onSubmit = async () => {
	if (!formRef.value) return;

	try {
		// 表单验证
		const valid = await formRef.value.validate();
		if (!valid) return;

		// 额外验证话术内容
		if (!state.formData.content || state.formData.content === '<p><br></p>' || state.formData.content.trim() === '<p><br></p>') {
			ElMessage.warning('话术内容不能为空');
			return;
		}

		state.loading = true;

		if (state.formData.id === 0) {
			// 新增模式
			await addScript(state.formData);
			ElMessage.success('添加成功');
		} else {
			// 编辑模式
			await updateScript(state.formData);
			ElMessage.success('修改成功');
		}

		// 关闭对话框并刷新列表
		state.isShowDialog = false;
		emit('refresh');
	} catch (error) {
		console.error('提交失败:', error);
		ElMessage.error('操作失败');
	} finally {
		state.loading = false;
	}
};

/**
 * 重置表单
 */
const resetForm = () => {
	state.formData = {
		id: 0,
		tag: '',
		content: '',
		creator: '',
		modifier: '',
	};

	// 重置表单验证状态
	nextTick(() => {
		if (formRef.value) {
			formRef.value.clearValidate();
		}
	});
};

// 暴露方法给父组件使用
defineExpose({
	openDialog,
});
</script>
