<template>
	<view>
		<view class="desc container">
			<uni-section :title="label" type="line">
				<view class="example-body">
					<uni-file-picker :auto-upload="false" :value="fileList" :limit="limit" :title="'最多选择'+ limit +'张图片'"
						@select="select" @delete="deletePhoto" :readonly="readonly"></uni-file-picker>
				</view>
			</uni-section>
		</view>
	</view>
</template>

<script>
	export default {
		props: {
			value: [String, Object, Array],
			// 图片数量限制
			limit: {
				type: Number,
				default: 1,
			},
			label: {
				Type: String,
				default: ''
			},
			readonly: false
		},
		data() {
			return {
				fileList: []
			}
		},
		mounted() {
			if (this.value) {
				this.fileList = this.value
			}
		},
		methods: {
			// 获取上传状态
			select(e) {
				this.uploadFilePromise(e['tempFilePaths'][0]).then(res => {
					if (res.code === 200) {
						this.fileList.push({
							url: this.$BASE_URL + res.url,
							extname: res.extname,
							name: res.fileName
						})
						this.$emit("input", JSON.stringify(this.fileList))
					}
				})
			},
			deletePhoto(e) {
				const findex = this.fileList.map(f => f.url).indexOf(e.tempFilePath);
				if (findex > -1) {
					this.fileList.splice(findex, 1);
					this.$emit("input", JSON.stringify(this.fileList));
				}
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: this.$BASE_URL + '/common/upload',
						filePath: url,
						name: 'file',
						header: {
							"Authorization": "Bearer " + uni.getStorageSync('token')
						},
						success: (res) => {
							// console.log(JSON.parse(res.data).url);
							setTimeout(() => {
								resolve(JSON.parse(res.data))
							}, 50)
						}
					});
				})
			}
		}
	}
</script>

<style>
	.desc {
		padding: 10rpx 15rpx 0 15rpx;
		color: #818181;
		font-size: 20rpx;
	}


	.example-body {
		padding: 10px;
		padding-top: 0;
	}

	.custom-image-box {
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		flex-direction: row;
		justify-content: space-between;
		align-items: center;
	}

	.text {
		font-size: 14px;
		color: #333;
	}
</style>
