<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="accountCode">
							<el-input v-model="formData.accountCode" placeholder="请输入账号编码" 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="accountName">
							<el-input v-model="formData.accountName" placeholder="请输入客服账号名称" 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="AI身份" prop="selfIdentity">
							<el-input type="textarea" v-model="formData.selfIdentity" :rows="4" placeholder="AI客服身份描述，如：你是专业的小红书客服顾问..." />
						</el-form-item>
						<el-form-item label="开场白" prop="greeting">
							<el-input
								type="textarea"
								v-model="formData.greeting"
								:rows="4"
								placeholder="WebSocket连接时发送的开场白，如：你好，有什么可以帮你的吗？"
							/>
							<div class="form-tip">留空则不发送开场白</div>
						</el-form-item>
						<el-form-item label="关键词" prop="keywordOption">
							<el-select v-model="formData.keywordOption" multiple placeholder="选择关键词选项" style="width: 100%">
								<el-option label="推荐回复" value="recommend" />
								<el-option label="智能问答" value="qa" />
								<el-option label="人工转接" value="transfer" />
							</el-select>
						</el-form-item>
					</el-collapse-item>
				</el-collapse>
			</el-form>

			<template #footer>
				<span class="dialog-footer">
					<el-button v-debounce @click="onCancel" size="default">取 消</el-button>
					<el-button type="primary" v-debounce @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, getAccountOne } from '/@/api/customerService/account';

interface DialogFormData {
	id?: number;
	datasetIds: number[];
	documentIds: number[];
	accountCode: string;
	accountName: string;
	platform: string;
	status?: number;
	greeting?: string;
	keywordOption?: string[];
	selfIdentity?: string;
}

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

const state = reactive({
	loading: false,
	isShowDialog: false,
	activeNames: [] as string[],
	formData: {
		id: 0,
		datasetIds: [] as number[],
		documentIds: [] as number[],
		accountCode: '',
		accountName: '',
		platform: '',
		status: 1,
		greeting: '',
		keywordOption: [] as string[],
		selfIdentity: '',
	} as DialogFormData,
});

const rules: FormRules = {
	accountCode: [{ required: true, message: '账号编码不能为空', trigger: 'blur' }],
	platform: [{ required: true, message: '请选择客服平台', trigger: 'change' }],
};

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

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

	if (row && row.id) {
		try {
			state.loading = true;
			const res = await getAccountOne({ id: row.id });
			if (res.data) {
				state.formData = {
					...res.data,
					id: res.data.id,
					datasetIds: res.data.datasetIds || [],
					documentIds: res.data.documentIds || [],
					accountCode: res.data.accountCode || '',
					accountName: res.data.accountName || '',
					platform: res.data.platform || '',
					status: res.data.status ?? 1,
					greeting: res.data.greeting || '',
					keywordOption: res.data.keywordOption || [],
					selfIdentity: res.data.selfIdentity || '',
				};
			}
		} catch (error) {
			console.error('获取账号详情失败:', error);
			// 错误已由全局拦截器处理
		} finally {
			state.loading = false;
		}
	}

	state.isShowDialog = true;

	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 as any);
			ElMessage.success('修改成功');
		} else {
			await addAccount(state.formData as any);
			ElMessage.success('添加成功');
		}

		closeDialog();
		emit('refresh');
	} catch (error) {
		console.error('操作失败:', error);
	}
};

/**
 * 重置表单
 */
const resetForm = () => {
	state.formData = {
		id: 0,
		datasetIds: [],
		documentIds: [],
		accountCode: '',
		accountName: '',
		platform: '',
		status: 1,
		greeting: '',
		keywordOption: [],
		selfIdentity: '',
	};
};

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

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