<script setup lang="ts">
import { VbUtil } from "@@/vb-dom"
import { symbolKeys } from "./../../models"

// 从统一上下文获取数据
const context = inject(symbolKeys.tableContext)!

// 从 context 获取列菜单显示状态
const columnMenuVisible = context.state.columnMenuVisible

// 获取列数据和 el-tree ref
const columns = context.state.columns
const tableBox = context.refs.tableBox
const elTreeRef = ref()

// 计算可见列 ID
const visColumnIds = ref<string[]>([])

function getVisibleIds() {
	const ids: string[] = []
	function calcVisibleIds(list: any[]) {
		list.forEach((v) => {
			if (v.visible === undefined || v.visible) {
				ids.push(v.field)
				if (v.children && v.children.length > 0) {
					calcVisibleIds(v.children)
				}
			}
		})
	}
	calcVisibleIds(columns.value)
	return ids
}

function getColumnById(id: string, list: any[]): any | null {
	for (let i = 0; i < list.length; i++) {
		const item = list[i]
		if (item.field === id) {
			return item
		}
		if (item.children && item.children.length > 0) {
			const ret = getColumnById(id, item.children)
			if (ret) {
				return ret
			}
		}
	}
	return null
}

// 切换列菜单
const toggleColumnMenu = () => {
	columnMenuVisible.value = !columnMenuVisible.value
}

// 列变化处理
const onColumnChange = (data: any) => {
	const column = getColumnById(data.field, columns.value)
	if (column) {
		column.visible = !(column.visible == undefined || column.visible)
		VbUtil.EventHandlerUtil.trigger(tableBox.value, "vbtable.columns-change", columns.value)
	}
}

// 监听 columns 变化，更新选中状态
watch(
	() => columns.value,
	() => {
		visColumnIds.value = getVisibleIds()
		if (elTreeRef.value) {
			elTreeRef.value.setCheckedKeys(visColumnIds.value)
		}
	},
	{ immediate: true }
)
</script>

<template>
	<div class="column-menu-panel" :class="{ 'panel-hidden': !columnMenuVisible }">
		<div class="panel-header">
			<span class="panel-title">显隐列</span>
			<vb-tooltip class="item" content="关闭" placement="top" :delay="1000">
				<div
					class="btn btn-sm btn-light-primary w-25px h-25px p-0 d-flex align-items-center justify-content-center"
					@click="toggleColumnMenu">
					<span class="bi bi-x-circle fs-5"></span>
				</div>
			</vb-tooltip>
		</div>
		<div class="panel-content">
			<el-tree
				ref="elTreeRef"
				:data="columns"
				show-checkbox
				node-key="field"
				:default-checked-keys="visColumnIds"
				:check-on-click-node="true"
				:props="{ label: 'name', children: 'children' }"
				@check="onColumnChange"></el-tree>
		</div>
	</div>
</template>
