<template>
	<div class="container" >
		<div class="holder" :style="holderStyle">
			<iframe :src="iframeUrl"
			        scrolling="no"
			        ref="iframe"
			        :style="{
					pointerEvents: enableMouseEvent ? 'auto': 'none',
				}"
			        frameborder="0"
			></iframe>
		</div>
	</div>
</template>

<script>
import dragPage from './dragPage';
export default {
	name: "VueContainer",
	mixins: [dragPage],
	data: function () {
		return {
			projectHost: null,
			enableMouseEvent: true,
			zoom: 1,
			iframeWidth: '100%',
			iframeHeight: '100%',
			transformX: 0,
			transformY: 0
		}
	},
	computed: {
		iframeUrl() {
			return this.projectHost + '#/'
		},
		holderStyle() {
			return {
				width: this.iframeWidth,
				height: this.iframeHeight,
				transform: `scale(${this.zoom}) translate(${this.transformX}px, ${this.transformY}px)`,
			}
		},
	},
	mounted() {
		this.bus.$on('setIframeMouseEvent', this.setIframeMouseEvent);
		this.bus.$on('setIframeStatus', this.getXY);
		this.createCollection();
		this.fetchProjectHost();
	},
	methods: {
		async createCollection() {
			console.log('connecting');
			const target = this.$refs.iframe.contentWindow;
			this.$iframe.injectWindow(target);
			this.$iframe.on('resizeIframe', this.resizeIframe);
			await this.$iframe.beReady;
			setTimeout(() => {
				this.$iframe.post({
					event: 'getTheProjectWidthAndHeight',
				}).then(data => {
					console.log(data);
					this.iframeWidth = data.width + 'px';
					this.iframeHeight = data.height + 'px';
				});
			}, 1000)
		},
		fetchProjectHost() {
			this.axios({
				url: window.api + '/api/GetProjectHost',
				method: 'post',
			}).then(data => {
				this.projectHost = data.data.url;
			});
		},
		setIframeMouseEvent(flag) {
			this.enableMouseEvent = flag;
		},
		getXY() {
			const result = this.$refs.iframe.getBoundingClientRect();
			this.$store.commit('updateIframeStatus', result);
		},
		resizeIframe(data) {
			this.zoom += data.step;
			this.iframeHeight = data.height + 'px';
			this.iframeWidth = data.width + 'px';
		}
	},
	beforeDestroy() {
		console.log('$iframe dispose');
		this.$iframe.dispose();
		this.bus.$off('setIframeMouseEvent', this.setIframeMouseEvent);
		this.bus.$off('setIframeStatus', this.getXY);
	}
}
</script>

<style scoped lang="scss">
.container {
	width: 100%;
	height: 100%;
	background: white;
	overflow: hidden;
	position: absolute;
	.holder {
		transform-origin: center;
	}
	iframe {
		width: 100%;
		height: 100%;
	}
}
</style>
