<template>
	<a-modal
		title="重命名文件"
		v-model:visible="visible"
		:maskClosable="false"
		width="550px"
		@afterVisibleChange="handleVisibleChange"
		@cancel="handleDialogClose"
	>
		<a-form class="rename-file-form" ref="renameFileFormRef" :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"
				/>
			</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 { renameFile } from '@/api/myResource/file'

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

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

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

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

	const handleVisibleChange = (visible) => {
		if (visible) {
			form.fileName = props.oldFileName
		}
	}

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

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

			const res = await renameFile({
				userFileId: props.userFileId,
				fileName: form.fileName
			})

			if (res.success) {
				message.success('重命名成功')
				renameFileFormRef.value.resetFields()
				visible.value = false
				props.callback('confirm')
			} else {
				message.error(res.message)
			}
		} catch (error) {
			console.error(error)
		} finally {
			sureBtnLoading.value = false
		}
	}

	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>
