<script setup>
import "@/assets/grids.css"
import {onMounted, onUnmounted, ref} from "vue";

const columns = ref(4)
const rootRef = ref()

const calculateColumns = function () {
	let w = window.innerWidth
	let columns = Math.floor(w / 250)
	if (columns == 0) {
		columns = 1
	}

	let columnElements = rootRef.value.getElementsByClassName("column")
	if (columnElements.length == 0) {
		return
	}
	let maxColumns = columnElements.length
	if (columns > maxColumns) {
		columns = maxColumns
	}

	// 添加右侧边框
	for (let index = 0; index < columnElements.length; index++) {
		let el = columnElements[index]
		el.className = el.className.replace("with-border", "")
		if (index % columns == columns - 1 || index == columnElements.length - 1 /** 最后一个 **/) {
			el.className += " with-border"
		}
	}
	if (columns > 10) {
		columns = 10
	}

	return columns
}

const resizeListener = function () {
	columns.value = calculateColumns()
}

onMounted(() => {
	columns.value = calculateColumns()

	window.addEventListener("resize", resizeListener)
})

onUnmounted(() => {
	window.removeEventListener("resize", resizeListener)
})

</script>

<template>
	<div ref="rootRef" class="grid" :class="'grid-cols-' + columns + ' counter-chart'">
		<slot></slot>
	</div>
</template>

<style scoped>
</style>