<script setup>
// 常用属性：
//    name <string> 字段名
//    multiple <boolean> 是否可以多选
//    fileLimit <number> 可选择的文件数量
//    accept <string> 可以选择的文件类型
//    maxFileSize <number> 最大文件尺寸
//    disabled <boolean> 是否禁用
//
// 常用事件：
//    @change 文件有变化时通知

import FileUpload from "primevue/fileupload";
import TLabel from "@/components/ui/TLabel.vue";
import TButton from "@/components/ui/TButton.vue";
import {inject} from "vue";

const props = defineProps(["name", "multiple"])

const emits = defineEmits(["change"])

const onFilesChosen = (e) => {
	emits("change", e.files)
	notifyForm(e.files)
}

const chooseFiles = (e, chooseFn) => {
	chooseFn(e)
}

const clearFiles = (e, clearFn) => {
	clearFn(e)

	if (e.files != null) {
		emits("change", e.files)
		notifyForm(e.files)
	} else {
		const files = new DataTransfer().files
		emits("change", files)
		notifyForm(files)
	}
}

const postFormData = inject("postFormData")
const notifyForm = (files) => {
	if (postFormData != null && typeof postFormData === "object") {
		let fieldName = props.name
		if (typeof fieldName !== "string") {
			fieldName = "file"
		}

		postFormData[fieldName] = files
	}
}

defineExpose({
	get files() {
		let fieldName = props.name
		if (typeof fieldName !== "string") {
			fieldName = "file"
		}

		if (typeof postFormData[fieldName] == null) {
			return []
		}

		return postFormData[fieldName]
	}
})

</script>

<template>
	<FileUpload mode="advanced" @select="onFilesChosen" :multiple="multiple" :customUpload="true" :pt="{input:{name:name}}">
		<template #header="{files, chooseCallback, clearCallback}">
			<div class="flex gap-4">
				<!-- TODO 需要多语言 -->
				<TButton secondary="" icon="pi pi-plus" @click="chooseFiles($event, chooseCallback)"
						 label="选择文件" :disabled="!multiple && files.length >= 1" size="small"></TButton>
				<TButton secondary="" icon="pi pi-times" severity="secondary" @click="clearFiles($event, clearCallback)"
						 v-if="files.length > 0" size="small"></TButton>
			</div>
		</template>
		<template #content="{files}">
			<div class="flex gap-3 px-4 pb-4" v-if="files.length > 0">
				<div v-if="multiple">
					<div v-if="files.length < 3" class="flex gap-2">
						<TLabel v-for="file in files" size="small">{{ file.name }}</TLabel>
					</div>
					<div v-else>
						已选择{{ files.length }}个文件 <!-- TODO 需要多语言 -->
					</div>
				</div>
				<div v-if="!multiple" class="flex gap-1 items-center">
					<span>已选文件：</span>
					<TLabel size="small">{{ files[files.length - 1].name }}</TLabel>
				</div>
			</div>
		</template>
	</FileUpload>
</template>

<style scoped>
:deep(.p-fileupload-upload-button) {
	display: none;
}

:deep(.p-fileupload-content) {
	padding: 0;
}
</style>