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

import BodyTds from "@@@/table/partials/body/BodyTds.vue"

const props = defineProps<{
	row: any
	index: number
	orgh: number
}>()

const propOpts = inject(symbolKeys.bodyTr, {
	selectedIds: ref([]),
	isTree: false,
	keyField: "",
	hasCheckbox: false,
	isMultipleCheck: false,
	parentField: "parent_id",
	childrenField: "children",
	iconField: "name",
	leafField: "isLeaf",
	expandDepth: 0,
	intervalLeft: 10,
	isLazy: false,
	lazySearch: false,
	tdTrClass: "text-center fs-7"
})
const selectedIds = toRef(propOpts.selectedIds)
const tableBox = inject(symbolKeys.tableBox) as Ref<HTMLElement>

const isExpand = computed(() => {
	return propOpts.isLazy ? true : propOpts.expandDepth > props.orgh
})

const hasChildren = computed(() => {
	return props.row[propOpts.childrenField] && props.row[propOpts.childrenField].length > 0
})

const getTrClass = computed(() => {
	let _trClass = ` ${propOpts.tdTrClass} `
	if (hasChildren.value) {
		_trClass += `hasChildren ${isExpand.value ? "tr-expand" : "tr-collapse"} `
	}
	_trClass += !propOpts.isLazy && props.orgh > propOpts.expandDepth ? "hide" : "show"
	return _trClass
})
function getParent(row: any) {
	return `${propOpts.isTree ? `tr_${row[propOpts.parentField]}` : ""}`
}

const onChange = (event: Event) => {
	const target = event.target as HTMLInputElement
	VbUtil.EventHandlerUtil.trigger(tableBox.value, "vbtable.select", {
		isChecked: target.checked,
		row: props.row
	})
}
const onRowClick = () => {
	VbUtil.EventHandlerUtil.trigger(tableBox.value, "vbtable.row.click", props.row)
}
const onDbRowClick = () => {
	VbUtil.EventHandlerUtil.trigger(tableBox.value, "vbtable.row.dbclick", props.row)
}
</script>
<template>
	<tr
		:class="getTrClass"
		:id="`tr_${row[propOpts.keyField]}`"
		:data-parent="getParent(row)"
		@click="onRowClick"
		@dblclick="onDbRowClick">
		<td v-if="propOpts.hasCheckbox" class="check-box">
			<div class="form-check form-check-sm form-check-custom form-check-solid">
				<input
					class="form-check-input"
					type="checkbox"
					:checked="selectedIds.includes(row[propOpts.keyField])"
					:value="row[propOpts.keyField]"
					@change="onChange" />
			</div>
		</td>
		<BodyTds
			:row="row"
			:index="index"
			:is-tree="propOpts.isTree"
			:hasChildren="hasChildren"
			:isExpand="isExpand"
			:orgh="orgh">
			<template v-for="(_, name) in $slots" #[name]="{ row }">
				<slot :name="name" :row="Object.assign({}, row)" />
			</template>
		</BodyTds>
	</tr>
</template>
