<template>
	<view class="wanl-waterfall">
		<view id="wanl-left-cloumn" class="wanl-cloumn">
			<slot name="left" :leftList="leftList"></slot>
		</view>
		<view id="wanl-right-cloumn" class="wanl-cloumn">
			<slot name="right" :rightList="rightList"></slot>
		</view>
	</view>
</template>

<script>
export default {
	name: 'mall-waterfall',
	props: {
		flowList: {
			type: Array,
			required: true,
			default: () => []
		},
		addTime: {
			type: [Number, String],
			default: 20
		}
	},
	data() {
		return {
			leftList: [],
			rightList: [],
			tempList: []
		}
	},
	watch: {
		copyFlowList(nVal, oVal) {
			let startIndex = Array.isArray(oVal) && oVal.length > 0 ? oVal.length : 0
			if (nVal.slice(startIndex).length === 0) {
				this.leftList = []
				this.rightList = []
				this.tempList = this.cloneData(this.copyFlowList)
			} else {
				this.tempList = this.tempList.concat(this.cloneData(nVal.slice(startIndex)))
			}
			this.splitData()
		}
	},
	mounted() {
		this.tempList = this.cloneData(this.copyFlowList)
		this.splitData()
	},
	computed: {
		copyFlowList() {
			return this.cloneData(this.flowList)
		}
	},
	methods: {
		async splitData() {
			if (!this.tempList.length) return
			let rightRect = await this.getRect('#wanl-right-cloumn')
			let leftRect = await this.getRect('#wanl-left-cloumn')
			let item = this.tempList[0]
			if (!item) return
			if (leftRect.height < rightRect.height) {
				this.leftList.push(item)
			} else if (leftRect.height > rightRect.height) {
				this.rightList.push(item)
			} else {
				if (this.leftList.length <= this.rightList.length) {
					this.leftList.push(item)
				} else {
					this.rightList.push(item)
				}
			}
			this.tempList.splice(0, 1)
			if (this.tempList.length) {
				setTimeout(() => { this.splitData() }, this.addTime)
			}
		},
		cloneData(data) {
			return JSON.parse(JSON.stringify(data))
		},
		getRect(selector, all) {
			return new Promise(resolve => {
				let query = null
				// #ifndef MP-ALIPAY
				query = uni.createSelectorQuery().in(this)
				// #endif
				// #ifdef MP-ALIPAY
				query = uni.createSelectorQuery()
				// #endif
				query[all ? 'selectAll' : 'select'](selector)
					.boundingClientRect(rect => {
						if (all && Array.isArray(rect) && rect.length) resolve(rect)
						if (!all && rect) resolve(rect)
					})
					.exec()
			})
		}
	}
}
</script>

<style lang="scss" scoped>
.wanl-waterfall {
	display: flex;
	flex-direction: row;
	align-items: flex-start;
}
.wanl-cloumn {
	display: flex;
	flex: 1;
	flex-direction: column;
	height: auto;
	width: 50%;
}
</style>