<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="数据集">
							<el-input v-model="formData.datasetName" placeholder="数据集" disabled />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="场景类型">
							<el-input v-model="formData.sceneType" placeholder="场景类型" disabled />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="话术内容" prop="questionContent">
							<Editor v-model="formData.questionContent" 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, onMounted } from 'vue';
import { ElMessage, type FormInstance, type FormRules } from 'element-plus';
import Editor from '/@/components/editor/index.vue';
import { addScript, updateScript, getScriptDetail } from '/@/api/customerService/script';
import { listknowledges } from '/@/api/knowledge/dataset';

// 定义类型接口
interface DialogRow {
	id?: number;
	datasetId: string | number;
	datasetName?: string;
	sceneType: number;
	questionContent: string;
}

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

// 定义数据集选项类型
interface DatasetOption {
	label: string;
	value: string;
}

// 响应式数据
const state = reactive({
	loading: false,
	isShowDialog: false,
	datasets: [] as DatasetOption[], // 数据集列表
	editorKey: 0, // 用于强制重新渲染编辑器
	formData: {
		id: 0,
		datasetId: 0,
		datasetName: '',
		sceneType: 0,
		questionContent: '',
	} as DialogRow,
});

// 表单验证规则
const rules: FormRules = {
	questionContent: [{ required: true, message: '话术内容不能为空', trigger: 'blur' }],
};

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

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

/**
 * 加载数据集列表
 */
const loadDatasets = async () => {
	try {
		const response = await listknowledges({ pageNum: 1, pageSize: 100 });
		if (response.data && response.data.list) {
			state.datasets = response.data.list.map((item: any) => ({
				label: item.name,
				value: item.id,
			}));
		}
	} catch (error) {
		// 错误已由全局拦截器处理
	}
};

// 生命周期
onMounted(() => {
	loadDatasets();
});

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

	// 重新加载数据集列表，确保数据是最新的
	await loadDatasets();

	if (row && row.id) {
		try {
			// 加载话术详情
			const response = await getScriptDetail({ id: row.id });
			if (response.data) {
				// 确保datasetId是字符串类型，与datasets选项的value类型一致
				const detailData = {
					...response.data,
					datasetId: String(response.data.datasetId),
					datasetName: '',
				};

				// 查找对应的数据集名称
				const dataset = state.datasets.find((d) => d.value === detailData.datasetId);
				if (dataset) {
					detailData.datasetName = dataset.label;
				}

				state.formData = detailData;
			}
		} catch (error) {
			ElMessage.error('获取话术详情失败');
			return;
		}
	} else {
		// 新增模式，确保清空数据
		state.formData = {
			id: 0,
			datasetId: 0,
			datasetName: '',
			sceneType: 0,
			questionContent: '',
		};
	}

	// 强制重新渲染编辑器
	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;

		// 确保数据类型正确
		const submitData = {
			...state.formData,
			datasetId: String(state.formData.datasetId),
			sceneType: Number(state.formData.sceneType),
		};

		state.loading = true;

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

		// 关闭对话框并刷新列表
		state.isShowDialog = false;
		emit('refresh');
	} catch (error) {
		// 错误已由请求拦截器统一处理
	} finally {
		state.loading = false;
	}
};

/**
 * 重置表单
 */
const resetForm = () => {
	state.formData = {
		id: 0,
		datasetId: 0,
		datasetName: '',
		sceneType: 0,
		questionContent: '',
	};

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

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