<template>
	<div class="upload-file">
		<div class="preview" v-if="url">
			<img :src="url" @error="onChange(null)" />
			<div class="close" @click="onChange(null)">
				<svg-icon name="close-border" size="16" size-unit="px" />
			</div>
		</div>
		<div class="control" v-else>
			<div class="icon"><svg-icon name="upload" size="17" size-unit="px" /></div>
			<div class="txt">{{ tip || $t('FlowCanvas.uploadFiles') }}</div>
			<div class="btn" @click="onSelectFile">{{ $t('FlowCanvas.selectFile') }}</div>
		</div>
	</div>
</template>

<script setup lang="ts">
	import { reactive, computed } from 'vue'
	import { uploadImage } from '@/api/upload'
	const emit = defineEmits(['update:modelValue', 'change'])
	const props = defineProps({
		modelValue: { type: [File, Object, String, null] },
		tip: { type: String, default: '' }
	})
	const data = reactive({
		file: null
	})
	const url = computed(() => {
		const type = props.modelValue?.constructor
		var str = ''
		if (type === File) {
			str = URL.createObjectURL(props.modelValue as File)
		} else if (type === String) {
			str = props.modelValue as string
		}
		return str
	})
	const onChange = (v) => {
		emit('update:modelValue', v)
		emit('change', v)
	}
	const onSelectFile = () => {
		const input = document.createElement('input')
		input.type = 'file'
		input.accept = 'image/png, image/jpeg, image/jpg'
		input.addEventListener('change', (e) => {
			const file = e.target.files[0]
			const formData = new FormData()
			formData.append('file', file)

			uploadImage(formData).then((res) => {
				if (res) onChange(res)
			})
		})
		input.click()
	}
	defineExpose({ data })
</script>

<style lang="less" scoped>
	.upload-file {
		width: 100%;
		height: 99px;
		border-radius: 10px;
		background-color: #f0f0f0;
		display: flex;
		align-items: center;
		justify-content: center;
		> .control {
			text-align: center;
			> .txt {
				margin-top: 6px;
				margin-bottom: 8px;
				font-size: 8px;
				color: #7c7c7c;
			}
			> .btn {
				display: flex;
				align-items: center;
				justify-content: center;
				box-shadow: 0px 0.75px 0px 0px rgba(0, 0, 0, 0.02);
				min-width: 39px;
				// height: 13px;
				border-radius: 2.3px;
				width: 56px;
				text-align: center;
				line-height: 18px;
				background-color: #fff;
				font-size: 9px;
				color: #000;
				border: 1px solid #d9d9d9;
				cursor: pointer;
				&:active {
					opacity: 0.6;
				}
			}
		}
		> .preview {
			height: 80px;
			max-height: 100%;
			position: relative;
			> img {
				height: 100%;
				max-height: 100%;
				object-fit: contain;
			}
			> .close {
				position: absolute;
				top: -10px;
				right: -10px;
				border-radius: 50%;
				background-color: #fff;
				cursor: pointer;
			}
		}
	}
</style>
