<template>
	<a-card size="small">
		<template #title>
			<a-tabs centered size="small">
				<a-tab-pane key="form" tab="组件区" />
			</a-tabs>
		</template>
		<div :style="{ minHeight: 'calc(100vh - 190px)', maxHeight: 'calc(100vh - 190px)', overflowY: 'auto' }">
			<a-card id="form-items" title="表单组件" size="small">
				<a-card-grid
					v-for="element in formComponents"
					:key="element.uuid"
					:data-id="element.uuid"
					:data-type="element.type"
					class="list-group-item"
					style="width: 25%; padding: 0 5px; text-align: center"
				>
					<input-item :name="element.name" :icon="element.icon" />
				</a-card-grid>
			</a-card>
			<a-card id="auxiliary-items" title="辅助组件" size="small">
				<a-card-grid
					v-for="element in auxiliaryComponents"
					:key="element.uuid"
					:data-id="element.uuid"
					:data-type="element.type"
					class="list-group-item"
					style="width: 25%; padding: 0 5px; text-align: center"
				>
					<input-item :name="element.name" :icon="element.icon" />
				</a-card-grid>
			</a-card>
			<a-card id="layout-items" title="布局组件" size="small">
				<a-card-grid
					v-for="element in layoutComponents"
					:key="element.uuid"
					:data-id="element.uuid"
					:data-type="element.type"
					class="list-group-item"
					style="width: 25%; padding: 0 5px; text-align: center"
				>
					<input-item :name="element.name" :icon="element.icon" />
				</a-card-grid>
			</a-card>
		</div>
	</a-card>
</template>
<script lang="ts" setup>
	import components from './components'
	import Sortable, { Options } from 'sortablejs'

	const formComponents = computed(() => {
		return components.filter((item) => item.formItem?.group === 'form')
	})
	const auxiliaryComponents = computed(() => {
		return components.filter((item) => item.formItem?.group === 'auxiliary')
	})

	const layoutComponents = computed(() => {
		return components.filter((item) => item.formItem?.group === 'layout')
	})

	const auxiliarySort = ref<Sortable>()
	const formSort = ref<Sortable>()
	const layoutSort = ref<Sortable>()

	const dragOptions = (): Options => {
		return {
			animation: 150,
			sort: false,
			group: { name: 'components', pull: 'clone', put: false },
		}
	}

	nextTick(() => {
		const formElement = document.querySelector('#form-items .ant-card-body')
		if (formElement) {
			formSort.value = Sortable.create(formElement as HTMLElement, dragOptions())
		}

		const auxiliaryElement = document.querySelector('#auxiliary-items .ant-card-body')
		if (auxiliaryElement) {
			auxiliarySort.value = Sortable.create(auxiliaryElement as HTMLElement, dragOptions())
		}

		const layoutElement = document.querySelector('#layout-items .ant-card-body')
		if (layoutElement) {
			layoutSort.value = Sortable.create(layoutElement as HTMLElement, dragOptions())
		}
	})
</script>
