<template>
	<view class="location_message_container bg_container">
		<u--image 
			:showLoading="true" 
			:width="selfWidth" 
			: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="selfWidth" 
			mode="widthFix" 
			src="/static/images/sync_error.png">
		</u--image>
		<u--text class="address" :style="{
			width:selfWidth+'px'
		}" :lines="1" :size="20" :text="desc"></u--text>
	</view>
</template>

<script>
	import util from "@/util"
	import md5 from "md5";
	export default {
		name: "LocationMessageRender",
		components: {},
		props: {
			message: Object,
			conversationID:String,
		},
		data() {
			return {
				selfWidth:200,
				loadingWidth: "200px",
				src:"",
				coverDownloading:false,
				coverDownloadProgress:"",
				apisrc:"",
				maxHeight:"",
				desc:""
			};
		},
		created() {
			let loc = this.message.locationElem;
			this.desc = loc.description;
			this.apisrc = "http://api.tianditu.gov.cn/staticimage?"
				+"center="+loc.longitude+","+loc.latitude
				+"&width=400"
				+"&height=300"
				+"&zoom=10"
				+"&markers="+loc.longitude+","+loc.latitude
				+"&tk=5255a4be64441ba9fa2ebe605ca472bf";
				//
			//this.apisrc="http://192.168.1.222/staticimage.png";
			this.init();
		},
		methods: {
			getImageInfo(src){
				const _this = this;
				uni.getImageInfo({
					src:src,
					success(res) {
						const imageHeight = res.height;
						const imageWidth = res.width;
						const aspectRatio = imageHeight / imageWidth;
						_this.maxHeight =  (_this.selfWidth * aspectRatio);
						console.log(res)
						_this.src = src;
					}
				})
			},
			async init(){
				const self = this;
				let url = "";
				// 如果有远程 snapshotUrl，则下载到 coverCachePath
				const snapshotUrl = this.apisrc ;
				const key = md5(snapshotUrl || '');
				const dir_name = `${this.conversationID}`;
				const save_file_name = `loc_${key}.png`;
				const coverCachePath = `${dir_name}/${save_file_name}`;
				if (typeof plus === 'undefined' || !coverCachePath) return;
				self.coverDownloading = true;
				util.cacheFile(snapshotUrl,coverCachePath,(fn)=>{
					self.coverDownloading = false;
					self.getImageInfo(fn);
					console.log(fn);
				},(e)=>{
					console.log(e);
				},(e)=>{
					console.log(e);
				});
			},
			clickMediaItem() {
				let loc = this.message.locationElem;
				uni.navigateTo({
					url:"/pages/common/map?type=viewlocation&lng="+loc.longitude+"&lat="+loc.latitude+"&address="+loc.description
				})
			},
			onLoaded() {
				this.loadingWidth = "auto";
			},

		},
	};
</script>

<style lang="scss" scoped>
	.location_message_container{
		.address{
			margin-top: 20rpx;
		}
	}
</style>