<template>
	<div class="edit-page">
		<el-button class="round-btn" round size="small" @click="goBack">
			<i class="el-icon-back"></i>
			返回
		</el-button>
		<div class="iframe-box" ref="iframeBox" v-loading="iframeLoading" :element-loading-text="maskText">
			<div class="scale-box"><iframe :src="tplSrc" frameborder="0" @load="iframeLoad" allowFullScreen></iframe></div>
		</div>
		<el-drawer
			:before-close="beforeClose"
			:modal="false"
			:visible.sync="drawer"
			ref="drawer"
			size="620px"
			:direction="position"
			destroy-on-close
			@close="drawerClose('恢复已编辑数据', true)"
		>
			<template slot="title">
				<el-link type="primary" style="margin: 0 15px;" href="/screen/assets/font/demo_index.html" target="_blank">图标名称展示</el-link>
			</template>
			<el-main>
				<el-collapse style="max-height: 78.5vh;" value="1">
					<el-collapse-item name="1">
						<template slot="title">
							<h3>基础配置</h3>
						</template>
						<component :is="editData.editName" v-model="editData.config.data" :keys="keys" style="overflow: auto;max-height:calc(100vh - 175px);"></component>
					</el-collapse-item>
					<el-collapse-item>
						<template slot="title">
							<h3>高级配置</h3>
							<span style="font-size: 12px;margin-left: 2em;color: #F56C6C;">非专业人员请勿操作</span>
						</template>
						<vue-json-editor v-model="editData.config.data" :showBtns="false" @json-change="onJsonChange"></vue-json-editor>
					</el-collapse-item>
				</el-collapse>
			</el-main>
			<el-row style="margin-top: 20px;text-align: center;">
				<el-button @click="drawerClose('恢复已编辑数据')">取 消</el-button>
				<el-button type="primary" @click="onSubmit" :loading="submitLoading">提 交</el-button>
			</el-row>
		</el-drawer>
	</div>
</template>

<script>
import vueJsonEditor from 'vue-json-editor';
import md5 from 'md5';
export default {
	components: {
		vueJsonEditor,
		All: resolve => require(['../../components/tplEdit/All'], resolve),
		Echarts: resolve => require(['../../components/tplEdit/Echarts/Echarts'], resolve),
		ProfessorDoc: resolve => require(['../../components/tplEdit/ProfessorDoc'], resolve),
		SwitchLi: resolve => require(['../../components/tplEdit/SwitchLi'], resolve),
		//地图编辑模板
		AMap: resolve => require(['../../components/tplEdit/AMap'], resolve),
		//监控列表
		MonitorList: resolve => require(['../../components/tplEdit/MonitorList'], resolve),
		DistributedList: resolve => require(['../../components/tplEdit/DistributedList/index'], resolve)
	},
	data() {
		return {
			iframeLoading: true,
			editData: {
				config: {
					data: {}
				}
			},
			keys: {},
			formInline: {
				user: '',
				region: ''
			},
			//抽屉
			drawer: false,
			editPosition: 0,
			submitLoading: false,
			timeoutfun: this.$timeFun(),
			timeoutfun2:this.$timeFun()
		};
	},
	watch: {
		'editData.config.data': {
			handler(n, v) {
				this.synchronous();
			},
			deep: true
		}
	},
	computed: {
		//编辑模板出现位置
		position() {
			return this.editPosition - 0 > 50 ? 'ltr' : 'rtl';
		},
		pageTitle() {
			return `${this.$route.query.mapName}`;
		},
		//模板url
		tplSrc() {
			const { id } = this.$route.query;
			return `/screen/?v=${Math.random(1,9999,0)}#/home/${id}/1/`;
		},
		//计算大屏展示地址
		mapSrc() {
			const { tplSrc = '', id = '' } = this.$route.query;
			return `${tplSrc}?v=${Math.random(1,9999,0)}&id=${id}`;
		},
		//加载遮罩文字提示
		maskText() {
			return '模板系统加载中';
		},
		//成功提示消息
		submitOkMsg() {
			return '数据提交成功';
		},
		//模板code
		moduleCode() {
			const {
				config: {
					pId,
					port,
					mId = '',
					data: { id = '' }
				}
			} = this.editData;
			console.log('保存', pId, port, id,this.editData);
			console.log('md5', port, md5(pId + port + this.$route.query.id + mId + id));
			return md5(pId + port + this.$route.query.id + mId + id);
		}
	},
	methods: {
		onJsonChange(n) {
			this.$set(this.editData, 'data', n);
		},
		//同步数据
		synchronous() {
			this.timeoutfun(e => {
				this.iframe.contentWindow.postMessage(this.editData, location.href);
			}, 800);
		},
		//关闭抽屉前回调
		beforeClose(done) {
			// this.$confirm('即将关闭编辑页面,是否还有数据未提交?', '提示', {
			// 	confirmButtonText: '关闭',
			// 	cancelButtonText: '取消',
			// 	type: 'warning'
			// }).then(() => {
			// 	done();
			// });
				done();
		},
		//关闭抽屉
		drawerClose(msg, close) {
			!close &&
				this.$message({
					message: msg || this.submitOkMsg,
					type: msg ? 'info' : 'success'
				});
			close || this.$refs.drawer.closeDrawer();
			//提交成功重新加载数据
			this.iframe.contentWindow.postMessage(
				{
					type: 'reload'
				},
				location.href
			);
		},
		//提交当前数据到数据库
		onSubmit(reset) {
			this.submitLoading = true;
			const {
				config: { data }
			} = this.editData;
			this.timeoutfun2(e => {
				this.$port
					.addModuleData({
						mapId: this.$route.query.id,
						moduleCode: this.moduleCode,
						dataType: 4,
						sourceName: '',
						content:reset == 'reset' ? null : JSON.stringify(data)
					})
					.then(res => {
						this.submitLoading = false;
						if (!res.code) {
							this.drawerClose();
						}
					});
			});
		},
		goBack() {
			this.$router.push({
				path: '/a-picture'
			});
		},
		iframeLoad(e) {
			this.iframeLoading = false;
			window.onmessage = event => {
				const {
						position,
						type,
						config = {
							data: {},
							keys: {}
						}
					} = event.data,
					{ keys = {} } = config;
				console.log(event.data);
				//把数据同步到编辑模板中
				switch (type) {
					case 'release':
						this.iframeLoading = true;
						this.release();
						return '';
					//重置
					case 'reset':
						this.iframeLoading = true;
						this.editData = event.data;
						this.onSubmit('reset');
						return '';
					//编辑
					case 'edit':
						//显示编辑模板
						this.drawer = true;
						this.editData = event.data;
						this.editPosition = position;
						this.keys = keys;
						return '';
					default:
				}
			};
			this.iframe = e.target;
			const ifw = e => {
				try {
					//自适应大小
					const { offsetHeight, offsetWidth } = this.$refs.iframeBox;
					let box = this.$refs.iframeBox.querySelector('.scale-box');
					box.style.transform = `scaleX(${offsetWidth / 1920}) scaleY(${offsetHeight / 1080})`;
				} catch (e) {
					//TODO handle the exception
				}
			};
			ifw();
			//窗口变化重新计算
			window.onresize = ifw;
			//向内页发送域名
			this.iframe.contentWindow.postMessage(
				{
					type: 'href',
					href: location.href //父窗口
				},
				location.href
			);
		},
		//预览
		release() {
			// window.open(this.tplSrc, '', 'channelmode=1,fullscreen=1,left=0,top=0,location=0');
			window.open(this.mapSrc);
		}
	}
};
</script>

<style lang="less">
#el-drawer__title {
	margin-bottom: 0;
}

.edit-page {
	position: relative;
	margin-left: -20px;
	margin-right: -20px;
	margin-top: -20px;

	.round-btn {
		position: absolute;
		top: 10px;
		left: 10px;
		z-index: 999;
		background: linear-gradient(to bottom, #48a3ff, #03dce3);
		border: none;
		color: #fff;
	}

	.iframe-box {
		height: calc(100vh - 60px);
		position: relative;
		overflow: hidden;

		.scale-box {
			transform-origin: top left;
			width: 1920px;
			height: 1080px;

			iframe {
				width: 1920px;
				height: 1080px;
			}
		}
	}
}
</style>
