<template>
	<div
		v-if="visible"
		class="modal-layer">
		<transition
			name="el-fade-in"
			@after-enter="afterEnter"
			@after-leave="afterLeave">
			<div class="assets-show" v-if="file"
			     @click.self="handleWrapperClick"
			>
				<div class="wrapper">
					<el-button class="close-button" size="mini" circle icon="el-icon-close" @click="hide"></el-button>
					<div class="name-bar">
						<el-input v-for="(field, index) in showFields" :key="index" size="mini" class="item" v-model="file[field]"
						          readonly>
							<template slot="prepend"><span class="field">{{field}}</span></template>
							<el-button slot="append" icon="el-icon-document-copy" @click="copyValue(field)"></el-button>
						</el-input>
					</div>
					<el-image class="big-image" :src="imageUrl" fit="contain"/>
					<div class="image-info">
						<span class="size">{{size}}</span>
					</div>
					<div class="operate-bar">
						<el-button-group>
						</el-button-group>
					</div>
				</div>
			</div>
		</transition>
	</div>
</template>

<script>
	import copy from 'copy-to-clipboard'

	export default {
		name: "AssetsShow",
		data() {
			return {
				visible: false,
				file: null,
				size: '',
				showFields: ['name', 'url', 'uuid'],
			}
		},
		watch: {
			file() {
				this.size = '';
			}
		},
		computed: {
			imageUrl() {
				return this.file.url;
			},
		},
		methods: {
			show(file) {
				this.visible = true;
				this.file = file;
				document.body.appendChild(this.$el);

				let img = new Image();
				img.onload = () => {
					const {width, height} = img;
					this.size = width + ' x ' + height;
				};
				img.src = this.imageUrl;
			},
			hide() {
				if (this.$el && this.$el.parentNode) {
					this.visible = false;
					this.$el.parentNode.removeChild(this.$el);
				}
			},
			afterEnter() {
				this.$emit('opened');
			},
			afterLeave() {
				this.$emit('closed');
			},
			handleWrapperClick() {
				this.hide();
			},
			copyValue(field) {
				copy(this.file[field]);
				this.$message({
					message: this.$t('Copied field to clipboard', {field}),
					type: 'success',
					duration: 700,
				});
			},
		}
	}
</script>

<style scoped>

</style>