<template>
	<view @click="onClick" :style="{width,height}" class="cloud-image-box">
		<image v-if="cSrc" :style="{width,height}" :src="cSrc" :mode="mode" @error="onImageError"></image>
	</view>
</template>

<script>
	/**
	* cloud-image 
	* @description 兼容普通资源和unicloud图片资源渲染的组件
	* @property {String} mode	图片裁剪、缩放的模式。默认为 aspectFill（适合头像），支持所有 image 的 mode
	* @property {String} src	资源完了链接或uniCloud云存储资源的fileid
	* @property {String} width	图片的宽，默认为：100rpx
	* @property {String} height	图片的高，默认为：100rpx
	* @event {Function} click 点击 cloud-image 触发事件
	* @event {Function} load-error 临时链接获取失败或图片加载失败
	*/
	export default {
		name: "cloud-image",
		emits:['click', 'load-error'],
		props: {
			mode: {
				type:String,
				default () {
					return 'aspectFill'
				}
			},
			src: {
				// type:String,
				default () {
					return ""
				}
			},
			width: {
				type:String,
				default () {
					return '100rpx'
				}
			},
			height: {
				type:String,
				default () {
					return '100rpx'
				}
			}
		},
		watch: {
			src:{
				handler(src) {
					this.cSrc = ''
					if (!src || typeof src !== 'string') {
						return
					}
					const s = src.trim()
					if (!s) {
						return
					}
					if (s.substring(0, 8) === 'cloud://') {
						uniCloud.getTempFileURL({
							fileList: [s]
						}).then((res) => {
							const url = res && res.fileList && res.fileList[0] && res.fileList[0].tempFileURL
							if (url) {
								this.cSrc = url
							} else {
								this.$emit('load-error')
							}
						}).catch(() => {
							this.$emit('load-error')
						})
					} else {
						this.cSrc = s
					}
				},
				immediate: true
			}
		},
		methods:{
			onClick(){
				this.$emit('click')
			},
			onImageError() {
				this.cSrc = ''
				this.$emit('load-error')
			}
		},
		data() {
			return {
				cSrc: ''
			};
		}
	}
</script>

<style scoped>
	.cloud-image-box {
		display: flex;
		justify-content: center;
		align-items: center;
		overflow: hidden;
	}
</style>