<template>
	<!-- 图片上传 -->
	<view class="image-upload">
		<u-upload v-on="_listeners" v-bind="_attrs">
			<slot></slot>
		</u-upload>
	</view>
</template>

<script>
import { uploadFile } from '@/api/com';
export default {
	name: 'imageUpload',
	inheritAttrs: false,
	model: {
		prop: 'value',
		event: 'change',
	},
	props: {
		value: {
			type: Array,
			default: () => [],
		},
	},
	watch: {
		value: {
			handler(list) {
				this.fileList = list;
			},
			immediate: true,
		},
	},
	computed: {
		_attrs() {
			return {
				...this.$attrs,
				fileList: this.fileList,
				maxCount: this.$attrs.maxCount || 20,
			};
		},
		_listeners() {
			return {
				...this.$listeners,
				afterRead: this.afterPic,
				delete: this.deletePic,
			};
		},
	},
	data() {
		return {
			fileList: [],
		};
	},
	methods: {
		deepUpload(fileData) {
			// 多选上传
			let idx = 0;
			const upload = async () => {
				try {
					if (fileData.length === idx) {
						return;
					}
					const file = fileData[idx];
					idx++;
					this.fileList.push({
						...file,
						status: 'uploading',
						message: '上传中',
					});
					const fileIdx = this.fileList.length - 1;
					const { data } = await uploadFile(file.url);
					// 上传成功 todo 这里是把旧的删除替换新的 http_url 并改变status
					this.fileList.splice(fileIdx, 1, {
						status: 'success',
						message: '',
						url: data.http_url,
						noPrefixUrl: data.url, // 没有前缀的
					});
					this.$emit('change', this.fileList); // 改变父组件的 value
					upload(); // 递归 一个一个上传
				} catch (e) {
					// 上传失败
					this.fileList.splice(this.fileList.length - 1, 1); // 因为在请求接口就push了
					this.$emit('change', this.fileList); // 改变父组件的 value
					console.error(e);
				}
			};
			upload();
		},
		async singleUpload(file) {
			//单多选上传
			try {
				this.fileList.push({
					...file,
					status: 'uploading',
					message: '上传中',
				});
				const fileIdx = this.fileList.length - 1;
				const { data } = await uploadFile(file.url);
				// 上传成功
				this.fileList.splice(fileIdx, 1, {
					status: 'success',
					message: '',
					url: data.http_url,
					noPrefixUrl: data.url, // 没有前缀的
				});
				this.$emit('change', this.fileList); // 改变父组件的 value
			} catch (e) {
				// 上传失败
				this.fileList.splice(this.fileList.length - 1, 1);
				this.$emit('change', this.fileList); // 改变父组件的 value
				console.error(e);
			}
		},
		async afterPic(e) {
			if (this.$listeners.afterRead) {
				// 外部自定义
				this.$emit('afterRead', e);
				return;
			}
			const { file } = e;
			// 开启了多选上传图片 {Array} file
			this.$attrs.multiple && this.deepUpload(file); // 递归 一个一个上传 (避免某一个失败，删除file的问题)
			// 没有开启多选上传
			!this.$attrs.multiple && this.singleUpload(file);
		},
		deletePic(e) {
			if (this.$listeners.delete) {
				this.$emit('delete', e);
				return;
			}
			this.fileList.splice(e.index, 1); // 删除
			this.$emit('change', this.fileList); // 改变父组件的 value
		},
	},
};
</script>

<style scoped lang="scss"></style>
