2026-06-22 18:15:09 +08:00

1592 lines
46 KiB
Vue
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<template>
<div class="scan-box-container" :style="{ width }">
<!-- Tab 切换 -->
<div class="scan-tabs">
<el-tabs v-model="activeTab" stretch @tab-click="handleTabChange">
<el-tab-pane label="筛选" name="custom">
<template #label>
<span class="tab-label">
<el-icon><Operation /></el-icon>
筛选
</span>
</template>
</el-tab-pane>
<el-tab-pane label="过滤" name="preset">
<template #label>
<span class="tab-label">
<el-icon><DataAnalysis /></el-icon>
过滤
</span>
</template>
</el-tab-pane>
</el-tabs>
</div>
<!-- 内容区域 -->
<div class="scan-content">
<!-- 自定义筛选 -->
<div v-show="activeTab === 'custom'" class="custom-filter">
<div class="filter-scroll-area" ref="filterScroll">
<!-- 所有字段配置的表单 -->
<div class="field-forms">
<template v-for="(field, fieldIndex) in availableFields" :key="field.value">
<div
v-if="resolveFieldGroupLabel(field, fieldIndex)"
class="field-group-divider"
>
<span class="field-group-label">{{ resolveFieldGroupLabel(field, fieldIndex) }}</span>
</div>
<!-- 文本类型 -->
<div v-if="field.type === 'text'" class="field-form-item">
<div class="field-label">
<span class="field-label-text">
<span>{{ field.label }}</span>
<el-tag v-if="field.required" size="small" type="danger">必填</el-tag>
</span>
<el-button
v-if="field.extraAction?.label"
type="primary"
link
size="small"
class="field-extra-action"
@click="handleFieldAction(field)"
>
{{ field.extraAction.label }}
</el-button>
</div>
<div
class="field-control"
:class="{ 'field-control--multi': isMultiValueTextOperator(customConditions[field.value].operator) }"
>
<el-select
v-model="customConditions[field.value].operator"
placeholder="条件类型"
size="small"
class="operator-select"
@change="handleOperatorChange(field)"
>
<el-option
v-for="op in getOperators(field)"
:key="op.value"
:label="op.label"
:value="op.value"
/>
</el-select>
<span v-if="isNullishOperator(customConditions[field.value].operator)" class="no-value-tip">无需填值</span>
<el-input
v-else-if="isMultiValueTextOperator(customConditions[field.value].operator)"
v-model="customConditions[field.value].value"
type="textarea"
:autosize="{ minRows: 3, maxRows: 8 }"
:placeholder="getTextPlaceholder(field)"
size="small"
clearable
class="value-input value-input--multi"
@change="handleCustomChange"
@blur="normalizeTextValue(field)"
@paste="handleMultiValuePaste($event, field)"
/>
<el-input
v-else
v-model="customConditions[field.value].value"
:placeholder="getTextPlaceholder(field)"
size="small"
clearable
class="value-input"
@change="handleCustomChange"
@blur="normalizeTextValue(field)"
/>
</div>
</div>
<!-- 数字类型 -->
<div v-else-if="field.type === 'number'" class="field-form-item">
<div class="field-label">
<span>{{ field.label }}</span>
<el-tag v-if="field.required" size="small" type="danger">必填</el-tag>
</div>
<div class="field-control">
<el-select
v-model="customConditions[field.value].operator"
placeholder="请选择"
size="small"
class="operator-select"
@change="handleOperatorChange(field)"
>
<el-option
v-for="op in getOperators(field)"
:key="op.value"
:label="op.label"
:value="op.value"
/>
</el-select>
<!-- isnull / isnotnull: 无需填值 -->
<span v-if="isNullishOperator(customConditions[field.value].operator)" class="no-value-tip">无需填值</span>
<!-- between / notbetween: 区间双输入 -->
<template v-else-if="isRangeOperator(customConditions[field.value].operator)">
<el-input-number
v-model="customConditions[field.value].valueMin"
:controls="false"
size="small"
placeholder="最小值"
class="range-input"
@change="handleCustomChange"
/>
<span class="range-sep">至</span>
<el-input-number
v-model="customConditions[field.value].valueMax"
:controls="false"
size="small"
placeholder="最大值"
class="range-input"
@change="handleCustomChange"
/>
</template>
<!-- in / notin: 逗号分隔文本 -->
<el-input
v-else-if="isMultiOperator(customConditions[field.value].operator)"
v-model="customConditions[field.value].value"
placeholder="多个值逗号分隔"
size="small"
clearable
class="value-input"
@change="handleCustomChange"
/>
<!-- 普通单值 -->
<el-input-number
v-else
v-model="customConditions[field.value].value"
:controls="false"
size="small"
:placeholder="field.placeholder || `请输入${field.label}`"
class="value-input"
@change="handleCustomChange"
/>
</div>
</div>
<!-- 日期类型 -->
<div v-else-if="field.type === 'date'" class="field-form-item">
<div class="field-label">
<span>{{ field.label }}</span>
<el-tag v-if="field.required" size="small" type="danger">必填</el-tag>
</div>
<div class="field-control">
<el-select
v-model="customConditions[field.value].operator"
placeholder="请选择"
size="small"
class="operator-select"
@change="handleOperatorChange(field)"
>
<el-option
v-for="op in getOperators(field)"
:key="op.value"
:label="op.label"
:value="op.value"
/>
</el-select>
<span v-if="isNullishOperator(customConditions[field.value].operator)" class="no-value-tip">无需填值</span>
<!-- between / notbetween: 日期区间 -->
<el-date-picker
v-else-if="isRangeOperator(customConditions[field.value].operator)"
v-model="customConditions[field.value].value"
type="daterange"
range-separator="至"
start-placeholder="开始日期"
end-placeholder="结束日期"
size="small"
style="width: 100%;"
format="YYYY-MM-DD"
value-format="YYYY-MM-DD"
@change="handleCustomChange"
/>
<el-date-picker
v-else
v-model="customConditions[field.value].value"
type="date"
:placeholder="field.placeholder || `请选择${field.label}`"
size="small"
class="value-input"
format="YYYY-MM-DD"
value-format="YYYY-MM-DD"
@change="handleCustomChange"
/>
</div>
</div>
<!-- 日期/日期时间范围类型,operator 固定为 between -->
<div v-else-if="isRangePickerField(field)" class="field-form-item">
<div class="field-label">
<span>{{ field.label }}</span>
<el-tag v-if="field.required" size="small" type="danger">必填</el-tag>
</div>
<div class="field-control field-control--range">
<el-date-picker
v-model="customConditions[field.value].value"
:type="getRangePickerType(field)"
range-separator="至"
:start-placeholder="field.startPlaceholder || getRangePickerStartPlaceholder(field)"
:end-placeholder="field.endPlaceholder || getRangePickerEndPlaceholder(field)"
:format="getRangePickerFormat(field)"
:value-format="getRangePickerValueFormat(field)"
:default-time="getRangePickerDefaultTime(field)"
size="small"
style="width: 100%;"
@change="handleCustomChange"
/>
</div>
</div>
<!-- 下拉选择类型 -->
<div v-else-if="field.type === 'select'" class="field-form-item">
<div class="field-label">
<span>{{ field.label }}</span>
<el-tag v-if="field.required" size="small" type="danger">必填</el-tag>
</div>
<div class="field-control">
<el-select
v-model="customConditions[field.value].value"
:multiple="!!field.multiple"
:placeholder="field.placeholder || `请选择${field.label}`"
size="small"
filterable
clearable
style="width: 100%;"
@change="handleCustomChange"
>
<el-option
v-for="option in field.options"
:key="option.value"
:label="option.label"
:value="option.value == null ? '' : option.value"
/>
</el-select>
</div>
</div>
<!-- 多选类型 -->
<div v-else-if="field.type === 'multiple'" class="field-form-item">
<div class="field-label">
<span>{{ field.label }}</span>
<el-tag v-if="field.required" size="small" type="danger">必填</el-tag>
</div>
<div class="field-control">
<el-select
v-model="customConditions[field.value].value"
multiple
:placeholder="field.placeholder || `请选择${field.label}`"
size="small"
:filterable = "field.filterable"
style="width: 100%;"
@change="handleCustomChange"
>
<el-option
v-for="option in field.options"
:key="option.value"
:label="option.label"
:value="option.value == null ? '' : option.value"
/>
</el-select>
</div>
</div>
<!-- 布尔类型 -->
<div v-else-if="field.type === 'boolean'" class="field-form-item">
<div class="field-label">
<span>{{ field.label }}</span>
<el-tag v-if="field.required" size="small" type="danger">必填</el-tag>
</div>
<div class="field-control">
<el-select
v-model="customConditions[field.value].value"
:placeholder="field.placeholder || `请选择${field.label}`"
size="small"
style="width: 100%;"
@change="handleCustomChange"
>
<el-option label="是" :value="true" />
<el-option label="否" :value="false" />
<el-option label="全部" :value="''" />
</el-select>
</div>
</div>
<!-- 自定义组件类型 -->
<div v-else-if="field.type === 'custom'" class="field-form-item">
<div class="field-label">
<span>{{ field.label }}</span>
<el-tag v-if="field.required" size="small" type="danger">必填</el-tag>
</div>
<div class="field-control">
<component
:is="field.component"
v-model="customConditions[field.value].value"
v-bind="field.props || {}"
@change="handleCustomChange"
/>
</div>
</div>
</template>
</div>
</div>
<!-- 固定底部操作栏 -->
<div class="fixed-bottom-actions" :class="{ 'has-scroll': hasScroll }">
<div class="actions-content">
<el-button
size="small"
@click="handleReset"
class="reset-btn"
>
重置
</el-button>
<el-button
type="primary"
size="small"
@click="handleSubmit"
:loading="submitting"
>
确定
</el-button>
</div>
</div>
</div>
<!-- 预设过滤 -->
<div v-show="activeTab === 'preset'" class="preset-filter">
<div class="filter-scroll-area">
<!-- 搜索框 -->
<div class="preset-search" v-if="presetTree && presetTree.length > 0">
<el-input
v-model="presetSearchText"
placeholder="搜索过滤条件"
size="small"
clearable
@input="filterPresetTree"
>
<template #prefix>
<el-icon><Search /></el-icon>
</template>
</el-input>
</div>
<!-- 预设树 -->
<div class="preset-tree" v-if="filteredPresetTree && filteredPresetTree.length > 0">
<el-tree
ref="presetTreeRef"
:data="filteredPresetTree"
:props="treeProps"
node-key="id"
accordion
highlight-current
:expand-on-click-node="false"
:filter-node-method="filterNode"
@node-click="handlePresetClick"
>
<template #default="{ node, data }">
<span class="custom-tree-node">
<span class="tree-node-content">
<i v-if="data.icon" :class="data.icon" class="tree-icon"></i>
<span class="node-label">{{ node.label }}</span>
<span v-if="data.count" class="count-badge">{{ data.count }}</span>
</span>
</span>
</template>
</el-tree>
</div>
<!-- 空状态 -->
<div v-else class="empty-preset">
<div class="empty-content">
<el-icon size="40"><Files /></el-icon>
<p>暂无预设过滤条件</p>
</div>
</div>
</div>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import { ref, reactive, watch, computed, onMounted, onBeforeUnmount, nextTick } from 'vue'
import { useRoute } from 'vue-router'
import { useScanBoxCacheStore } from '@/stores/modules/scanBoxCache'
import { Operation, DataAnalysis, Search, Files } from '@element-plus/icons-vue'
defineOptions({
name: 'ScanBox'
})
const props = defineProps({
// 组件宽度
width: {
type: String,
default: '250px'
},
// 预设树状条件
presetTree: {
type: Array,
default: () => []
},
// 树形结构配置
treeProps: {
type: Object,
default: () => ({
children: 'children',
label: 'label'
})
},
// 可用字段配置
availableFields: {
type: Array as any,
default: () => []
},
// 默认操作符配置
defaultOperators: {
type: Object,
default: () => ({
text: [
{ value: 'eq', label: '等于' },
{ value: 'ne', label: '不等于' },
{ value: 'like', label: '模糊匹配' },
{ value: 'notlike', label: '模糊排除' },
{ value: 'contains', label: '包含' },
{ value: 'startswith', label: '开头为' },
{ value: 'endswith', label: '结尾为' },
{ value: 'in', label: 'IN(逗号分隔)' },
{ value: 'notin', label: 'NOT IN' },
{ value: 'isnull', label: '为空' },
{ value: 'isnotnull', label: '不为空' },
{ value: 'regexp', label: '正则匹配' },
{ value: 'notregexp', label: '正则不匹配' }
],
number: [
{ value: 'eq', label: '等于' },
{ value: 'ne', label: '不等于' },
{ value: 'gt', label: '大于' },
{ value: 'lt', label: '小于' },
{ value: 'ge', label: '大于等于' },
{ value: 'le', label: '小于等于' },
{ value: 'between', label: '区间内' },
{ value: 'notbetween', label: '区间外' },
{ value: 'in', label: 'IN(逗号分隔)' },
{ value: 'notin', label: 'NOT IN' },
{ value: 'isnull', label: '为空' },
{ value: 'isnotnull', label: '不为空' }
],
date: [
{ value: 'eq', label: '等于' },
{ value: 'ne', label: '不等于' },
{ value: 'gt', label: '晚于' },
{ value: 'lt', label: '早于' },
{ value: 'ge', label: '大于等于' },
{ value: 'le', label: '小于等于' },
{ value: 'between', label: '区间内' },
{ value: 'notbetween', label: '区间外' },
{ value: 'isnull', label: '为空' },
{ value: 'isnotnull', label: '不为空' }
],
daterange: [
{ value: 'between', label: '区间' }
],
datetimerange: [
{ value: 'between', label: '区间' }
]
})
},
// 初始条件
initialConditions: {
type: Object,
default: null
},
// 同一路由下不同功能页的筛选缓存隔离键
cacheKey: {
type: String,
default: ''
},
// 是否自动提交
autoSubmit: {
type: Boolean,
default: false
}
})
const emit = defineEmits(['condition-change', 'reset', 'condition-clear', 'submit', 'field-action'])
const route = useRoute()
const scanBoxCacheStore = useScanBoxCacheStore()
// Data
const activeTab = ref('custom')
const customConditions = reactive<any>({})
const presetSearchText = ref('')
const filteredPresetTree = ref<any[]>([])
const activeCondition = ref<any>(null)
const submitting = ref(false)
const hasScroll = ref(false)
const filterScroll = ref<HTMLElement | null>(null)
const presetTreeRef = ref<any>(null)
let debounceTimer: any = null
let cacheTimer: any = null
function cloneSnapshotValue<T>(value: T): T {
if (value === undefined) {
return value
}
return JSON.parse(JSON.stringify(value))
}
function getRouteCacheKey() {
return String(route.path || '').trim()
}
function getScopedCacheKey() {
return String(props.cacheKey || '').trim()
}
function saveSnapshot() {
const routePath = getRouteCacheKey()
if (!routePath) return
scanBoxCacheStore.setSnapshot(routePath, {
activeTab: activeTab.value,
activeCondition: cloneSnapshotValue(activeCondition.value),
customConditions: cloneSnapshotValue(customConditions)
}, getScopedCacheKey())
}
/** 仅保存 UI 草稿(表单值),不覆盖上次查询的 activeCondition */
function saveDraftSnapshot() {
const routePath = getRouteCacheKey()
if (!routePath) return
const existing = scanBoxCacheStore.getSnapshot(routePath, getScopedCacheKey())
scanBoxCacheStore.setSnapshot(routePath, {
activeTab: activeTab.value,
activeCondition: existing?.activeCondition ?? null,
customConditions: cloneSnapshotValue(customConditions)
}, getScopedCacheKey())
}
function scheduleSaveSnapshot() {
clearTimeout(cacheTimer)
cacheTimer = setTimeout(() => {
saveDraftSnapshot()
}, 120)
}
function clearSnapshot() {
const routePath = getRouteCacheKey()
if (!routePath) return
scanBoxCacheStore.clearSnapshot(routePath, getScopedCacheKey())
}
function hasAnyCondition() {
if (activeTab.value === 'preset') {
return Boolean(activeCondition.value)
}
return Object.keys(buildConditionsObject() || {}).length > 0
}
function restoreSnapshotIfExists() {
const routePath = getRouteCacheKey()
if (!routePath) return
const snapshot = scanBoxCacheStore.getSnapshot(routePath, getScopedCacheKey())
if (!snapshot) return
if (snapshot.activeTab) {
activeTab.value = snapshot.activeTab
}
activeCondition.value = cloneSnapshotValue(snapshot.activeCondition)
Object.keys(snapshot.customConditions || {}).forEach((fieldKey) => {
if (!customConditions[fieldKey]) return
Object.assign(customConditions[fieldKey], snapshot.customConditions[fieldKey])
})
nextTick(() => {
if (hasAnyCondition()) {
emit('condition-change', activeCondition.value)
}
})
}
// Watchers
watch(() => props.initialConditions, (val) => {
if (val) {
loadInitialConditions(val)
}
}, { immediate: true })
watch(() => props.presetTree, (val) => {
if (val && Array.isArray(val)) {
filteredPresetTree.value = JSON.parse(JSON.stringify(val))
} else {
filteredPresetTree.value = []
}
}, { immediate: true })
watch(() => props.availableFields, (fields) => {
initCustomConditions(fields)
}, { immediate: true })
watch(activeTab, () => {
scheduleSaveSnapshot()
})
// Computed
const fieldValues = computed(() => {
return props.availableFields.map((field: any) => field.value)
})
// Lifecycle
onMounted(() => {
initCustomConditions(props.availableFields)
restoreSnapshotIfExists()
if (filterScroll.value) {
filterScroll.value.addEventListener('scroll', handleScroll)
}
checkScroll()
})
onBeforeUnmount(() => {
clearTimeout(cacheTimer)
clearTimeout(debounceTimer)
if (filterScroll.value) {
filterScroll.value.removeEventListener('scroll', handleScroll)
}
})
// Methods
// 操作符类型辅助函数
function isNullishOperator(op: string) {
return ['isnull', 'isnotnull'].includes(op)
}
function isRangeOperator(op: string) {
return ['between', 'notbetween'].includes(op)
}
function isMultiOperator(op: string) {
return ['in', 'notin'].includes(op)
}
function isMultiValueTextOperator(op: string) {
return ['contains', 'in', 'notin'].includes(op)
}
function normalizeMultiValueText(raw: string): string {
if (!raw) return raw
const normalized = raw
.replace(/[\r\n\t]+/g, ',')
.replace(/[,;;、]+/g, ',')
const values = normalized
.split(',')
.map((v) => v.trim())
.filter(Boolean)
return values.join(',')
}
function getTextPlaceholder(field: any) {
const operator = customConditions[field.value].operator
const basePlaceholder = field.placeholder || `请输入${field.label}`
if (operator === 'contains' || operator === 'in' || operator === 'notin') {
return `${basePlaceholder}(多个值用逗号分隔)`
}
return basePlaceholder
}
// 统一的操作符切换处理函数
function handleOperatorChange(field: any) {
const operator = customConditions[field.value].operator
// 切换至非多值操作符时,如果当前值是数组则转为逗号字符串
if (!['contains', 'in', 'notin'].includes(operator)) {
const currentValue = customConditions[field.value].value
if (Array.isArray(currentValue)) {
customConditions[field.value].value = currentValue.join(', ')
}
}
// 切换至 isnull/isnotnull 时清空值
if (isNullishOperator(operator)) {
customConditions[field.value].value = undefined
customConditions[field.value].valueMin = undefined
customConditions[field.value].valueMax = undefined
}
handleCustomChange()
}
// 升级兼容:保留旧名称供内部历史调用
function handleTextOperatorChange(field: any) {
handleOperatorChange(field)
}
function normalizeTextValue(field: any) {
const operator = customConditions[field.value].operator
const value = customConditions[field.value].value
if (!isMultiValueTextOperator(operator) || !value) {
return
}
let normalizedValue = normalizeMultiValueText(String(value))
if (operator === 'contains') {
normalizedValue = normalizedValue
.replace(/\s+/g, '')
.replace(/,+/g, ',')
.replace(/^,|,$/g, '')
}
if (normalizedValue !== value) {
customConditions[field.value].value = normalizedValue
handleCustomChange()
}
}
function handleMultiValuePaste(event: ClipboardEvent, field: any) {
const operator = customConditions[field.value].operator
if (!isMultiValueTextOperator(operator)) return
const pasted = event.clipboardData?.getData('text') || ''
if (!/[\r\n\t]/.test(pasted)) return
event.preventDefault()
const current = String(customConditions[field.value].value || '').trim()
const normalizedPaste = normalizeMultiValueText(pasted)
if (!normalizedPaste) return
customConditions[field.value].value = current
? `${current.replace(/,+$/g, '')},${normalizedPaste}`
: normalizedPaste
handleCustomChange()
nextTick(() => {
handleSubmit()
})
}
const defaultDayStart = new Date(2000, 0, 1, 0, 0, 0)
const defaultDayEnd = new Date(2000, 0, 1, 23, 59, 59)
function isRangePickerFieldType(type: string) {
return type === 'daterange' || type === 'datetimerange'
}
function isRangePickerField(field: any) {
return isRangePickerFieldType(String(field?.type || ''))
}
function isDateTimeRangeField(field: any) {
return field?.type === 'datetimerange'
}
function getRangePickerType(field: any) {
return isDateTimeRangeField(field) ? 'datetimerange' : 'daterange'
}
function getRangePickerFormat(field: any) {
if (field?.format) return field.format
return isDateTimeRangeField(field) ? 'YYYY-MM-DD HH:mm' : 'YYYY-MM-DD'
}
function getRangePickerValueFormat(field: any) {
if (field?.valueFormat) return field.valueFormat
return isDateTimeRangeField(field) ? 'YYYY-MM-DD HH:mm:ss' : 'YYYY-MM-DD'
}
function getRangePickerStartPlaceholder(field: any) {
return isDateTimeRangeField(field) ? '开始时间' : '开始日期'
}
function getRangePickerEndPlaceholder(field: any) {
return isDateTimeRangeField(field) ? '结束时间' : '结束日期'
}
function getRangePickerDefaultTime(field: any) {
if (!isDateTimeRangeField(field)) return undefined
return [defaultDayStart, defaultDayEnd] as [Date, Date]
}
function resolveRangeConditionMeta(field: any, op: string) {
if (isRangePickerFieldType(field.type)) {
return {
operator: 'between',
type: field.type
}
}
return {
operator: op,
type: field.type
}
}
function cloneConditionDefaultValue(value: any) {
if (value === undefined) return undefined
if (value === null) return null
if (Array.isArray(value) || typeof value === 'object') {
return JSON.parse(JSON.stringify(value))
}
return value
}
function initCustomConditions(fields: any[], isSilent = false, forceReset = false) {
fields.forEach(field => {
let defaultValue: any = undefined
let defaultOperator = ''
switch (field.type) {
case 'select':
case 'multiple':
defaultValue = field.multiple ? [] : undefined
break
case 'boolean':
defaultValue = ''
break
case 'daterange':
case 'datetimerange':
defaultValue = []
defaultOperator = 'between'
break
default:
defaultValue = undefined
}
// daterange 已在上面 switch 设置了 defaultOperator,其他类型按字段配置或默认列表确定
if (!isRangePickerFieldType(field.type)) {
if (field.operators && Array.isArray(field.operators) && field.operators.length > 0) {
defaultOperator = field.defaultOperator || field.operators[0]
} else {
const defaultOps = props.defaultOperators[field.type as keyof typeof props.defaultOperators]
if (defaultOps && defaultOps.length > 0) {
defaultOperator = field.defaultOperator || defaultOps[0].value || ''
}
}
}
if (Object.prototype.hasOwnProperty.call(field, 'defaultValue')) {
defaultValue = cloneConditionDefaultValue(field.defaultValue)
}
if (!customConditions[field.value]) {
customConditions[field.value] = {
value: defaultValue,
operator: defaultOperator,
valueMin: undefined,
valueMax: undefined
}
} else if (forceReset) {
customConditions[field.value].value = defaultValue
customConditions[field.value].operator = defaultOperator
customConditions[field.value].valueMin = undefined
customConditions[field.value].valueMax = undefined
}
})
if (isSilent) return
if (props.autoSubmit) {
handleCustomChange()
}
}
function loadInitialConditions(conditions: any) {
if (conditions.type === 'preset') {
activeCondition.value = conditions
activeTab.value = 'preset'
} else if (conditions.type === 'custom') {
activeCondition.value = conditions
activeTab.value = 'custom'
if (conditions.conditions) {
Object.keys(conditions.conditions).forEach(field => {
if (customConditions[field]) {
Object.assign(customConditions[field], conditions.conditions[field])
}
})
}
}
}
function checkScroll() {
if (!filterScroll.value) return
hasScroll.value = filterScroll.value.scrollHeight > filterScroll.value.clientHeight
}
function handleScroll() {
checkScroll()
}
function handleTabChange(pane: any) {
// Element Plus tab-click returns pane context. pane.paneName is the name.
// Vue 2 was tab component instance.
if (pane.paneName === 'custom') {
nextTick(() => {
checkScroll()
})
}
}
function resolveFieldGroupLabel(field: any, index: number | string): string | null {
const fieldIndex = Number(index)
const group = field?.group
if (!group || typeof group !== 'string') return null
if (fieldIndex === 0) return group
const prev = props.availableFields[fieldIndex - 1] as any
return prev?.group === group ? null : group
}
function getOperators(field: any) {
if (field.operators && field.operators.length > 0) {
const operatorDefinitions = props.defaultOperators[field.type as keyof typeof props.defaultOperators] || []
return operatorDefinitions.filter((op: any) => field.operators.includes(op.value))
}
return props.defaultOperators[field.type as keyof typeof props.defaultOperators] || (props.defaultOperators as any).text || []
}
function handlePresetClick(data: any, node: any) {
if (!node.isLeaf) return
activeCondition.value = data.value
scheduleSaveSnapshot()
emit('condition-change', activeCondition.value)
}
function handleCustomChange() {
scheduleSaveSnapshot()
if (props.autoSubmit) {
clearTimeout(debounceTimer)
debounceTimer = setTimeout(() => {
buildAndEmitCustomCondition()
}, 300)
}
}
/** select 选项可带 operator、conditionValue(用于波次分配等同一字段不同操作符) */
function buildMappedSelectCondition(field: any, condition: any): { value: any; operator: string; type: string } | null {
if (field.type !== 'select' || !Array.isArray(field.options)) return null
const raw = condition.value
if (raw === undefined || raw === null || raw === '') return null
const selected = field.options.find((o: any) => o.value === raw)
if (!selected || typeof selected.operator !== 'string' || !selected.operator) return null
const apiValue = Object.prototype.hasOwnProperty.call(selected, 'conditionValue')
? selected.conditionValue
: selected.value
return {
value: apiValue,
operator: selected.operator,
type: field.conditionType || 'text'
}
}
function buildAndEmitCustomCondition() {
const conditions: any = {}
let hasCondition = false
props.availableFields.forEach((field: any) => {
const condition = customConditions[field.value]
const op = condition.operator
// isnull / isnotnull: 无需值,直接包含
if (isNullishOperator(op)) {
conditions[field.value] = {
value: null,
operator: op,
field: field.value,
type: field.type
}
hasCondition = true
return
}
// between / notbetween 对 number 类型:使用 valueMin/valueMax
if (field.type === 'number' && isRangeOperator(op)) {
const min = condition.valueMin
const max = condition.valueMax
if (min !== undefined && min !== null && max !== undefined && max !== null) {
conditions[field.value] = {
value: [min, max],
operator: op,
field: field.value,
type: 'number'
}
hasCondition = true
}
return
}
const mappedSelectEmit = buildMappedSelectCondition(field, condition)
if (mappedSelectEmit) {
conditions[field.value] = {
...mappedSelectEmit,
field: field.value,
isMultiple: false
}
hasCondition = true
return
}
let conditionValue = condition.value
// 处理多值操作符:contains / in / notin 逗号分隔 -> 数组
if (['contains', 'in', 'notin'].includes(op) && typeof conditionValue === 'string' && conditionValue) {
const values = conditionValue.split(',').map((v: string) => v.trim()).filter(Boolean)
if (values.length > 0) {
conditionValue = values
}
}
const rangeMeta = resolveRangeConditionMeta(field, op)
const finalOp = rangeMeta.operator
const finalType = rangeMeta.type
if (conditionValue !== undefined &&
conditionValue !== null &&
conditionValue !== '' &&
!(Array.isArray(conditionValue) && conditionValue.length === 0)) {
conditions[field.value] = {
value: conditionValue,
operator: finalOp,
field: field.value,
type: finalType,
isMultiple: Array.isArray(conditionValue)
}
hasCondition = true
}
})
if (hasCondition) {
activeCondition.value = conditions
saveSnapshot()
emit('condition-change', activeCondition.value)
} else if (activeCondition.value && activeCondition.value.type === 'custom') {
clearActiveCondition()
}
}
function filterPresetTree(val: string) {
if (presetTreeRef.value) {
presetTreeRef.value.filter(val)
}
}
function filterNode(value: string, data: any) {
if (!value) return true
return data.label && data.label.toLowerCase().includes(value.toLowerCase())
}
/** 仅重置内部 UI 状态,不向外 emit(供 defineExpose 与父组件二次调用,避免与 @reset 形成递归) */
function applyResetState() {
initCustomConditions(props.availableFields, true, true)
activeCondition.value = null
presetSearchText.value = ''
filterPresetTree('')
}
function handleReset() {
applyResetState()
clearSnapshot()
emit('reset')
}
function handleSubmit() {
submitting.value = true
// 查询前立即持久化当前条件,供刷新恢复和导出使用
saveSnapshot()
// 对于自定义筛选,先构建当前条件但不依赖 buildAndEmitCustomCondition 的内部 emit
if (activeTab.value === 'custom') {
const currentConditions = buildConditionsObject()
if (currentConditions && Object.keys(currentConditions).length > 0) {
activeCondition.value = currentConditions
emit('condition-change', activeCondition.value)
} else {
// 没有任何自定义条件时,明确发出空条件,父组件应按无筛选(即 loadList)处理
activeCondition.value = null
emit('condition-change', {})
}
} else if (activeTab.value === 'preset') {
// 预设直接发送当前选中的预设条件(可能为 null)
emit('condition-change', activeCondition.value)
} else {
// 兜底:仍然调用构建并可能触发自动提交逻辑
buildAndEmitCustomCondition()
}
emit('submit', activeCondition.value)
setTimeout(() => {
submitting.value = false
}, 300)
}
function clearActiveCondition() {
activeCondition.value = null
clearSnapshot()
emit('condition-clear')
}
// 对外暴露的方法,供父组件调用
function getConditions() {
// 如果当前是自定义筛选,且没有已应用的 activeCondition,或者想要获取最新的输入值
// 我们可以根据 activeTab 来决定返回什么
if (activeTab.value === 'custom') {
const currentConditions = buildConditionsObject()
return currentConditions
}
if (!activeCondition.value) return {}
if (typeof activeCondition.value === 'string' || typeof activeCondition.value === 'number') {
return { preset: activeCondition.value }
}
if (activeCondition.value && (activeCondition.value as any).conditions) {
const where: any = {}
Object.keys((activeCondition.value as any).conditions).forEach((k) => {
const c = (activeCondition.value as any).conditions[k]
where[k] = c && c.value !== undefined ? c.value : c
})
return where
}
if (typeof activeCondition.value === 'object') {
const where: any = {}
Object.keys(activeCondition.value).forEach((k) => {
const c = (activeCondition.value as any)[k]
where[k] = c && c.value !== undefined ? c.value : c
})
return where
}
return {}
}
function buildConditionsObject() {
const conditions: any = {}
props.availableFields.forEach((field: any) => {
const condition = customConditions[field.value]
const op = condition.operator
// isnull / isnotnull
if (isNullishOperator(op)) {
conditions[field.value] = {
value: null,
operator: op,
type: field.type
}
return
}
// between / notbetween 对 number
if (field.type === 'number' && isRangeOperator(op)) {
const min = condition.valueMin
const max = condition.valueMax
if (min !== undefined && min !== null && max !== undefined && max !== null) {
conditions[field.value] = {
value: [min, max],
operator: op,
type: 'number'
}
}
return
}
const mappedSelectObj = buildMappedSelectCondition(field, condition)
if (mappedSelectObj) {
conditions[field.value] = mappedSelectObj
return
}
let conditionValue = condition.value
if (['contains', 'in', 'notin'].includes(op) && typeof conditionValue === 'string' && conditionValue) {
const values = conditionValue.split(',').map((v: string) => v.trim()).filter(Boolean)
if (values.length > 0) conditionValue = values
}
const rangeMeta = resolveRangeConditionMeta(field, op)
const finalOp = rangeMeta.operator
const finalType = rangeMeta.type
if (conditionValue !== undefined &&
conditionValue !== null &&
conditionValue !== '' &&
!(Array.isArray(conditionValue) && conditionValue.length === 0)) {
conditions[field.value] = {
value: conditionValue,
operator: finalOp,
type: finalType
}
}
})
return conditions
}
function reset() {
applyResetState()
}
function clear() {
clearActiveCondition()
}
function handleFieldAction(field: any) {
emit('field-action', field.value, field)
}
function getFieldDraft(fieldKey: string) {
const condition = customConditions[fieldKey]
if (!condition) return null
return {
value: condition.value,
operator: condition.operator,
valueMin: condition.valueMin,
valueMax: condition.valueMax
}
}
function setFieldCondition(
fieldKey: string,
patch: { operator?: string; value?: any; valueMin?: any; valueMax?: any },
options: { autoSubmit?: boolean } = {}
) {
if (!customConditions[fieldKey]) {
customConditions[fieldKey] = {
value: undefined,
operator: 'eq',
valueMin: undefined,
valueMax: undefined
}
}
activeTab.value = 'custom'
const nextCondition = {
...customConditions[fieldKey],
...(patch.operator !== undefined ? { operator: patch.operator } : {}),
...(patch.value !== undefined ? { value: patch.value } : {}),
...(patch.valueMin !== undefined ? { valueMin: patch.valueMin } : {}),
...(patch.valueMax !== undefined ? { valueMax: patch.valueMax } : {})
}
customConditions[fieldKey] = nextCondition
scheduleSaveSnapshot()
if (options.autoSubmit === true) {
handleSubmit()
return
}
if (options.autoSubmit !== false && props.autoSubmit) {
handleCustomChange()
}
}
/** 获取上次查询时存储的条件,供导出等场景复用 */
function getStoredConditions() {
const routePath = getRouteCacheKey()
if (!routePath) return null
return scanBoxCacheStore.getSnapshot(routePath, getScopedCacheKey())
}
defineExpose({ getConditions, reset, clear, getFieldDraft, setFieldCondition, submit: handleSubmit, getStoredConditions })
</script>
<style scoped>
.scan-box-container {
height: 100%;
display: flex;
flex-direction: column;
background: #fff;
border-right: 1px solid #e8e8e8;
box-shadow: 1px 0 2px rgba(0, 0, 0, 0.05);
width: 250px;
min-width: 160px;
}
.scan-tabs {
flex-shrink: 0;
border-bottom: 1px solid #e8e8e8;
background: #fafafa;
}
.scan-tabs :deep(.el-tabs__header) {
margin: 0;
}
.scan-tabs :deep(.el-tabs__nav-wrap::after) {
height: 1px;
}
.scan-tabs :deep(.el-tabs__item) {
height: 40px;
line-height: 40px;
font-size: 13px;
}
.tab-label {
display: flex;
align-items: center;
justify-content: center;
gap: 4px;
}
.scan-content {
flex: 1;
display: flex;
flex-direction: column;
overflow: hidden;
}
.custom-filter,
.preset-filter {
flex: 1;
display: flex;
flex-direction: column;
overflow: hidden;
}
.filter-scroll-area {
flex: 1;
overflow-y: auto;
padding: 16px;
/* 隐藏滚动条 */
&::-webkit-scrollbar {
display: none;
}
-ms-overflow-style: none; /* IE and Edge */
scrollbar-width: none; /* Firefox */
}
/* 自定义筛选样式 */
.field-forms {
display: flex;
flex-direction: column;
gap: 16px;
}
.field-group-divider {
margin-top: 4px;
padding-top: 4px;
}
.field-group-divider:not(:first-child) {
border-top: 1px dashed #e8e8e8;
margin-top: 8px;
padding-top: 12px;
}
.field-group-label {
display: block;
font-size: 12px;
font-weight: 600;
color: #909399;
letter-spacing: 0.5px;
line-height: 1.4;
}
.field-form-item {
display: flex;
flex-direction: column;
gap: 8px;
}
.field-label {
display: flex;
justify-content: space-between;
align-items: center;
font-size: 13px;
font-weight: 500;
color: #333;
}
.field-label-text {
display: flex;
align-items: center;
gap: 4px;
min-width: 0;
}
.field-label .el-tag {
margin-left: 0;
}
.field-extra-action {
flex-shrink: 0;
padding: 0;
height: auto;
font-size: 12px;
}
.field-control {
display: flex;
flex-direction: row;
gap: 4px;
}
.operator-select {
width: 85px;
flex-shrink: 0;
}
.value-input {
flex: 1;
min-width: 0;
}
.field-control--range,
.field-control--multi {
flex-direction: column;
}
.field-control--multi .operator-select {
width: 100%;
}
.field-control--multi .value-input--multi {
width: 100%;
}
.field-control--multi :deep(.el-textarea__inner) {
min-height: 72px;
line-height: 1.5;
font-size: 12px;
}
.field-control--range :deep(.el-date-editor--daterange),
.field-control--range :deep(.el-date-editor--datetimerange) {
width: 100%;
}
.field-control--range :deep(.el-range-input) {
font-size: 12px;
}
.field-control :deep(.el-input__wrapper),
.field-control :deep(.el-select__wrapper) {
border-radius: 4px;
}
/* 预设筛选样式 */
.preset-search {
margin-bottom: 12px;
}
.preset-tree {
padding: 8px 0;
}
.custom-tree-node {
flex: 1;
display: flex;
align-items: center;
justify-content: space-between;
font-size: 13px;
padding: 2px 0;
}
.tree-node-content {
display: flex;
align-items: center;
gap: 6px;
}
.tree-icon {
color: #409eff;
font-size: 14px;
}
.node-label {
flex: 1;
}
.count-badge {
background: #f0f0f0;
padding: 2px 6px;
border-radius: 10px;
font-size: 12px;
color: #999;
}
.empty-preset {
display: flex;
align-items: center;
justify-content: center;
height: 100%;
color: #999;
}
.empty-content {
text-align: center;
}
.empty-content i {
font-size: 40px;
margin-bottom: 12px;
color: #e0e0e0;
}
.empty-content p {
margin: 0;
font-size: 13px;
}
/* 底部固定操作栏 */
.fixed-bottom-actions {
flex-shrink: 0;
padding: 12px 16px;
background: #fff;
border-top: 1px solid #e8e8e8;
display: flex;
justify-content: flex-end;
box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.05);
z-index: 10;
transition: all 0.3s;
}
.fixed-bottom-actions.has-scroll {
box-shadow: 0 -4px 12px rgba(0, 0, 0, 0.1);
}
.actions-content {
display: flex;
gap: 12px;
width: 100%;
}
.actions-content button {
flex: 1;
}
.reset-btn {
color: #666;
}
/* 区间双输入样式 */
.range-input {
flex: 1;
min-width: 0;
}
.range-sep {
flex-shrink: 0;
line-height: 28px;
font-size: 12px;
color: #909399;
padding: 0 2px;
}
/* isnull/isnotnull 无需填值提示 */
.no-value-tip {
flex: 1;
font-size: 12px;
color: #c0c4cc;
line-height: 28px;
padding-left: 4px;
font-style: italic;
}
</style>