<template>
	<view class="picture_message_container" @click="clickMediaItem">
		<u--image 
			:showLoading="true" 
			width="120" 
			:height="maxHeight" 
			mode="widthFix" 
			v-if="src"
			:src="src"
			@load="onLoaded" 
			@click="clickMediaItem">
			<template v-slot:loading>
				<u-loading-icon color="red"></u-loading-icon>
			</template>
		</u--image>
		<u--image 
			v-else
			:showLoading="true" 
			width="120" 
			mode="widthFix" 
			src="/static/images/sync_error.png">
		</u--image>
	</view>
</template>

<script>
	import util from "@/util"
	import md5 from "md5";
	export default {
		name: "PictureMessageContainer",
		props: {
			message: Object,
			conversationID:String,
		},
		data() {
			//console.log(this.message);
			return {
				loadingWidth: "120px",
				src:"",
				coverCachePath:"",
				coverDownloading:false,
				coverExists:false,
				coverDownloadProgress:"",
			};
		},
		computed: {
			maxHeight() {
				const imageHeight = this.message.pictureElem.sourcePicture.height;
				const imageWidth = this.message.pictureElem.sourcePicture.width;
				const aspectRatio = imageHeight / imageWidth;
				return 120 * aspectRatio;
			}
		},
		created() {
			this.init();
		},
		methods: {
			async init(){
				const self = this;
				let url = "";
				const pictureElem = this.message.pictureElem;
				// 如果有远程 snapshotUrl，则下载到 coverCachePath
				let snapshotUrl = pictureElem?.sourcePath;
				if(snapshotUrl && await util.fileExsit(snapshotUrl)){
					self.src = snapshotUrl;
					return ;
				}
				
				snapshotUrl = (pictureElem?.sourcePicture.url ?? pictureElem.bigPicture?.url);
				if(!snapshotUrl){
					console.log(this.message);
					return;
				}
				console.log(snapshotUrl);
				util.cacheFile(snapshotUrl,`${this.conversationID}`).then((fn)=>{
					self.coverDownloading = false;
					self.src = fn;
					console.log(fn);
				});
			},
			getShowPath(url){
				return new Promise((resolve,reject)=>{
					if(url.startsWith('file')||url.startsWith('_')||url.startsWith('http')||url.startsWith('blob')){
						return resolve(url);
					}
					plus.io.resolveLocalFileSystemURL(url, function(entry) {
						return resolve(entry.toLocalURL()); 
					}, function(e) { 
						console.log(e);
						resolve(url); 
					});
					
				});
			},
			clickMediaItem() {
				uni.previewImage({
					current: 0,
					//urls: [this.message.pictureElem.sourcePicture.url],
					urls: [this.src],
					indicator: "none",
				});
			},
			onLoaded() {
				this.loadingWidth = "auto";
			},
		},
	};
</script>

<style lang="scss" scoped>
	.picture_message_container {
		position: relative;
		border-radius: 16rpx;
		overflow: hidden;
	}
</style>