<template>
	<div class="system-edit-role-container">
		<el-dialog title="" v-model="isShowDialog" width="769px">
			<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="name">
							<el-input v-model="formData.name" 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" placeholder="请输入产品详细描述..." />
						</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 { addRole, editRole, getRole } from '/@/api/customerService/script';
import Editor from '/@/components/editor/index.vue';

// 定义类型接口
interface MenuDataTree {
	id: number;
	pid: number;
	title: string;
	children?: MenuDataTree[];
}

interface DialogRow {
	id: number;
	name: string;
	status: number;
	listOrder: number;
	remark: string;
	menuIds: number[];
	content?: string;
}

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

// 响应式数据
const state = reactive({
	loading: false,
	isShowDialog: false,
	formData: {
		id: 0,
		name: '',
		status: 1,
		listOrder: 0,
		remark: '',
		menuIds: [],
		content: '',
	} as DialogRow,
	menuData: [] as MenuDataTree[],
	menuExpand: false,
	menuNodeAll: false,
	menuCheckStrictly: false,
});

// 表单验证规则
const rules: FormRules = {
	name: [{ required: true, message: '标签名称不能为空', trigger: 'blur' }],
	content: [{ required: true, message: '产品详情不能为空', trigger: 'blur' }],
};

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

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

// 菜单配置
const menuProps = {
	children: 'children',
	label: 'title',
};

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

	if (row) {
		// 编辑模式：获取角色详情
		getRole(row.id)
			.then((res: any) => {
				if (res.data?.role) {
					state.formData = {
						...res.data.role,
						content: res.data.role.content || '',
						menuIds: res.data.menuIds ?? [],
					};
				}
			})
			.catch((error) => {
				console.error('获取角色详情失败:', error);
				ElMessage.error('获取角色详情失败');
			});
	}

	state.isShowDialog = true;
};

/**
 * 关闭对话框
 */
const closeDialog = () => {
	state.isShowDialog = false;
};

/**
 * 取消操作
 */
const onCancel = () => {
	closeDialog();
};

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

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

		state.loading = true;

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

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

/**
 * 重置表单
 */
const resetForm = () => {
	state.menuCheckStrictly = false;
	state.menuExpand = false;
	state.menuNodeAll = false;
	state.formData = {
		id: 0,
		name: '',
		status: 1,
		listOrder: 0,
		remark: '',
		menuIds: [],
		content: '',
	};

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

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

<style scoped lang="scss">
.system-edit-role-container {
	:deep(.el-dialog__body) {
		padding: 20px;
	}

	.mb20 {
		margin-bottom: 20px;
	}

	.dialog-footer {
		display: flex;
		justify-content: flex-end;
		align-items: center;
	}
}

.tree-border {
	margin-top: 5px;
	border: 1px solid #e5e6e7;
	border-radius: 4px;
}

.menu-data-tree {
	border: var(--el-input-border, var(--el-border-base));
	border-radius: var(--el-input-border-radius, var(--el-border-radius-base));
	padding: 5px;
}
</style>
