<script setup lang="ts">
import { VbUtil } from "@@/vb-dom"
import symbolKeys from "@@@/table/symbol"
const propOpts = inject(symbolKeys.searchFrom, {
	searchFormRowItems: ref([]),
	searchFormItems: ref([]),
	queryParams: ref({}),
	searchFormSpan: 4,
	tableSearchBtnSpan: 1.5
})
const searchFormRef = ref<any>()
const { searchFormRowItems, searchFormItems, queryParams } = propOpts
const tableBox = inject(symbolKeys.tableBox) as Ref<HTMLElement>
const formSlotSuffix = inject(symbolKeys.formSlotSuffix, "tool-form_")

const _searchFormItems = computed(() => {
	if (propOpts.searchFormItems || propOpts.searchFormRowItems) {
		const items = searchFormItems.value ?? []
		if (
			!items.find((v) => {
				return v.field == "searchbtn"
			})
		)
			items.push({
				field: "searchbtn",
				component: "slot",
				span: 1.5
			})
		return items
	}
	return propOpts.searchFormItems
})

// form表单的插槽 需要tool-form_开头,并去除tool-form_传递给VbForm组件
function formatterFormSlot(v: string | number): string | undefined {
	v = v as string
	if (v.search(formSlotSuffix) == 0) {
		return v.substring(formSlotSuffix.length)
	}
	return undefined
}

function query() {
	VbUtil.EventHandlerUtil.trigger(tableBox.value, "vbtable.query")
}
function resetForm() {
	searchFormRef.value.clearValidate()
	searchFormRef.value.resetFields()
	VbUtil.EventHandlerUtil.trigger(tableBox.value, "vbtable.reset")
}
</script>

<template>
	<VbForm
		v-if="searchFormRowItems || searchFormItems"
		ref="searchFormRef"
		v-model:data="queryParams"
		:row-items="searchFormRowItems"
		:items="_searchFormItems"
		:span="propOpts.searchFormSpan">
		<template v-for="(_, name) in $slots" #[`${formatterFormSlot(name)}`]>
			<slot v-if="name.toString().search(formSlotSuffix) == 0" :name="name" />
		</template>
		<template #searchbtn>
			<slot v-if="$slots.searchbtn" name="searchbtn"></slot>
			<el-col v-else :span="propOpts.tableSearchBtnSpan">
				<el-button class="btn btn-primary" @click="query">
					<template #icon>
						<VbIcon icon-name="magnifier" icon-type="solid"></VbIcon>
					</template>
					搜索
				</el-button>
				<el-button class="btn btn-light-primary" @click="resetForm">
					<template #icon>
						<VbIcon icon-name="arrows-loop" icon-type="solid"></VbIcon>
					</template>
					重置
				</el-button>
			</el-col>
		</template>
	</VbForm>
	<el-form
		v-else-if="$slots['table-search-form']"
		ref="searchFormRef"
		:inline="true"
		:model="propOpts.queryParams"
		class="el-row mb-3">
		<slot name="table-search-form" />
		<el-col :span="propOpts.tableSearchBtnSpan">
			<el-form-item>
				<el-button class="btn btn-primary" @click="query">
					<template #icon>
						<VbIcon icon-name="magnifier" icon-type="solid"></VbIcon>
					</template>
					搜索
				</el-button>
				<el-button class="btn btn-light-primary" @click="resetForm">
					<template #icon>
						<VbIcon icon-name="arrows-loop" icon-type="solid"></VbIcon>
					</template>
					重置
				</el-button>
			</el-form-item>
		</el-col>
	</el-form>
</template>
