<template>
	<view class="waterfall-list-container">
		<view class="waterfall-list" v-for="(item, index) in columnCount" :key="index"
			:style="{ 
				width: width,
				marginLeft: index === 0 ? '0' : `${itemGap}rpx`,
				marginRight: index === columnCount - 1 ? '0' : `${itemGap}rpx`
			}">
			<view v-for="(el, i) in list[index]" :key="i">
				<slot name="content" :item="el" :width="width" />
			</view>
		</view>
	</view>
</template>

<script>
export default {
	name: "w-waterfall",
	props: {
		sideGap: {
			type: Number,
			default: 5
		},
		itemGap: {
			type: Number,
			default: 2
		},
		columnCount: {
			type: Number,
			default: 2,
		},
		data: {
			type: Array,
			default: () => ([])
		}
	},
	watch: {
		data: {
			handler(newV) {
				if (newV.length != 0) {
					this.init()
				}
			},
			immediate: true
		}
	},
	mounted() {
		const screenWidth = uni.getWindowInfo().screenWidth;
		const screenRate = screenWidth / 750;
		const gap = ((this.columnCount - 1) * this.itemGap) + this.sideGap;
		const itemWidth = (screenWidth - gap) / this.columnCount
		this.width = Math.round(itemWidth * (1 / screenRate)) - 40/this.columnCount + 'rpx'
	},
	data() {
		return {
			width: '',
			list: []
		};
	},
	methods: {
		init() {
			let list = []
			for (let i = 0; i < this.columnCount; i++) {
				list[i] = []
			}
			let i = 0
			this.data.forEach((el, index) => {
				if (i > this.columnCount - 1) {
					i = 0
				}
				list[i].push(el)
				i++
			})
			this.list = list
		},
	}
}
</script>

<style lang="scss">
.waterfall-list-container {
	// #ifdef APP-NVUE
	// #endif
	// #ifndef APP-NVUE
	// #endif
	display: flex;
	flex-direction: row;
	justify-content: space-between;
	padding: 0 20rpx;
}
</style>