<template>
	<view id="content" class="content">
		<draggable v-model="initModule" @end="setList">
			<template v-if="initModule && initModule.length > 0">
				<view v-for="item in initModule" :key="item.id">
					<widget-shape :id="item.id">
						<component :ref="`${item.component}Ref`" :is="item.component"
							:dataVal="setConfig(item.fields.dataVal)" :attrs="setConfig(item.fields.attrs)"
							:styles="setConfig(item.fields.styles)" />
					</widget-shape>
				</view>
			</template>
		</draggable>
	</view>
</template>

<script>
	import draggable from "./vuedraggable.umd.min.js";
	import widgetShape from "./widget-shape.vue"
	export default {
		components: {
			draggable,
			widgetShape
		},
		data() {
			return {
				initModule: [],
				EditModuleId: null,
			}

		},

		provide() {
			return {
				page: this,
			};
		},
		onLoad(opt) {
			this.getMessage();

		},
		onReachBottom() {
			console.log('滚动到底不了')
			if (this.initModule && this.initModule.length > 0) {
				this.initModule.forEach(el => {
					// console.log('this.initModule = ', el.component , this.$refs[`${el.component}Ref`][0].onReachBottom)
					if (this.$refs[`${el.component}Ref`][0].onReachBottom) {
						this.$refs[`${el.component}Ref`][0].reachBottom()
					}

				})

			}
		},
		methods: {

			// 统一接收平台信息，调用对应方法处理
			getMessage() {
				window.addEventListener("message", e => {
					console.log('messagemessage', e.data)
					if (e.source != window.parent) return;

					if (e.data) {
						let {
							even,
							params
						} = e.data;
						if (even == "setPages") this.init(params);
						if (even == "setEditModuleId") this.getEditModuleId(params);
					}
				});
			},

			init(params) {
				this.initModule = params || [];
			},
			getEditModuleId(e) {
				this.EditModuleId = e || null;
			},
			setEditModuleId(id) {
				if (!id) return false
				const className = `module_${id}`;
				let topNum = 0;
				const query = uni.createSelectorQuery().in(this);
				query.select(`#${className}`).boundingClientRect(data => {
					topNum = data.top
				}).exec();
				window.parent.postMessage({
						type: "setEditModule",
						params: {
							editId: id,
							topNum: topNum
						}
					},
					"*"
				);

			},

			// 组件顺位改变，刷新列表
			setList(e) {
				window.parent.postMessage({
						type: "updateEditModule",
						params: {
							moduleList: this.initModule
						}
					},
					"*"
				);
				this.setEditModuleId(this.EditModuleId)
			},

			getFiltrateData(data) {
				const val = {}
				for (let key in data) {
					if (data[key].child) {
						val[key] = this.getFiltrateData(data[key].child)
					} else {
						val[key] = data[key].value
					}
				}

				return val
			},

			setConfig(data) {
				const obj = data ? this.getFiltrateData(data.child) : ''
				return obj
			}
		},
		watch: {
			EditModuleId: {
				handler(newId, oldValue) {
					if (newId) this.setEditModuleId(newId)
				},
				deep: true,
				immediate: true
			}
		},

	}
</script>

<style>
</style>