<template>
	<div class="component-analysis">
		<ComponentTree :source="components"></ComponentTree>
	</div>
</template>

<script>
import ComponentTree from "@/components/up-right/extra/ComponentTree";
export default {
	name: "ComponentAnalysis",
	components: { ComponentTree },
	data: function () {
		return {
			components: {
				name: '暂无数据',
				children: []
			}
		}
	},
	mounted() {
		console.log('组件分析 已就绪');
		this.initialize();
		this.getCurrent();
	},
	methods: {
		initialize() {
			this.$iframe.on('componentChange', this.onChange);
		},
	    getCurrent() {
	    	console.log(this.$iframe);
		    this.$iframe.post( {event: 'getCurrentSelectedComponent'})
	    },
		onChange(message) {
			const data = message.data;
			if (!message.replace) {
				this.components = data;
			} else {
				const newVal = this.flatten(data);
				const oldVal = this.flatten(this.components);
				this.traverseMerge(newVal, oldVal);
			}
		},
		flatten(tree) {
			const result = [];
			const handler = (tree) => {
			    result.push(tree);
			    tree.children.forEach(child => handler(child));
			}
			handler(tree);
			return result;
		},
		traverseMerge(newVal, oldVal) {
			newVal.forEach(item => {
				oldVal.find(each => each.uid === item.uid).isCurrent = item.isCurrent;
			})
		}
	},
	beforeDestroy() {
		this.$iframe.off('componentChange', this.onChange);
	}
}
</script>

<style scoped lang="scss">
.component-analysis {
	width: 100%;
	height: 100%;
	padding: 20px;
}
</style>
