<template>
	<el-col class="mb20">
		<el-form-item label="文件名" prop="name">
			<el-input placeholder="请输入文件名" v-model="modelValue.name" />
		</el-form-item>
	</el-col>
	<el-col class="mb20">
		<el-form-item label="网址" prop="url">
			<el-input placeholder="请输入网址" v-model="modelValue.url">
				<template #append>
					<el-button :icon="Search" :loading="loading" @click="handleParse"></el-button>
					<el-divider direction="vertical" class="mx-4" />
					<el-button :icon="Setting" @click="handleToggleSettings"></el-button>
				</template>
			</el-input>
		</el-form-item>
	</el-col>
	<el-col class="mb20" v-if="showSettings">
		<el-form-item prop="settings">
			<template #label>目标<tip content="请输入目标元素class，例如 .class1"></tip> </template>
			<el-input show-word-limit v-model="modelValue.settings" />
		</el-form-item>
	</el-col>
	<el-col class="mb20">
		<el-form-item label="内容" prop="content">
			<el-input type="textarea" rows="10" maxlength="3000" show-word-limit v-model="modelValue.content" />
		</el-form-item>
	</el-col>
</template>

<script setup lang="ts">
import { ref, PropType } from 'vue';
import { Search, Setting } from '@element-plus/icons-vue';
// @ts-ignore
import JsonEditor from '@axolo/json-editor-vue';
import { crawleObj } from '/@/api/knowledge/aiDocument';
import { ElMessage } from 'element-plus';

const props = defineProps({
	modelValue: {
		type: Object as PropType<any>,
		required: true,
	},
});

const emit = defineEmits(['update:modelValue']);

const showSettings = ref(false);
const loading = ref(false);

const handleToggleSettings = () => {
	showSettings.value = !showSettings.value;
};

const handleParse = async () => {
	if (loading.value) return;
	if (!props.modelValue.url) {
		ElMessage.warning('请输入网址');
		return;
	}

	loading.value = true;
	try {
		const payload = {
			url: props.modelValue.url,
			settings: props.modelValue.settings,
		};

		const { data } = await crawleObj(payload);
		props.modelValue.content = data;
		emit('update:modelValue', { ...props.modelValue, content: data });
		ElMessage.success('解析成功');
	} catch (error) {
		ElMessage.error('解析失败，请检查后台服务或接口定义');
	} finally {
		loading.value = false;
	}
};
</script>
