<template>
	<a-modal title="新建文件" v-model:visible="visible" :maskClosable="false" width="550px" @cancel="handleDialogClose">
		<a-form class="add-file-form" ref="addFileFormRef" :model="form" :rules="formRules" layout="vertical">
			<a-form-item label="文件名称" name="fileName">
				<a-textarea
					v-model:value="form.fileName"
					placeholder="请输入文件名称"
					:auto-size="{ minRows: 1 }"
					:maxLength="255"
					show-count
				/>
			</a-form-item>
		</a-form>
		<template #footer>
			<a-button @click="handleDialogClose">取 消</a-button>
			<a-button type="primary" :loading="sureBtnLoading" @click="handleDialogSure"> 确 定 </a-button>
		</template>
	</a-modal>
</template>

<script setup>
	import { ref, reactive } from 'vue'
	import { message } from 'ant-design-vue'
	import { createOfficeFile } from '@/api/myResource/onlyoffice'
	import { useMyResourceStore } from '@/store/myResource'

	const props = defineProps({
		extendName: String,
		filePath: String,
		callback: Function
	})

	const visible = ref(false)
	const sureBtnLoading = ref(false)
	const addFileFormRef = ref(null)

	const form = reactive({
		fileName: ''
	})

	const formRules = {
		fileName: [{ required: true, message: '请输入文件名称', trigger: 'blur' }]
	}

	const handleDialogClose = () => {
		addFileFormRef.value?.resetFields()
		visible.value = false
		props.callback('cancel')
	}

	const handleDialogSure = async () => {
		try {
			sureBtnLoading.value = true
			await addFileFormRef.value.validate()

			const res = await createOfficeFile({
				extendName: props.extendName,
				filePath: props.filePath,
				fileName: form.fileName
			})

			if (res.success && res.code === 0) {
				message.success('文件创建成功')
				addFileFormRef.value.resetFields()
				visible.value = false
				props.callback('confirm')
			} else {
				message.warning(res.message)
			}
		} catch (error) {
			console.error(error)
		} finally {
			sureBtnLoading.value = false
		}
	}

	defineExpose({
		visible
	})
</script>

<style lang="less" scoped>
	@import '@/style/myResource/varibles.less';

	.add-file-form {
		width: 100%;
	}
</style>
