<template>
	<view class="upload-index">
		<uv-upload ref="update" :accept="accept" :fileList="fileList" name="1" multiple
			:maxCount="type === 'insert' ? 5 : list.length" :deletable="type === 'insert'" @afterRead="afterRead"
			@delete="deletePic" @clickPreview="clickFile" width="80" height="80">
		</uv-upload>
	</view>
</template>

<script>
	import config from "@/config";
	import {
		insertDownloadFile
	} from '@/request/api/common.js'
	export default {
		name: "preview",
		props: {
			list: {
				type: Array,
				default: () => {
					return []
				}
			},
			type: {
				type: String,
				default: 'preview'
			},
			accept: {
				type: String,
				default: 'image'
			}
		},
		data() {
			return {
				fileList: []
			};
		},
		created() {
			this.fileList = this.list.map(node => {
				if (node.type) {
					node['isImage'] = this.image(node.type.toLowerCase());
				} else {
					let name = node.name.split('.');
					node['isImage'] = this.image(name[name.length - 1].toLowerCase());
				}
				return node;
			});
		},
		methods: {
			image(value) {
				return 'jpeg|jpg|gif|png|svg|webp|jfif|bmp|dpg'.indexOf(value) > -1;
			},
			// 删除图片
			deletePic(event) {
				uni.showModal({
					title: '有极提示',
					content: '是否删除该附件',
					success: res => {
						if (res.confirm) {
							this.fileList.splice(event.index, 1)
						}
					}
				});
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this.fileList.length;
				lists.map((item) => {
					this.fileList.push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this.fileList[fileListLen]
					this.fileList.splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result.node.url,
						id: result.id,
						name: result.name
					}))
					fileListLen++
				}
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: config.baseUrl + '/file/filenode/-1', // 仅为示例，非真实的接口地址
						filePath: url,
						name: 'uploadFile',
						success: (res) => {
							setTimeout(() => {
								resolve(JSON.parse(res.data).data)
							}, 1000)
						}
					});
				})
			},
			getFile() {
				return this.fileList.map(res => {
					return {
						id: res.id,
						name: res.name,
						url: res.url,
						type: res.type
					}
				})
			},
			clickFile(item, list, findIndex) {
				let _self = this;
				if (item.isImage || item.isVideo) return;
				uni.showActionSheet({
					itemList: ['预览', '下载'],
					success: node => {
						if (node.tapIndex === 0) {
							this.openFile(item)
						} else if (node.tapIndex === 1) {
							this.download(item);
						}
					}
				});
			},
			download(item) {
				let _self = this;
				uni.showLoading({
					title: '正在下载'
				})
				uni.downloadFile({
					url: config.baseUrl + '/file/filenode/' + item.id + '/type/' + item.name,
					success: downloadfile => {
						uni.hideLoading();
						let file = !uni.getStorageSync('downliadFile') ? [] : JSON.parse(uni.getStorageSync(
							'downliadFile'));
						file.unshift({
							wxUrl: downloadfile.tempFilePath,
							userId: _self.$store.getters.user.userId,
							type: item.type,
							size: downloadfile.dataLength,
							projectId: _self.$store.getters.project.id || 0,
							organizationId: _self.$store.getters.project.id || 0,
							fileName: item.name,
							date: _self.$uv.timeFormat(new Date(),'yyyy-mm-dd hh:MM:ss')
						});
						uni.setStorageSync('downliadFile', JSON.stringify(file));
						_self.$toast('下载成功');
					},
					fail: error => {
						uni.hideLoading();
						_self.$toast('下载失败')
					}
				});
			},
			openFile(item) {
				let _self = this;
				uni.showLoading({
					title: '正在打开'
				})
				uni.downloadFile({
					url: config.baseUrl + '/file/filenode/' + item.id + '/type/' + item.name,
					success: downloadfile => {
						uni.hideLoading();
						uni.openDocument({
							filePath: downloadfile.tempFilePath,
							fileType: item.type,
							success: (res) => {},
							fail: (error) => {
								_self.$toast('打开失败')
							}
						});
					},
					fail: error => {
						uni.hideLoading();
						_self.$toast('打开失败')
					}
				});
			}
		}
	}
</script>

<style>

</style>