<template>
	<view class="face_message_container bg_container">
		<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>
	</view>
</template>

<script>
	import util from "@/util"
	import md5 from "md5";
	export default {
		name: "FaceMessageRender",
		components: {},
		props: {
			message: Object,
			conversationID:String,
		},
		data() {
			//console.log(this.message);
			return {
				loadingWidth: "120px",
				maxHeight:'120px',
				src:"",
				coverCachePath:"",
				coverDownloading:false,
				coverExists:false,
				coverDownloadProgress:"",
			};
		},
		computed: {
			getImgUrl() {
				return (
					this.message.FaceElem?.data ??
					this.message.FaceElem.index
				);
			}
		},
		created() {
			this.init();
		},
		methods: {
			async init(){
				const self = this;
				let url = "";
				// 如果有远程 snapshotUrl，则下载到 coverCachePath
				const snapshotUrl = this.message.FaceElem.data;
				const key = md5(snapshotUrl || '');
				this.coverCachePath = `_doc/${this.conversationID}/face_${key}.jpg`;
				if (typeof plus === 'undefined' || !this.coverCachePath) return;
				try {
					// 检查封面是否存在
					const coverExists = await util.fileExsit(self.coverCachePath);
					this.coverExists = !!coverExists;
					if (this.coverExists) {
						this.src = this.coverCachePath;
						return;
					}
					if (!snapshotUrl) {
						this.src="/static/images/sync_error.png";
						return;
					}
					this.coverDownloading = true;
					await new Promise((resolve, reject) => {
						util.downloadFile(snapshotUrl, self.coverCachePath, function(localPath) {
							self.coverDownloading = false;
							self.coverExists = true;
							resolve(localPath);
						}, function(err) {
							self.coverDownloading = false;
							reject(err);
						}, function(progress) {
							self.coverDownloadProgress = progress;
						});
					});
				} catch (e) {
					this.coverDownloading = false;
				}
			},
			onLoaded() {
				this.loadingWidth = "auto";
			}
		},
	};
</script>

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