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

const rootRef = ref()

const {columns, totalElements} = (function () {
	return {
		columns: ref("4"),
		totalElements: ref(0)
	}
})()

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

	let columnElements = rootRef.value.getElementsByClassName("column")
	if (columnElements.length == 0) {
		return "one"
	}
	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"
		}
	}

	switch (columns) {
		case 1:
			return "1"
		case 2:
			return "2"
		case 3:
			return "3"
		case 4:
			return "4"
		case 5:
			return "5"
		case 6:
			return "6"
		case 7:
			return "7"
		case 8:
			return "8"
		case 9:
			return "9"
		case 10:
			return "10"
		default:
			return "10"
	}
}

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

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

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

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

onUpdated(() => {
	let _totalElements = rootRef.value.getElementsByClassName("column").length
	if (_totalElements == totalElements.value) {
		return
	}
	totalElements.value = _totalElements
	calculateColumns()
})

</script>

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

<style scoped lang="postcss">
</style>