<template>
	<div class="account-edit-dialog">
		<el-dialog :title="(formData.id ? '修改' : '添加') + '客服账号'" 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="accountName">
							<el-input v-model="formData.accountName" placeholder="请输入客服账号，如：cs_xhs_qixue" clearable />
						</el-form-item>
					</el-col>

					<!-- 客服平台选择 -->
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="客服平台" prop="platform">
							<el-select v-model="formData.platform" placeholder="请选择客服平台" clearable style="width: 100%">
								<el-option label="小红书" value="小红书" />
								<el-option label="抖音" value="抖音" />
								<el-option label="快手" value="快手" />
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>

				<!-- 高级配置（可选） -->
				<el-collapse v-model="activeNames" class="mt20">
					<el-collapse-item title="高级配置（可选）" name="advanced">
						<el-form-item label="自定义提示词" prop="prompt">
							<el-input
								type="textarea"
								v-model="formData.prompt"
								:rows="8"
								placeholder="留空则使用系统默认提示词模板，如：你是专业的客服顾问，请用温暖关心的语气回答用户问题..."
							/>
							<div style="color: #909399; font-size: 12px; margin-top: 5px;">
								提示：系统会自动引用知识库内容，您只需专注于业务话术即可。留空将使用默认模板，创建后也可通过"配置提示词"按钮修改
							</div>
						</el-form-item>
						<el-form-item label="开场白" prop="opener">
							<el-input
								type="textarea"
								v-model="formData.opener"
								:rows="3"
								placeholder="留空则使用默认开场白，用户进入对话时首先显示的内容"
								maxlength="200"
								show-word-limit
							/>
							<div style="color: #909399; font-size: 12px; margin-top: 5px;">
								提示：留空将使用默认开场白，创建后也可通过"配置提示词"按钮修改
							</div>
						</el-form-item>
					</el-collapse-item>
				</el-collapse>
			</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 ? '修 改' : '新 增' }}
					</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 { addAccount, updateAccount } from '/@/api/customerService/account';

interface DialogFormData {
	id?: string;
	accountName: string;
	platform: string;
	prompt?: string;
	opener?: string;
	status: number;
	creator: '';
	modifier: '';
}

const emit = defineEmits<{
	(e: 'refresh'): void;
}>();

const state = reactive({
	loading: false,
	isShowDialog: false,
	activeNames: [] as string[],
	formData: {
		id: '',
		accountName: '',
		platform: '',
		prompt: '',
		opener: '',
		status: 1,
		creator: '',
		modifier: '',
	} as DialogFormData,
});

const rules: FormRules = {
	accountName: [
		{ required: true, message: '客服账号不能为空', trigger: 'blur' },
		{ min: 2, max: 50, message: '客服账号长度在 2 到 50 个字符', trigger: 'blur' },
	],
	platform: [{ required: true, message: '请选择客服平台', trigger: 'change' }],
};

const formRef = ref<FormInstance>();
const { loading, isShowDialog, formData, activeNames } = toRefs(state);

/**
 * 打开对话框
 */
const openDialog = (row?: DialogFormData) => {
	resetForm();

	if (row && row.id) {
		// 编辑模式：填充数据
		state.formData = { ...row };
	} else {
		// 新增模式：重置ID和状态
		state.formData.id = '';
		state.formData.status = 1;
	}

	state.isShowDialog = true;

	// 下次DOM更新后清除验证
	nextTick(() => {
		formRef.value?.clearValidate();
	});
};

/**
 * 关闭对话框
 */
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) {
			// 修改操作
			await updateAccount(state.formData);
			ElMessage.success('修改成功');
		} else {
			// 新增操作
			await addAccount(state.formData);
			ElMessage.success('添加成功');
		}

		closeDialog();
		emit('refresh');
	} catch (error) {
		console.error('操作失败:', error);
		ElMessage.error(state.formData.id ? '修改失败' : '添加失败');
	} finally {
		state.loading = false;
	}
};

/**
 * 重置表单
 */
const resetForm = () => {
	state.formData = {
		id: '',
		accountName: '',
		platform: '',
		prompt: '',
		opener: '',
		status: 1,
		creator: '',
		modifier: '',
	};
};

defineExpose({
	openDialog,
	closeDialog,
});
</script>

<style scoped>
.status-tip {
	font-size: 12px;
	color: #999;
	margin-top: 5px;
}
</style>
