<template>
	<div style="display: flex;">
		<img v-if="imagesLength == 1 && imageUrl" :src="imageUrl" alt="avatar" width="100px" height="100px"
			style="margin-right: 10px;" />
		<template v-else>
			<template v-for="(item, index) in imagesList" v-key="index">
				<div style="margin-right: 10px;">
					<a-space direction="vertical">
						<a-image :src="item.url" :width="100" :height="100" />
						<a-button block danger size="small" @click="delImage(index)">删除此张</a-button>
					</a-space>
				</div>
			</template>
		</template>
		<template v-if="imagesList.length < imagesLength || imagesList.length == 1">
			<a-upload  v-model:file-list="fileList" list-type="picture-card" class="avatar-uploader"
				:show-upload-list="false" :before-upload="beforeUpload" :data="uploadData"
				:customRequest="uploadCustom">
				<plus-outlined />
				<div class="ant-upload-text">{{uploadTxt}}</div>
			</a-upload>
		</template>
	</div>
</template>

<script setup lang="ts">
	import { ref, onMounted, computed, defineProps, watch, defineEmits } from 'vue';
	import axios from 'axios';
	import { useCommon } from '@/hooks/useCommon';
	let { message, imageprefix } = useCommon();
	const props = defineProps({
		upload_txt: String,
		success_image: String,
		images_length: Number,
		images_list: {
			type: Array,
			default: []
		},
		image_type: {
			type: Number,
			default: 1
		}
	});
	const emit = defineEmits();
	const headers = ref<Object>({
		Authorization: sessionStorage.getItem('token'),
		'X-Requested-With': null
	})
	const uploadData = ref<Object>({
		image: ''
	})
	const imageType = ref<Number>(props.image_type)
	let imagesList = ref<Object[]>([])
	let odImagesList = ref<Object[]>([]) // 暂存
	let fileList = ref<Object[]>([])
	let imageUrl = ref<String>(props.success_image) // 图片路径
	let uploadTxt = ref<String>(props.upload_txt)
	let imagesLength = ref<Number>(props.images_length)
	watch(() => [props.success_image, props.image_type, props.images_list], (newVal, oldVal) => {
		imageUrl.value = newVal[0];
		imageType.value = newVal[1];
		odImagesList.value = []
		imagesList.value = []
		if (newVal[2]) {
			newVal[2].map(item => {
				odImagesList.value.push({ photo: item })
			})
		}
		if (newVal[2]) {
			newVal[2].map(item => {
				imagesList.value.push({ url: imageprefix + item })
			})
		}
	}, {
		immediate: true
	})


	const beforeUpload = (file) => {
		uploadData.value.image = file
	}

	const uploadCustom = (e) => {
		let formdata = new FormData()
		formdata.append('image', e.file)
		axios({
			url: 'https://rcsc-test.jcjob.cn/api/common/image/upload?imgtype=' + imageType.value,
			method: 'post',
			data: formdata,
			headers: headers.value
		}).then((res) => {
			if (imagesLength.value === 1) {
				imagesList.value = [{
					uid: '-1', // 文件唯一标识，建议设置为负数，防止和内部产生的 id 冲突
					name: e.file.name, // 文件名
					status: 'done', // 状态有：uploading done error removed
					url: imageprefix + res.data.data.filename
				}]
			} else {
				if (imagesList.value.length < imagesLength.value) {
					console.log(imagesList.value)
					imagesList.value.push({
						uid: '-' + (imagesList.value.length + 1), // 文件唯一标识，建议设置为负数，防止和内部产生的 id 冲突
						name: e.file.name, // 文件名
						status: 'done', // 状态有：uploading done error removed
						url: imageprefix + res.data.data.filename
					})
				} else {
					message.danger('最多上传5张');
				}
			}
			console.log(res.data.data.filename)
			message.success(`${props.upload_txt}成功`);
			emit('uploadSuccess', res.data.data.filename)
		}).catch(err => {
			message.danger('上传失败，请联系管理员');
		})
	}

	// 删除照片
	const delImage = (index) => {
		imagesList.value.splice(index, 1)
		odImagesList.value.splice(index, 1)
		console.log(odImagesList.value)
		emit('delImageAfter', odImagesList.value)
	}


	// const uploadChange = ({ file, fileList }) => {
	// 	console.log(fileList)
	// 	if (file.file.response) {
	// 		message.success(`${props.upload_txt}成功`);
	// 		emit('uploadSuccess', file.file.response)
	// 	}
	// }
</script>

<style scoped lang="less">
	.avatar-uploader>.ant-upload {
		width: 128px;
		height: 128px;
	}

	.ant-upload-select-picture-card i {
		font-size: 32px;
		color: #999;
	}

	.ant-upload-select-picture-card .ant-upload-text {
		margin-top: 8px;
		color: #666;
	}

	.ant-upload-select-picture-card .ant-upload-list-item {
		width: 128px;
		height: 128px;
		margin-right: 8px;
	}
</style>