<template>
	<el-dialog title="上传文档" v-model="isShowDialog" width="600px" :close-on-click-modal="false" @close="onCancel">
		<el-form ref="formRef" :model="ruleForm" :rules="rules" label-width="100px">
			<el-form-item label="所属数据集" prop="knowledgeId">
				<el-select v-model="ruleForm.datasetId" placeholder="请选择数据集" clearable style="width: 100%" :disabled="!!currentknowledgeId">
					<el-option v-for="item in knowledgeOptions" :key="item.id" :label="item.name" :value="item.id" />
				</el-select>
			</el-form-item>
			<el-form-item label="上传文件" prop="files">
				<el-upload
					ref="uploadRef"
					class="upload-area"
					drag
					multiple
					:auto-upload="false"
					:file-list="fileList"
					:on-change="onFileChange"
					:on-remove="onFileRemove"
					accept=".pdf,.docx,.doc,.txt,.md,.html"
				>
					<el-icon class="el-icon--upload"><ele-UploadFilled /></el-icon>
					<div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
					<template #tip>
						<div class="el-upload__tip">支持 PDF、Word、TXT、Markdown、HTML 格式，单个文件不超过 20MB</div>
					</template>
				</el-upload>
			</el-form-item>
			<el-form-item label="分段设置">
				<el-row :gutter="20" style="width: 100%">
					<el-col :span="12">
						<div class="setting-item">
							<span class="label">分段长度</span>
							<el-input-number v-model="ruleForm.chunkSize" :min="100" :max="2000" :step="100" />
						</div>
					</el-col>
					<el-col :span="12">
						<div class="setting-item">
							<span class="label">重叠长度</span>
							<el-input-number v-model="ruleForm.chunkOverlap" :min="0" :max="500" :step="50" />
						</div>
					</el-col>
				</el-row>
			</el-form-item>
			<el-form-item label="处理选项">
				<el-checkbox v-model="ruleForm.cleanWhitespace">清理多余空白</el-checkbox>
				<el-checkbox v-model="ruleForm.removeHeaders">移除页眉页脚</el-checkbox>
			</el-form-item>
		</el-form>
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="onCancel">取 消</el-button>
				<el-button type="primary" @click="onSubmit" :loading="submitLoading" :disabled="fileList.length === 0">
					上传 ({{ fileList.length }} 个文件)
				</el-button>
			</span>
		</template>
	</el-dialog>
</template>

<script lang="ts">
export default {
	name: 'uploadDocument',
};
</script>

<script setup lang="ts">
import { ref, reactive, watch } from 'vue';
import { ElMessage } from 'element-plus';
import type { FormInstance, FormRules, UploadFile, UploadInstance } from 'element-plus';
import { uploadDocument } from '/@/api/knowledge/document';

// 定义props
const props = defineProps<{
	knowledgeOptions: any[];
	currentknowledgeId?: string;
}>();

// 定义事件
const emit = defineEmits(['getDocumentList']);

// 表单ref
const formRef = ref<FormInstance>();
const uploadRef = ref<UploadInstance>();

// 弹窗状态
const isShowDialog = ref(false);
const submitLoading = ref(false);

// 文件列表
const fileList = ref<UploadFile[]>([]);

// 表单数据
const ruleForm = reactive({
	datasetId: '',
	chunkSize: 500,
	chunkOverlap: 50,
	cleanWhitespace: true,
	removeHeaders: false,
});

// 表单验证规则
const rules = reactive<FormRules>({
	datasetId: [{ required: true, message: '请选择数据集', trigger: 'change' }],
});

// 监听当前数据集ID
watch(
	() => props.currentknowledgeId,
	(val) => {
		if (val) {
			ruleForm.datasetId = val;
		}
	},
	{ immediate: true }
);

// 重置表单
const resetForm = () => {
	if (!props.currentknowledgeId) {
		ruleForm.datasetId = '';
	}
	ruleForm.chunkSize = 500;
	ruleForm.chunkOverlap = 50;
	ruleForm.cleanWhitespace = true;
	ruleForm.removeHeaders = false;
	fileList.value = [];
};

// 文件变化
const onFileChange = (file: UploadFile, files: UploadFile[]) => {
	// 检查文件大小
	if (file.raw && file.raw.size > 20 * 1024 * 1024) {
		ElMessage.warning(`文件 ${file.name} 超过20MB限制`);
		files.splice(files.indexOf(file), 1);
		return;
	}
	fileList.value = files;
};

// 文件移除
const onFileRemove = (file: UploadFile, files: UploadFile[]) => {
	fileList.value = files;
};

// 打开弹窗
const openDialog = () => {
	resetForm();
	isShowDialog.value = true;
};

// 取消
const onCancel = () => {
	isShowDialog.value = false;
	formRef.value?.resetFields();
	fileList.value = [];
};

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

	form.validate(async (valid: boolean) => {
		if (valid) {
			if (fileList.value.length === 0) {
				ElMessage.warning('请选择要上传的文件');
				return;
			}

			submitLoading.value = true;
			try {
				// 逐个上传文件
				for (const file of fileList.value) {
					const formData = new FormData();
					formData.append('file', file.raw as Blob);
					formData.append('datasetId', ruleForm.datasetId);
					formData.append('chunkSize', ruleForm.chunkSize.toString());
					formData.append('chunkOverlap', ruleForm.chunkOverlap.toString());
					formData.append('cleanWhitespace', ruleForm.cleanWhitespace.toString());
					formData.append('removeHeaders', ruleForm.removeHeaders.toString());

					await uploadDocument(formData);
				}

				ElMessage.success(`成功上传 ${fileList.value.length} 个文件`);
				isShowDialog.value = false;
				emit('getDocumentList');
			} catch (_error) {
				ElMessage.error('上传失败，请重试');
			} finally {
				submitLoading.value = false;
			}
		}
	});
};

// 暴露方法
defineExpose({
	openDialog,
});
</script>

<style scoped lang="scss">
.upload-area {
	width: 100%;
	:deep(.el-upload) {
		width: 100%;
	}
	:deep(.el-upload-dragger) {
		width: 100%;
	}
}
.setting-item {
	display: flex;
	align-items: center;
	.label {
		margin-right: 10px;
		white-space: nowrap;
	}
}
</style>
