<template>
	<a-modal title="新建文件夹" v-model:visible="visible" :maskClosable="false" width="580px" @cancel="handleDialogClose">
		<a-form class="add-folder-form" ref="addFolderFormRef" :model="form" :rules="formRules" layout="vertical">
			<a-form-item label="文件夹名称" name="fileName">
				<a-textarea
					v-model:value="form.fileName"
					placeholder="请输入文件夹名称"
					:auto-size="{ minRows: 3, maxRows: 3 }"
					:maxLength="255"
					show-count
					@keydown.enter.prevent
				/>
			</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, watch, onUnmounted } from 'vue'
	import { message } from 'ant-design-vue'
	import { createFold } from '@/api/myResource/file'

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

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

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

	const validateFileName = async (rule, value) => {
		const fileNameReg = new RegExp(`[\\\\/:*?"<>|]`)
		if (value && fileNameReg.test(value)) {
			throw new Error(`文件夹名称不能包含下列任何字符：\\/:*?"<>|`)
		}
	}

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

	const handleAddKeyupEnter = (event) => {
		if (event.key === 'Enter') {
			handleDialogSure()
		}
	}

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

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

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

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

	watch(visible, (newValue) => {
		if (newValue) {
			document.addEventListener('keyup', handleAddKeyupEnter)
		} else {
			document.removeEventListener('keyup', handleAddKeyupEnter)
		}
	})

	onUnmounted(() => {
		document.removeEventListener('keyup', handleAddKeyupEnter)
	})

	defineExpose({
		visible
	})
</script>

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

	.ant-btn-primary {
		&,
		&:hover,
		&:focus {
			background-color: @primary-color;
			border-color: @primary-color;
		}
	}

	.ant-btn {
		&:hover,
		&:focus {
			background-color: @hover-color;
			border-color: @hover-color;
			color: white;
		}
	}
</style>
