1711 lines
47 KiB
Vue
1711 lines
47 KiB
Vue
<template>
|
||
<div class="upper-table-container" :class="tableSize">
|
||
<!-- 表格区域 -->
|
||
<div class="table-container" ref="tableContainer">
|
||
<el-table
|
||
v-loading="loading"
|
||
ref="tableRef"
|
||
:data="tableRenderData"
|
||
:highlight-current-row="highlightCurrentRow"
|
||
:row-key="rowKey"
|
||
:current-row-key="currentRowKey"
|
||
@current-change="handleCurrentChange"
|
||
@row-click="handleRowClick"
|
||
@row-contextmenu="handleRowContextMenu"
|
||
@sort-change="handleSortChange"
|
||
style="width: 100%"
|
||
:size="tableSize"
|
||
:border="border"
|
||
:stripe="stripe"
|
||
:show-header="showHeader"
|
||
:empty-text="emptyText"
|
||
:fit="fit"
|
||
:tooltip-effect="tooltipEffect"
|
||
:row-class-name="getRowClassName"
|
||
:row-style="getRowStyle"
|
||
height="100%"
|
||
>
|
||
<!-- 自定义选择列 -->
|
||
<el-table-column v-if="showSelection" :width="selectionColumnWidth" fixed="left">
|
||
<!-- 表头 -->
|
||
<template #header>
|
||
<div class="custom-selection-header" @click.stop="toggleAllSelection">
|
||
<el-checkbox
|
||
v-model="isAllSelectedInView"
|
||
:indeterminate="isIndeterminate"
|
||
@click.stop="toggleAllSelection"
|
||
/>
|
||
</div>
|
||
</template>
|
||
|
||
<!-- 单元格 -->
|
||
<template #default="scope">
|
||
<template v-if="isVirtualSpacerRow(scope.row)">
|
||
<span class="virtual-spacer-cell"></span>
|
||
</template>
|
||
<template v-else>
|
||
<div class="custom-selection-cell" @click.stop="toggleRowSelection(scope.row)">
|
||
<el-checkbox
|
||
:model-value="isRowSelected(scope.row)"
|
||
:key="`checkbox-${getRowKey(scope.row)}-${checkboxUpdateKey}`"
|
||
@click.stop="toggleRowSelection(scope.row)"
|
||
/>
|
||
</div>
|
||
</template>
|
||
</template>
|
||
</el-table-column>
|
||
|
||
<!-- 动态列 -->
|
||
<template v-for="column in displayColumns" :key="column.prop">
|
||
<el-table-column
|
||
v-if="column.prop"
|
||
:prop="column.prop"
|
||
:label="column.label"
|
||
:width="column.width"
|
||
:min-width="column.minWidth"
|
||
:fixed="column.fixed"
|
||
:sortable="column.sortable"
|
||
:sort-by="column.sortBy"
|
||
:sort-orders="column.sortOrders"
|
||
:resizable="column.resizable"
|
||
:show-overflow-tooltip="column.showOverflowTooltip !== false"
|
||
:align="column.align || 'left'"
|
||
:header-align="column.headerAlign || column.align || 'left'"
|
||
:class-name="column.className"
|
||
:label-class-name="column.labelClassName"
|
||
:filters="column.filters"
|
||
:filter-method="column.filterMethod"
|
||
:filtered-value="column.filteredValue"
|
||
:filter-multiple="column.filterMultiple"
|
||
:filter-placement="column.filterPlacement"
|
||
>
|
||
<template #default="scope">
|
||
<template v-if="isVirtualSpacerRow(scope.row)">
|
||
<span class="virtual-spacer-cell"></span>
|
||
</template>
|
||
<template v-else>
|
||
<slot :name="`column-${column.prop}`" :row="scope.row" :index="scope.$index">
|
||
<template v-if="column.formatter">
|
||
<span v-html="column.formatter(scope.row, scope.column, scope.row[scope.column.property], scope.$index)"></span>
|
||
</template>
|
||
<template v-else-if="column.prop === 'order_flag'">
|
||
<el-tooltip
|
||
:content="getOrderFlagFullText(scope.row[column.prop])"
|
||
placement="top"
|
||
:disabled="!getOrderFlagFullText(scope.row[column.prop])"
|
||
:show-after="400"
|
||
>
|
||
<span
|
||
:class="getDefaultCellTextClass(column.prop, scope.row[column.prop])"
|
||
role="button"
|
||
tabindex="0"
|
||
@click.stop="copyOrderFlagText(scope.row[column.prop])"
|
||
@keydown.enter.prevent="copyOrderFlagText(scope.row[column.prop])"
|
||
>
|
||
{{ getOrderFlagCellText(scope.row[column.prop]) }}
|
||
</span>
|
||
</el-tooltip>
|
||
</template>
|
||
<template v-else-if="column.template">
|
||
<component
|
||
:is="column.template"
|
||
:row="scope.row"
|
||
:column="scope.column"
|
||
:index="scope.$index"
|
||
/>
|
||
</template>
|
||
<template v-else-if="column.imgs">
|
||
<el-image
|
||
style="height: 23px; overflow: unset; margin: 0 3px"
|
||
v-for="(img, idx) in column.imgs(scope.row, scope.column, scope.$index)"
|
||
:key="idx"
|
||
:src="img"
|
||
:preview-src-list="column.imgs(scope.row, scope.column, scope.$index)"
|
||
preview-teleported
|
||
></el-image>
|
||
</template>
|
||
<span v-else :class="getDefaultCellTextClass(column.prop, scope.row[column.prop])">{{ scope.row[column.prop] }}</span>
|
||
</slot>
|
||
</template>
|
||
</template>
|
||
</el-table-column>
|
||
</template>
|
||
|
||
<!-- 空状态插槽 -->
|
||
<template #empty>
|
||
<slot name="empty">
|
||
<div class="empty-table">
|
||
<el-icon size="48" color="#c0c4cc"><Box /></el-icon>
|
||
<p>{{ emptyText }}</p>
|
||
</div>
|
||
</slot>
|
||
</template>
|
||
</el-table>
|
||
</div>
|
||
|
||
<!-- 分页区域 -->
|
||
<div class="pagination-container" v-if="showPagination">
|
||
<div class="pagination-info">
|
||
已选 {{ selectedCount }} 条,查询用时 {{ (queryTime / 1000).toFixed(2) }} 秒
|
||
</div>
|
||
<el-pagination
|
||
:current-page="pagination.currentPage"
|
||
:page-sizes="pageSizes"
|
||
:page-size="pagination.pageSize"
|
||
:total="total"
|
||
:layout="paginationLayout"
|
||
:background="paginationBackground"
|
||
:size="tableSize"
|
||
@size-change="handlePageSizeChange"
|
||
@current-change="handlePageChange"
|
||
/>
|
||
</div>
|
||
|
||
<el-dialog
|
||
v-model="columnConfigDialogVisible"
|
||
title="字段设置"
|
||
width="560px"
|
||
align-center
|
||
append-to-body
|
||
>
|
||
<div class="column-config-toolbar">
|
||
<el-button size="small" @click="resetColumnConfig">恢复默认</el-button>
|
||
<el-button size="small" @click="exportGlobalColumnConfig">导出全局配置</el-button>
|
||
<el-upload
|
||
accept=".json"
|
||
:show-file-list="false"
|
||
:auto-upload="false"
|
||
:on-change="handleImportColumnConfig"
|
||
>
|
||
<el-button size="small">导入全局配置</el-button>
|
||
</el-upload>
|
||
<el-button size="small" type="danger" plain @click="handleRepairColumnConfig">故障修复</el-button>
|
||
</div>
|
||
<div class="column-config-list" ref="columnConfigListRef">
|
||
<template v-for="section in columnConfigDialogSections" :key="section.key">
|
||
<div class="column-config-section">
|
||
<div class="column-config-section-title">{{ section.title }}</div>
|
||
<div
|
||
v-for="(item, sIdx) in section.items"
|
||
:key="item.prop"
|
||
class="column-config-item"
|
||
:class="{
|
||
'is-fixed-column': section.key !== 'scroll',
|
||
'is-draggable': section.key === 'scroll',
|
||
'is-drag-over': section.key === 'scroll' && dragOverProp === item.prop
|
||
}"
|
||
:draggable="section.key === 'scroll'"
|
||
@dragstart="onColumnDragStart($event, item)"
|
||
@dragover.prevent="onColumnDragOver($event, item)"
|
||
@drop.prevent="onColumnDrop(item)"
|
||
@dragend="onColumnDragEnd"
|
||
>
|
||
<div class="column-config-main">
|
||
<span
|
||
v-if="section.key === 'scroll'"
|
||
class="drag-handle"
|
||
aria-hidden="true"
|
||
>⋮⋮</span>
|
||
<span
|
||
v-else
|
||
class="drag-handle drag-handle--locked"
|
||
title="固定列不可调整顺序"
|
||
>⋮⋮</span>
|
||
<el-checkbox
|
||
:model-value="item.visible"
|
||
@change="(val: any) => onToggleColumnVisible(item.prop, !!val)"
|
||
>
|
||
{{ item.label || item.prop }}
|
||
</el-checkbox>
|
||
</div>
|
||
<div v-if="section.key === 'scroll'" class="column-config-actions">
|
||
<el-button
|
||
text
|
||
:disabled="sIdx === 0"
|
||
@click="moveColumn(item.prop, 'up')"
|
||
>
|
||
上移
|
||
</el-button>
|
||
<el-button
|
||
text
|
||
:disabled="sIdx === section.items.length - 1"
|
||
@click="moveColumn(item.prop, 'down')"
|
||
>
|
||
下移
|
||
</el-button>
|
||
</div>
|
||
<div v-else class="column-config-actions column-config-actions--fixed">
|
||
<span class="column-config-fixed-hint">固定</span>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</template>
|
||
</div>
|
||
<template #footer>
|
||
<el-button @click="columnConfigDialogVisible = false">关闭</el-button>
|
||
</template>
|
||
</el-dialog>
|
||
</div>
|
||
</template>
|
||
|
||
<script setup lang="ts">
|
||
import { ref, computed, watch, onMounted, onBeforeUnmount, nextTick } from 'vue'
|
||
import { Box } from '@element-plus/icons-vue'
|
||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||
import type { UploadFile } from 'element-plus'
|
||
import { useUserStore } from '@/stores/modules/user'
|
||
|
||
defineOptions({
|
||
name: 'UpperTable'
|
||
})
|
||
|
||
const props = defineProps({
|
||
loading: {
|
||
type: Boolean,
|
||
default: false,
|
||
},
|
||
// 表格数据
|
||
data: {
|
||
type: Array as any,
|
||
default: () => [],
|
||
},
|
||
// 表格列配置
|
||
columns: {
|
||
type: Array as any,
|
||
default: () => [],
|
||
},
|
||
// 表格尺寸
|
||
tableSize: {
|
||
type: String,
|
||
default: 'small',
|
||
validator: (value: string) => ['large', 'default', 'small'].includes(value),
|
||
},
|
||
// 高亮当前行
|
||
highlightCurrentRow: {
|
||
type: Boolean,
|
||
default: true,
|
||
},
|
||
// 行唯一键
|
||
rowKey: {
|
||
type: [String, Function],
|
||
default: 'id',
|
||
},
|
||
// 当前选中行的key
|
||
currentRowKey: {
|
||
type: [String, Number],
|
||
default: '',
|
||
},
|
||
// 显示边框
|
||
border: {
|
||
type: Boolean,
|
||
default: true,
|
||
},
|
||
// 显示斑马纹
|
||
stripe: {
|
||
type: Boolean,
|
||
default: true,
|
||
},
|
||
// 显示表头
|
||
showHeader: {
|
||
type: Boolean,
|
||
default: true,
|
||
},
|
||
// 空数据文本
|
||
emptyText: {
|
||
type: String,
|
||
default: '暂无数据',
|
||
},
|
||
queryTime: {
|
||
type: Number,
|
||
default: 0,
|
||
},
|
||
// 列的宽度是否自撑开
|
||
fit: {
|
||
type: Boolean,
|
||
default: true,
|
||
},
|
||
// tooltip effect
|
||
tooltipEffect: {
|
||
type: String,
|
||
default: 'dark',
|
||
},
|
||
// 显示选择列
|
||
showSelection: {
|
||
type: Boolean,
|
||
default: false,
|
||
},
|
||
// 是否可勾选函数
|
||
selectable: {
|
||
type: Function,
|
||
default: () => true,
|
||
},
|
||
// 外部传入的默认选中数据
|
||
defaultSelected: {
|
||
type: Array as any,
|
||
default: () => [],
|
||
},
|
||
// 是否自动同步外部选中状态到表格
|
||
autoSyncSelection: {
|
||
type: Boolean,
|
||
default: true,
|
||
},
|
||
// 选择列宽度
|
||
selectionColumnWidth: {
|
||
type: [String, Number],
|
||
default: 55,
|
||
},
|
||
// 选择列是否固定
|
||
selectionColumnFixed: {
|
||
type: [String, Boolean],
|
||
default: true,
|
||
},
|
||
// 分页配置
|
||
pagination: {
|
||
type: Object,
|
||
default: () => ({
|
||
currentPage: 1,
|
||
pageSize: 20,
|
||
total: 0,
|
||
}),
|
||
},
|
||
// 是否显示分页
|
||
showPagination: {
|
||
type: Boolean,
|
||
default: true,
|
||
},
|
||
// 分页每页显示个数选择器的选项设置
|
||
pageSizes: {
|
||
type: Array as any,
|
||
default: () => [10, 20, 50, 100, 200, 500],
|
||
},
|
||
// 分页布局
|
||
paginationLayout: {
|
||
type: String,
|
||
default: 'total, sizes, prev, pager, next, jumper',
|
||
},
|
||
// 分页背景色
|
||
paginationBackground: {
|
||
type: Boolean,
|
||
default: true,
|
||
},
|
||
enableColumnConfig: {
|
||
type: Boolean,
|
||
default: false,
|
||
},
|
||
tableId: {
|
||
type: String,
|
||
default: '',
|
||
},
|
||
columnConfigSchemaVersion: {
|
||
type: Number,
|
||
default: 1,
|
||
},
|
||
rowClassName: {
|
||
type: [String, Function],
|
||
default: '',
|
||
},
|
||
virtualThreshold: {
|
||
type: Number,
|
||
default: 80,
|
||
},
|
||
virtualMaxVisibleRows: {
|
||
type: Number,
|
||
default: 0,
|
||
},
|
||
virtualBufferRows: {
|
||
type: Number,
|
||
default: 12,
|
||
},
|
||
})
|
||
|
||
const emit = defineEmits([
|
||
'current-change',
|
||
'selection-change',
|
||
'row-click',
|
||
'row-contextmenu',
|
||
'sort-change',
|
||
'page-size-change',
|
||
'page-change',
|
||
'refresh',
|
||
'select-all-change',
|
||
'row-selection-change',
|
||
])
|
||
|
||
// Refs
|
||
const tableRef = ref<any>(null)
|
||
const userStore = useUserStore()
|
||
|
||
type ColumnItem = {
|
||
prop?: string
|
||
label?: string
|
||
width?: number | string
|
||
fixed?: 'left' | 'right' | boolean
|
||
[key: string]: any
|
||
}
|
||
|
||
type ColumnConfigItem = {
|
||
prop: string
|
||
label?: string
|
||
visible: boolean
|
||
order: number
|
||
width?: number | string
|
||
fixed?: 'left' | 'right' | false
|
||
}
|
||
|
||
type TableColumnProfile = {
|
||
schemaVersion: number
|
||
tableId: string
|
||
userId: string
|
||
roleId: string | number
|
||
updatedAt: number
|
||
columns: ColumnConfigItem[]
|
||
}
|
||
|
||
// State
|
||
// const visibleData = ref<any[]>([]) // Removed
|
||
// const rowHeight = ref(41) // Removed
|
||
// const bufferSize = ref(8) // Removed
|
||
// const offset = ref(0) // Removed
|
||
// const containerHeight = ref(0) // Removed
|
||
const selectedRows = ref<any[]>([])
|
||
const selectedRowKeys = ref<Set<any>>(new Set())
|
||
// const rowKeyMap = ref<Map<any, any>>(new Map()) // Removed
|
||
// const lastScrollTop = ref(0) // Removed
|
||
// let scrollTimer: any = null // Removed
|
||
const checkboxUpdateKey = ref<number | null>(null)
|
||
const columnConfigDialogVisible = ref(false)
|
||
const editableColumnConfigs = ref<ColumnConfigItem[]>([])
|
||
const columnConfigMap = ref<Record<string, ColumnConfigItem>>({})
|
||
const draggingProp = ref<string>('')
|
||
const dragOverProp = ref<string>('')
|
||
const tableContainer = ref<HTMLElement | null>(null)
|
||
const bodyScrollEl = ref<HTMLElement | null>(null)
|
||
const columnConfigListRef = ref<HTMLElement | null>(null)
|
||
const virtualScrollTop = ref(0)
|
||
const virtualViewportHeight = ref(0)
|
||
const dragAutoScrollStep = ref(0)
|
||
let dragAutoScrollRaf: number | null = null
|
||
|
||
type VirtualSpacerRow = {
|
||
__virtualSpacer: true
|
||
__virtualSpacerType: 'top' | 'bottom'
|
||
__virtualSpacerHeight: number
|
||
}
|
||
|
||
const normalizedColumns = computed<ColumnItem[]>(() => {
|
||
return (props.columns || []).filter((column: ColumnItem) => !!column?.prop)
|
||
})
|
||
|
||
/** 列配置项与列定义合并后的 fixed 语义(用于字段设置与表头顺序) */
|
||
function effectiveColumnFixed(item: ColumnConfigItem, col: ColumnItem): 'left' | 'right' | undefined {
|
||
if (item.fixed === false) return undefined
|
||
const f = item.fixed ?? col.fixed
|
||
if (f === true || f === 'left') return 'left'
|
||
if (f === 'right') return 'right'
|
||
return undefined
|
||
}
|
||
|
||
function isColumnOrderLocked(item: ColumnConfigItem): boolean {
|
||
const col = normalizedColumns.value.find((c) => String(c.prop) === item.prop)
|
||
if (!col) return false
|
||
return effectiveColumnFixed(item, col) !== undefined
|
||
}
|
||
|
||
function normalizeFromParts(left: ColumnConfigItem[], mid: ColumnConfigItem[], right: ColumnConfigItem[]) {
|
||
let o = 0
|
||
return [...left, ...mid, ...right].map((c) => ({ ...c, order: o++ }))
|
||
}
|
||
|
||
/** 按列定义顺序拆成左固定 / 可排序 / 右固定;中间块按当前 order 排序 */
|
||
function partitionColumnConfigsTriplet(configs: ColumnConfigItem[]) {
|
||
const map = new Map(configs.map((c) => [c.prop, c]))
|
||
const left: ColumnConfigItem[] = []
|
||
const mid: ColumnConfigItem[] = []
|
||
const right: ColumnConfigItem[] = []
|
||
for (const col of normalizedColumns.value) {
|
||
const p = String(col.prop || '')
|
||
const item = map.get(p)
|
||
if (!item) continue
|
||
const z = effectiveColumnFixed(item, col)
|
||
if (z === 'left') left.push(item)
|
||
else if (z === 'right') right.push(item)
|
||
else mid.push(item)
|
||
}
|
||
mid.sort((a, b) => a.order - b.order)
|
||
return { left, mid, right }
|
||
}
|
||
|
||
function normalizeColumnConfigOrders(configs: ColumnConfigItem[]): ColumnConfigItem[] {
|
||
const { left, mid, right } = partitionColumnConfigsTriplet(configs)
|
||
return normalizeFromParts(left, mid, right)
|
||
}
|
||
|
||
const effectiveTableId = computed(() => props.tableId?.trim())
|
||
|
||
const columnConfigStorageKey = computed(() => {
|
||
if (!props.enableColumnConfig || !effectiveTableId.value) return ''
|
||
const userId = userStore.user?.username || userStore.user?.id || 'unknown'
|
||
const roleId = userStore.roleId || 'default'
|
||
return `upper_table_columns_${userId}_${roleId}_${effectiveTableId.value}`
|
||
})
|
||
|
||
const globalColumnConfigStoragePrefix = computed(() => {
|
||
const userId = userStore.user?.username || userStore.user?.id || 'unknown'
|
||
const roleId = userStore.roleId || 'default'
|
||
return `upper_table_columns_${userId}_${roleId}_`
|
||
})
|
||
|
||
const displayColumns = computed(() => {
|
||
if (!props.enableColumnConfig || !effectiveTableId.value) {
|
||
return normalizedColumns.value
|
||
}
|
||
const configMap = columnConfigMap.value
|
||
return normalizedColumns.value
|
||
.filter((column) => {
|
||
const prop = String(column.prop || '')
|
||
const cfg = configMap[prop]
|
||
return cfg ? cfg.visible !== false : true
|
||
})
|
||
.sort((a, b) => {
|
||
const aOrder = configMap[String(a.prop || '')]?.order ?? Number.MAX_SAFE_INTEGER
|
||
const bOrder = configMap[String(b.prop || '')]?.order ?? Number.MAX_SAFE_INTEGER
|
||
return aOrder - bOrder
|
||
})
|
||
.map((column) => {
|
||
const cfg = configMap[String(column.prop || '')]
|
||
if (!cfg) return column
|
||
return {
|
||
...column,
|
||
width: cfg.width ?? column.width,
|
||
fixed: cfg.fixed === false ? undefined : (cfg.fixed ?? column.fixed)
|
||
}
|
||
})
|
||
})
|
||
|
||
/** 字段设置弹窗分组:固定列仅显示/隐藏,中间块可拖动排序 */
|
||
const columnConfigDialogSections = computed(() => {
|
||
const { left, mid, right } = partitionColumnConfigsTriplet(editableColumnConfigs.value)
|
||
const sections: { key: string; title: string; items: ColumnConfigItem[] }[] = []
|
||
if (left.length) {
|
||
sections.push({
|
||
key: 'fixed-left',
|
||
title: '左侧固定列(仅显示/隐藏,顺序与列定义一致)',
|
||
items: left
|
||
})
|
||
}
|
||
if (mid.length) {
|
||
sections.push({
|
||
key: 'scroll',
|
||
title: '可调整顺序(拖动或上移/下移)',
|
||
items: mid
|
||
})
|
||
}
|
||
if (right.length) {
|
||
sections.push({
|
||
key: 'fixed-right',
|
||
title: '右侧固定列(仅显示/隐藏,顺序与列定义一致)',
|
||
items: right
|
||
})
|
||
}
|
||
return sections
|
||
})
|
||
|
||
// Computed
|
||
const virtualRowHeight = computed(() => {
|
||
if (props.tableSize === 'large') return 49
|
||
if (props.tableSize === 'default') return 41
|
||
return 33
|
||
})
|
||
|
||
const shouldUseVirtual = computed(() => {
|
||
return props.data.length >= props.virtualThreshold
|
||
})
|
||
|
||
const virtualVisibleCount = computed(() => {
|
||
const bufferRows = props.virtualBufferRows
|
||
const viewportCount = virtualViewportHeight.value
|
||
? Math.ceil(virtualViewportHeight.value / virtualRowHeight.value) + bufferRows * 2
|
||
: (props.pagination.pageSize || 20)
|
||
if (props.virtualMaxVisibleRows > 0) {
|
||
return Math.min(props.virtualMaxVisibleRows, viewportCount)
|
||
}
|
||
return viewportCount
|
||
})
|
||
|
||
const virtualStartIndex = computed(() => {
|
||
if (!shouldUseVirtual.value) return 0
|
||
return Math.max(0, Math.floor(virtualScrollTop.value / virtualRowHeight.value) - props.virtualBufferRows)
|
||
})
|
||
|
||
const virtualEndIndex = computed(() => {
|
||
if (!shouldUseVirtual.value) return props.data.length
|
||
return Math.min(props.data.length, virtualStartIndex.value + virtualVisibleCount.value)
|
||
})
|
||
|
||
const virtualTopPadding = computed(() => {
|
||
if (!shouldUseVirtual.value) return 0
|
||
return virtualStartIndex.value * virtualRowHeight.value
|
||
})
|
||
|
||
const virtualBottomPadding = computed(() => {
|
||
if (!shouldUseVirtual.value) return 0
|
||
return Math.max(0, (props.data.length - virtualEndIndex.value) * virtualRowHeight.value)
|
||
})
|
||
|
||
const virtualVisibleRows = computed(() => {
|
||
if (!shouldUseVirtual.value) return props.data
|
||
return props.data.slice(virtualStartIndex.value, virtualEndIndex.value)
|
||
})
|
||
|
||
const tableRenderData = computed(() => {
|
||
if (!shouldUseVirtual.value) return props.data
|
||
const rows: any[] = []
|
||
if (virtualTopPadding.value > 0) {
|
||
rows.push(createVirtualSpacerRow('top', virtualTopPadding.value))
|
||
}
|
||
rows.push(...virtualVisibleRows.value)
|
||
if (virtualBottomPadding.value > 0) {
|
||
rows.push(createVirtualSpacerRow('bottom', virtualBottomPadding.value))
|
||
}
|
||
return rows
|
||
})
|
||
|
||
const total = computed(() => {
|
||
return props.pagination.total || props.data.length
|
||
})
|
||
|
||
const selectableRows = computed(() => {
|
||
return props.data.filter((row: any, index: number) => props.selectable(row, index))
|
||
})
|
||
|
||
const isAllSelected = computed(() => {
|
||
if (selectableRows.value.length === 0) return false
|
||
return selectableRows.value.every((row: any) =>
|
||
selectedRowKeys.value.has(getRowKey(row))
|
||
)
|
||
})
|
||
|
||
const isAllSelectedInView = computed({
|
||
get() {
|
||
return props.data.length > 0 && props.data.length === selectedRows.value.length
|
||
},
|
||
set(val) {
|
||
toggleAllSelection()
|
||
}
|
||
})
|
||
|
||
const isIndeterminate = computed(() => {
|
||
return props.data.length > selectedRows.value.length && selectedRows.value.length > 0
|
||
})
|
||
|
||
const selectedCount = computed(() => {
|
||
return selectedRows.value.length
|
||
})
|
||
|
||
// Watchers
|
||
watch(() => props.data, () => {
|
||
clearSelection()
|
||
syncVirtualViewport()
|
||
}, { deep: true })
|
||
|
||
watch(
|
||
[() => props.columns, () => props.enableColumnConfig, () => props.tableId, () => userStore.roleId, () => userStore.user],
|
||
() => {
|
||
rebuildColumnConfig()
|
||
},
|
||
{ immediate: true, deep: true }
|
||
)
|
||
|
||
watch(() => props.defaultSelected, (newVal) => {
|
||
if (props.autoSyncSelection) {
|
||
setSelectionFromExternal(newVal)
|
||
}
|
||
}, { deep: true })
|
||
|
||
watch(selectedRows, (newVal) => {
|
||
emit('selection-change', [...newVal])
|
||
}, { deep: true })
|
||
|
||
// Lifecycle
|
||
onMounted(() => {
|
||
if (props.defaultSelected.length > 0) {
|
||
setSelectionFromExternal(props.defaultSelected)
|
||
}
|
||
bindBodyScroll()
|
||
})
|
||
|
||
onBeforeUnmount(() => {
|
||
unbindBodyScroll()
|
||
stopColumnConfigAutoScroll()
|
||
})
|
||
|
||
// Methods
|
||
function getDefaultColumnConfigs() {
|
||
return normalizedColumns.value.map((column, index) => ({
|
||
prop: String(column.prop),
|
||
label: column.label,
|
||
visible: true,
|
||
order: index,
|
||
width: column.width,
|
||
fixed: column.fixed === true ? 'left' : (column.fixed as 'left' | 'right' | undefined)
|
||
}))
|
||
}
|
||
|
||
function applyColumnConfigMap(configs: ColumnConfigItem[]) {
|
||
const map: Record<string, ColumnConfigItem> = {}
|
||
configs.forEach((item) => {
|
||
map[item.prop] = item
|
||
})
|
||
columnConfigMap.value = map
|
||
editableColumnConfigs.value = [...configs].sort((a, b) => a.order - b.order)
|
||
}
|
||
|
||
function saveColumnConfig(configs: ColumnConfigItem[]) {
|
||
if (!columnConfigStorageKey.value) return
|
||
const userId = String(userStore.user?.username || userStore.user?.id || 'unknown')
|
||
const roleId = userStore.roleId || 'default'
|
||
const payload: TableColumnProfile = {
|
||
schemaVersion: props.columnConfigSchemaVersion,
|
||
tableId: effectiveTableId.value,
|
||
userId,
|
||
roleId,
|
||
updatedAt: Date.now(),
|
||
columns: configs
|
||
}
|
||
localStorage.setItem(columnConfigStorageKey.value, JSON.stringify(payload))
|
||
}
|
||
|
||
function buildMergedColumnConfigs(raw?: Partial<ColumnConfigItem>[]) {
|
||
const defaults = getDefaultColumnConfigs()
|
||
const defaultMap = new Map(defaults.map((item) => [item.prop, item]))
|
||
const merged: ColumnConfigItem[] = []
|
||
const used = new Set<string>()
|
||
|
||
;(raw || []).forEach((item, index) => {
|
||
if (!item?.prop) return
|
||
const prop = String(item.prop)
|
||
const base = defaultMap.get(prop)
|
||
if (!base) return
|
||
used.add(prop)
|
||
merged.push({
|
||
...base,
|
||
visible: item.visible ?? base.visible,
|
||
order: Number.isFinite(item.order as number) ? Number(item.order) : index,
|
||
width: item.width ?? base.width,
|
||
fixed: item.fixed ?? base.fixed
|
||
})
|
||
})
|
||
|
||
defaults.forEach((item) => {
|
||
if (!used.has(item.prop)) {
|
||
merged.push({ ...item, order: merged.length })
|
||
}
|
||
})
|
||
|
||
merged.sort((a, b) => a.order - b.order)
|
||
return normalizeColumnConfigOrders(merged)
|
||
}
|
||
|
||
function readStoredColumnConfigs() {
|
||
if (!columnConfigStorageKey.value) return null
|
||
const raw = localStorage.getItem(columnConfigStorageKey.value)
|
||
if (!raw) return null
|
||
try {
|
||
const parsed = JSON.parse(raw) as TableColumnProfile
|
||
if (!parsed || !Array.isArray(parsed.columns)) return null
|
||
const storedVersion = parsed.schemaVersion ?? 1
|
||
if (storedVersion !== props.columnConfigSchemaVersion) return null
|
||
return parsed.columns
|
||
} catch {
|
||
return null
|
||
}
|
||
}
|
||
|
||
function rebuildColumnConfig() {
|
||
const merged = buildMergedColumnConfigs(readStoredColumnConfigs() || undefined)
|
||
applyColumnConfigMap(merged)
|
||
if (props.enableColumnConfig && effectiveTableId.value) {
|
||
saveColumnConfig(merged)
|
||
}
|
||
}
|
||
|
||
function getDefaultCellTextClass(prop: string | undefined, value: unknown) {
|
||
if (prop === 'order_flag' && value !== undefined && value !== null && String(value).trim() !== '') {
|
||
return 'order-flag-text order-flag-copyable'
|
||
}
|
||
return ''
|
||
}
|
||
|
||
function getOrderFlagFullText(value: unknown) {
|
||
if (value == null) return ''
|
||
return String(value).trim()
|
||
}
|
||
|
||
function getOrderFlagCellText(value: unknown) {
|
||
const text = getOrderFlagFullText(value)
|
||
if (!text) return '—'
|
||
const max = 48
|
||
return text.length > max ? `${text.slice(0, max)}…` : text
|
||
}
|
||
|
||
async function copyOrderFlagText(value: unknown) {
|
||
const text = getOrderFlagFullText(value)
|
||
if (!text) {
|
||
ElMessage.warning('当前行无订单标记可复制')
|
||
return
|
||
}
|
||
try {
|
||
if (navigator.clipboard?.writeText) {
|
||
await navigator.clipboard.writeText(text)
|
||
} else {
|
||
throw new Error('no clipboard api')
|
||
}
|
||
ElMessage.success('订单标记已复制到剪贴板')
|
||
} catch {
|
||
try {
|
||
const textarea = document.createElement('textarea')
|
||
textarea.value = text
|
||
textarea.setAttribute('readonly', 'readonly')
|
||
textarea.style.position = 'fixed'
|
||
textarea.style.left = '-9999px'
|
||
document.body.appendChild(textarea)
|
||
textarea.select()
|
||
document.execCommand('copy')
|
||
document.body.removeChild(textarea)
|
||
ElMessage.success('订单标记已复制到剪贴板')
|
||
} catch {
|
||
ElMessage.error('复制失败,请手动复制')
|
||
}
|
||
}
|
||
}
|
||
|
||
function persistEditableConfigs() {
|
||
const normalized = normalizeColumnConfigOrders([...editableColumnConfigs.value])
|
||
applyColumnConfigMap(normalized)
|
||
saveColumnConfig(normalized)
|
||
}
|
||
|
||
function openColumnConfig() {
|
||
editableColumnConfigs.value = normalizeColumnConfigOrders(Object.values(columnConfigMap.value))
|
||
columnConfigDialogVisible.value = true
|
||
}
|
||
|
||
function onToggleColumnVisible(prop: string, visible: boolean) {
|
||
const next = editableColumnConfigs.value.map((item) => {
|
||
if (item.prop !== prop) return item
|
||
return { ...item, visible }
|
||
})
|
||
editableColumnConfigs.value = next
|
||
persistEditableConfigs()
|
||
}
|
||
|
||
function moveColumn(prop: string, direction: 'up' | 'down') {
|
||
const cfg = editableColumnConfigs.value.find((c) => c.prop === prop)
|
||
if (!cfg || isColumnOrderLocked(cfg)) return
|
||
|
||
const { left, mid, right } = partitionColumnConfigsTriplet(editableColumnConfigs.value)
|
||
const i = mid.findIndex((c) => c.prop === prop)
|
||
if (i === -1) return
|
||
const j = direction === 'up' ? i - 1 : i + 1
|
||
if (j < 0 || j >= mid.length) return
|
||
const tmp = mid[i]!
|
||
mid[i] = mid[j]!
|
||
mid[j] = tmp
|
||
|
||
const next = normalizeFromParts(left, mid, right)
|
||
applyColumnConfigMap(next)
|
||
saveColumnConfig(next)
|
||
}
|
||
|
||
function onColumnDragStart(e: DragEvent, item: ColumnConfigItem) {
|
||
if (isColumnOrderLocked(item)) {
|
||
e.preventDefault()
|
||
return
|
||
}
|
||
draggingProp.value = item.prop
|
||
}
|
||
|
||
function runColumnConfigAutoScroll() {
|
||
const listEl = columnConfigListRef.value
|
||
if (!listEl || dragAutoScrollStep.value === 0) {
|
||
dragAutoScrollRaf = null
|
||
return
|
||
}
|
||
listEl.scrollTop += dragAutoScrollStep.value
|
||
dragAutoScrollRaf = requestAnimationFrame(runColumnConfigAutoScroll)
|
||
}
|
||
|
||
function startColumnConfigAutoScroll(step: number) {
|
||
dragAutoScrollStep.value = step
|
||
if (dragAutoScrollStep.value === 0) {
|
||
stopColumnConfigAutoScroll()
|
||
return
|
||
}
|
||
if (dragAutoScrollRaf === null) {
|
||
dragAutoScrollRaf = requestAnimationFrame(runColumnConfigAutoScroll)
|
||
}
|
||
}
|
||
|
||
function stopColumnConfigAutoScroll() {
|
||
dragAutoScrollStep.value = 0
|
||
if (dragAutoScrollRaf !== null) {
|
||
cancelAnimationFrame(dragAutoScrollRaf)
|
||
dragAutoScrollRaf = null
|
||
}
|
||
}
|
||
|
||
function onColumnDragOver(e: DragEvent, item: ColumnConfigItem) {
|
||
if (!draggingProp.value) return
|
||
if (draggingProp.value === item.prop) return
|
||
const sourceCfg = editableColumnConfigs.value.find((c) => c.prop === draggingProp.value)
|
||
if (!sourceCfg || isColumnOrderLocked(sourceCfg) || isColumnOrderLocked(item)) return
|
||
dragOverProp.value = item.prop
|
||
|
||
const listEl = columnConfigListRef.value
|
||
if (!listEl) return
|
||
|
||
const rect = listEl.getBoundingClientRect()
|
||
const threshold = 56
|
||
const maxStep = 8
|
||
let step = 0
|
||
|
||
if (e.clientY < rect.top + threshold) {
|
||
const ratio = (rect.top + threshold - e.clientY) / threshold
|
||
step = -Math.max(2, Math.min(maxStep, Math.round(ratio * maxStep)))
|
||
} else if (e.clientY > rect.bottom - threshold) {
|
||
const ratio = (e.clientY - (rect.bottom - threshold)) / threshold
|
||
step = Math.max(2, Math.min(maxStep, Math.round(ratio * maxStep)))
|
||
}
|
||
|
||
startColumnConfigAutoScroll(step)
|
||
}
|
||
|
||
function onColumnDrop(target: ColumnConfigItem) {
|
||
const sourceProp = draggingProp.value
|
||
if (!sourceProp || sourceProp === target.prop) {
|
||
onColumnDragEnd()
|
||
return
|
||
}
|
||
|
||
const sourceCfg = editableColumnConfigs.value.find((c) => c.prop === sourceProp)
|
||
if (!sourceCfg || isColumnOrderLocked(sourceCfg) || isColumnOrderLocked(target)) {
|
||
onColumnDragEnd()
|
||
return
|
||
}
|
||
|
||
const { left, mid, right } = partitionColumnConfigsTriplet(editableColumnConfigs.value)
|
||
const sourceIndex = mid.findIndex((item) => item.prop === sourceProp)
|
||
const targetIndex = mid.findIndex((item) => item.prop === target.prop)
|
||
if (sourceIndex === -1 || targetIndex === -1) {
|
||
onColumnDragEnd()
|
||
return
|
||
}
|
||
|
||
const sourceItem = mid[sourceIndex]
|
||
if (!sourceItem) {
|
||
onColumnDragEnd()
|
||
return
|
||
}
|
||
|
||
mid.splice(sourceIndex, 1)
|
||
mid.splice(targetIndex, 0, sourceItem)
|
||
|
||
const next = normalizeFromParts(left, mid, right)
|
||
applyColumnConfigMap(next)
|
||
saveColumnConfig(next)
|
||
onColumnDragEnd()
|
||
}
|
||
|
||
function onColumnDragEnd() {
|
||
draggingProp.value = ''
|
||
dragOverProp.value = ''
|
||
stopColumnConfigAutoScroll()
|
||
}
|
||
|
||
function resetColumnConfig() {
|
||
const defaults = normalizeColumnConfigOrders(getDefaultColumnConfigs())
|
||
applyColumnConfigMap(defaults)
|
||
saveColumnConfig(defaults)
|
||
ElMessage.success('已恢复默认字段配置')
|
||
}
|
||
|
||
function exportGlobalColumnConfig() {
|
||
const userId = String(userStore.user?.username || userStore.user?.id || 'unknown')
|
||
const roleId = userStore.roleId || 'default'
|
||
const tableProfiles: TableColumnProfile[] = []
|
||
const prefix = globalColumnConfigStoragePrefix.value
|
||
Object.keys(localStorage).forEach((key) => {
|
||
if (!key.startsWith(prefix)) return
|
||
try {
|
||
const parsed = JSON.parse(localStorage.getItem(key) || '{}') as TableColumnProfile
|
||
if (parsed && parsed.tableId && Array.isArray(parsed.columns)) {
|
||
tableProfiles.push(parsed)
|
||
}
|
||
} catch {
|
||
// ignore invalid profile
|
||
}
|
||
})
|
||
const payload = {
|
||
format: 'upper-table-global-columns',
|
||
schemaVersion: props.columnConfigSchemaVersion,
|
||
userId,
|
||
roleId,
|
||
updatedAt: Date.now(),
|
||
tables: tableProfiles
|
||
}
|
||
const blob = new Blob([JSON.stringify(payload, null, 2)], { type: 'application/json;charset=utf-8' })
|
||
const url = URL.createObjectURL(blob)
|
||
const link = document.createElement('a')
|
||
link.href = url
|
||
link.download = `upper-table-global-columns-config.json`
|
||
link.click()
|
||
URL.revokeObjectURL(url)
|
||
}
|
||
|
||
function handleImportColumnConfig(file: UploadFile) {
|
||
if (!file.raw) return
|
||
const reader = new FileReader()
|
||
reader.onload = () => {
|
||
try {
|
||
const parsed = JSON.parse(String(reader.result || '{}')) as {
|
||
tables?: TableColumnProfile[]
|
||
tableId?: string
|
||
columns?: ColumnConfigItem[]
|
||
}
|
||
if (!parsed) {
|
||
ElMessage.error('配置文件格式不正确')
|
||
return
|
||
}
|
||
|
||
const importProfiles: TableColumnProfile[] = []
|
||
if (Array.isArray(parsed.tables)) {
|
||
importProfiles.push(...parsed.tables)
|
||
} else if (parsed.tableId && Array.isArray(parsed.columns)) {
|
||
importProfiles.push({
|
||
schemaVersion: props.columnConfigSchemaVersion,
|
||
tableId: parsed.tableId,
|
||
userId: String(userStore.user?.username || userStore.user?.id || 'unknown'),
|
||
roleId: userStore.roleId || 'default',
|
||
updatedAt: Date.now(),
|
||
columns: parsed.columns
|
||
})
|
||
}
|
||
|
||
if (importProfiles.length === 0) {
|
||
ElMessage.error('未找到可导入的全局配置')
|
||
return
|
||
}
|
||
|
||
const prefix = globalColumnConfigStoragePrefix.value
|
||
let importedCount = 0
|
||
importProfiles.forEach((profile) => {
|
||
if (!profile?.tableId || !Array.isArray(profile.columns)) return
|
||
const key = `${prefix}${profile.tableId}`
|
||
const payload: TableColumnProfile = {
|
||
schemaVersion: profile.schemaVersion ?? props.columnConfigSchemaVersion,
|
||
tableId: profile.tableId,
|
||
userId: String(userStore.user?.username || userStore.user?.id || 'unknown'),
|
||
roleId: userStore.roleId || 'default',
|
||
updatedAt: Date.now(),
|
||
columns: profile.columns
|
||
}
|
||
localStorage.setItem(key, JSON.stringify(payload))
|
||
importedCount += 1
|
||
})
|
||
|
||
rebuildColumnConfig()
|
||
ElMessage.success(`全局配置导入成功,已更新 ${importedCount} 个表`)
|
||
} catch {
|
||
ElMessage.error('配置文件解析失败')
|
||
}
|
||
}
|
||
reader.readAsText(file.raw)
|
||
}
|
||
|
||
async function handleRepairColumnConfig() {
|
||
try {
|
||
await ElMessageBox.confirm(
|
||
'故障修复会清除当前电脑中此账号的全部字段配置,并恢复各页面默认字段。是否继续?',
|
||
'确认故障修复',
|
||
{
|
||
type: 'warning',
|
||
confirmButtonText: '确认清除',
|
||
cancelButtonText: '取消'
|
||
}
|
||
)
|
||
|
||
await ElMessageBox.confirm(
|
||
'请再次确认:该操作不可撤销,确定清除所有字段配置吗?',
|
||
'二次确认',
|
||
{
|
||
type: 'warning',
|
||
confirmButtonText: '确定',
|
||
cancelButtonText: '返回'
|
||
}
|
||
)
|
||
|
||
const prefix = globalColumnConfigStoragePrefix.value
|
||
const removeKeys: string[] = []
|
||
Object.keys(localStorage).forEach((key) => {
|
||
if (key.startsWith(prefix)) {
|
||
removeKeys.push(key)
|
||
}
|
||
})
|
||
removeKeys.forEach((key) => localStorage.removeItem(key))
|
||
|
||
rebuildColumnConfig()
|
||
ElMessage.success(`故障修复完成,已清除 ${removeKeys.length} 个字段配置`)
|
||
} catch {
|
||
// user cancelled
|
||
}
|
||
}
|
||
|
||
function getRowKey(row: any) {
|
||
if (isVirtualSpacerRow(row)) {
|
||
return `virtual-${row.__virtualSpacerType}`
|
||
}
|
||
if (typeof props.rowKey === 'function') {
|
||
return props.rowKey(row)
|
||
}
|
||
return row[props.rowKey]
|
||
}
|
||
|
||
function createVirtualSpacerRow(type: 'top' | 'bottom', height: number): VirtualSpacerRow {
|
||
return {
|
||
__virtualSpacer: true,
|
||
__virtualSpacerType: type,
|
||
__virtualSpacerHeight: height
|
||
}
|
||
}
|
||
|
||
function isVirtualSpacerRow(row: any): row is VirtualSpacerRow {
|
||
return !!row && row.__virtualSpacer === true
|
||
}
|
||
|
||
function getRowClassName({ row }: { row: any }) {
|
||
if (isVirtualSpacerRow(row)) return 'virtual-spacer-row'
|
||
if (typeof props.rowClassName === 'function') {
|
||
return props.rowClassName({ row }) || ''
|
||
}
|
||
if (typeof props.rowClassName === 'string') return props.rowClassName
|
||
return ''
|
||
}
|
||
|
||
function getRowStyle({ row }: { row: any }) {
|
||
if (!isVirtualSpacerRow(row)) return {}
|
||
return {
|
||
height: `${row.__virtualSpacerHeight}px`
|
||
}
|
||
}
|
||
|
||
function handleBodyScroll() {
|
||
if (!bodyScrollEl.value) return
|
||
virtualScrollTop.value = bodyScrollEl.value.scrollTop || 0
|
||
virtualViewportHeight.value = bodyScrollEl.value.clientHeight || 0
|
||
}
|
||
|
||
function unbindBodyScroll() {
|
||
if (!bodyScrollEl.value) return
|
||
bodyScrollEl.value.removeEventListener('scroll', handleBodyScroll)
|
||
}
|
||
|
||
function bindBodyScroll() {
|
||
nextTick(() => {
|
||
unbindBodyScroll()
|
||
if (!tableRef.value?.$el) return
|
||
const tableEl = tableRef.value.$el as HTMLElement
|
||
const scrollWrap = tableEl.querySelector('.el-scrollbar__wrap') as HTMLElement | null
|
||
bodyScrollEl.value = scrollWrap
|
||
if (!bodyScrollEl.value) return
|
||
bodyScrollEl.value.addEventListener('scroll', handleBodyScroll, { passive: true })
|
||
handleBodyScroll()
|
||
})
|
||
}
|
||
|
||
function syncVirtualViewport() {
|
||
nextTick(() => {
|
||
if (!shouldUseVirtual.value) {
|
||
virtualScrollTop.value = 0
|
||
}
|
||
bindBodyScroll()
|
||
})
|
||
}
|
||
|
||
function isRowSelected(row: any) {
|
||
const rowKey = getRowKey(row)
|
||
return selectedRowKeys.value.has(rowKey)
|
||
}
|
||
|
||
function toggleRowSelection(row: any, selected: boolean | null = null) {
|
||
if (isVirtualSpacerRow(row)) return
|
||
const rowKey = getRowKey(row)
|
||
const currentlySelected = selectedRowKeys.value.has(rowKey)
|
||
const shouldSelect = selected !== null ? selected : !currentlySelected
|
||
|
||
if (shouldSelect && !currentlySelected) {
|
||
selectedRowKeys.value.add(rowKey)
|
||
selectedRows.value.push(row)
|
||
|
||
emit('row-selection-change', {
|
||
row,
|
||
rowKey,
|
||
selected: true,
|
||
selectedRows: [...selectedRows.value],
|
||
selectedKeys: [...selectedRowKeys.value]
|
||
})
|
||
} else if (!shouldSelect && currentlySelected) {
|
||
selectedRowKeys.value.delete(rowKey)
|
||
const index = selectedRows.value.findIndex((r: any) => getRowKey(r) === rowKey)
|
||
if (index !== -1) {
|
||
selectedRows.value.splice(index, 1)
|
||
}
|
||
|
||
emit('row-selection-change', {
|
||
row,
|
||
rowKey,
|
||
selected: false,
|
||
selectedRows: [...selectedRows.value],
|
||
selectedKeys: [...selectedRowKeys.value]
|
||
})
|
||
}
|
||
|
||
emit('select-all-change', {
|
||
isSelectAll: isAllSelected.value,
|
||
isAllSelectedInView: isAllSelectedInView.value,
|
||
selectedRows: [...selectedRows.value],
|
||
selectedKeys: [...selectedRowKeys.value],
|
||
totalSelectableRows: selectableRows.value.length
|
||
})
|
||
|
||
setTimeout(() => {
|
||
checkboxUpdateKey.value = Date.now()
|
||
}, 10)
|
||
}
|
||
|
||
function toggleAllSelection() {
|
||
if (props.data.length === selectedRows.value.length) {
|
||
clearSelection()
|
||
} else {
|
||
const allSelectableRows = selectableRows.value
|
||
selectedRows.value = [...allSelectableRows]
|
||
selectedRowKeys.value.clear()
|
||
allSelectableRows.forEach((row: any) => {
|
||
selectedRowKeys.value.add(getRowKey(row))
|
||
})
|
||
|
||
emit('select-all-change', {
|
||
isSelectAll: true,
|
||
isAllSelectedInView: isAllSelectedInView.value,
|
||
selectedRows: [...selectedRows.value],
|
||
selectedKeys: [...selectedRowKeys.value],
|
||
totalSelectableRows: allSelectableRows.length
|
||
})
|
||
}
|
||
setTimeout(() => {
|
||
checkboxUpdateKey.value = Date.now()
|
||
}, 10)
|
||
}
|
||
|
||
function clearSelection() {
|
||
selectedRows.value = []
|
||
selectedRowKeys.value.clear()
|
||
|
||
emit('selection-change', [])
|
||
emit('select-all-change', {
|
||
isSelectAll: false,
|
||
isAllSelectedInView: false,
|
||
selectedRows: [],
|
||
selectedKeys: [],
|
||
totalSelectableRows: selectableRows.value.length
|
||
})
|
||
}
|
||
|
||
function getSelection() {
|
||
return [...selectedRows.value]
|
||
}
|
||
|
||
function getSelectionKeys() {
|
||
return [...selectedRowKeys.value]
|
||
}
|
||
|
||
function isSelected(row: any) {
|
||
const rowKey = getRowKey(row)
|
||
return selectedRowKeys.value.has(rowKey)
|
||
}
|
||
|
||
function setSelectionFromExternal(rows: any[]) {
|
||
// Logic to sync external selection
|
||
// This was missing in the original code snippet provided in Read tool for methods section
|
||
// Assuming it sets selectedRows and selectedRowKeys
|
||
selectedRows.value = [...rows]
|
||
selectedRowKeys.value.clear()
|
||
rows.forEach(row => {
|
||
selectedRowKeys.value.add(getRowKey(row))
|
||
})
|
||
}
|
||
|
||
function handleCurrentChange(currentRow: any, oldCurrentRow: any) {
|
||
if (isVirtualSpacerRow(currentRow)) return
|
||
emit('current-change', currentRow, oldCurrentRow)
|
||
}
|
||
|
||
function handleRowClick(row: any, column: any, event: any) {
|
||
if (isVirtualSpacerRow(row)) return
|
||
const target = event.target
|
||
const isCheckbox = target.classList.contains('el-checkbox') ||
|
||
target.closest('.el-checkbox') ||
|
||
target.classList.contains('custom-selection-cell') ||
|
||
target.closest('.custom-selection-cell')
|
||
|
||
if (!isCheckbox) {
|
||
emit('row-click', row, column, event)
|
||
}
|
||
}
|
||
|
||
function handleRowContextMenu(row: any, column: any, event: any) {
|
||
if (isVirtualSpacerRow(row)) return
|
||
emit('row-contextmenu', row, column, event)
|
||
}
|
||
|
||
function handleSortChange({ column, prop, order }: any) {
|
||
emit('sort-change', { column, prop, order })
|
||
}
|
||
|
||
function handlePageSizeChange(size: number) {
|
||
emit('page-size-change', size)
|
||
}
|
||
|
||
function handlePageChange(page: number) {
|
||
emit('page-change', page)
|
||
}
|
||
|
||
function handleRefresh() {
|
||
emit('refresh')
|
||
}
|
||
|
||
function getTableRef() {
|
||
return tableRef.value
|
||
}
|
||
|
||
function setCurrentRow(row: any) {
|
||
if (tableRef.value) {
|
||
tableRef.value.setCurrentRow(row)
|
||
}
|
||
}
|
||
|
||
function clearSort() {
|
||
if (tableRef.value) {
|
||
tableRef.value.clearSort()
|
||
}
|
||
}
|
||
|
||
function clearFilter(columnKey: string) {
|
||
if (tableRef.value) {
|
||
tableRef.value.clearFilter(columnKey)
|
||
}
|
||
}
|
||
|
||
function getSummaries(param: { columns: any, data: any }) {
|
||
const { columns, data } = param
|
||
const sums: string[] = []
|
||
columns.forEach((column: any, index: number) => {
|
||
if (index === 0) {
|
||
sums[index] = '总计'
|
||
return
|
||
}
|
||
const values = data.map((item: any) => Number(item[column.property]))
|
||
if (!values.every((value: number) => isNaN(value))) {
|
||
sums[index] = values.reduce((prev: number, curr: number) => {
|
||
const value = Number(curr)
|
||
if (!isNaN(value)) {
|
||
return prev + curr
|
||
} else {
|
||
return prev
|
||
}
|
||
}, 0)
|
||
sums[index] += ' 元'
|
||
} else {
|
||
sums[index] = 'N/A'
|
||
}
|
||
})
|
||
|
||
return sums
|
||
}
|
||
|
||
// Expose methods
|
||
defineExpose({
|
||
getSelection,
|
||
getSelectionKeys,
|
||
toggleRowSelection,
|
||
toggleAllSelection,
|
||
openColumnConfig,
|
||
clearSelection,
|
||
getTableRef,
|
||
setCurrentRow,
|
||
clearSort,
|
||
clearFilter,
|
||
getSummaries
|
||
})
|
||
|
||
watch(
|
||
() => [props.tableSize, props.showHeader, props.showPagination, props.loading],
|
||
() => {
|
||
syncVirtualViewport()
|
||
},
|
||
{ deep: true }
|
||
)
|
||
</script>
|
||
|
||
<style scoped>
|
||
/* 表头居中 */
|
||
:deep(.el-table__header-wrapper th .cell) {
|
||
text-align: center;
|
||
}
|
||
|
||
/* 基础样式 */
|
||
.upper-table-container {
|
||
display: flex;
|
||
flex-direction: column;
|
||
background: #fff;
|
||
border-radius: 4px;
|
||
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
|
||
overflow: hidden;
|
||
position: relative;
|
||
/* 支持弹性高度:允许在 flex 父容器中自动伸缩 */
|
||
flex: 1 1 auto;
|
||
min-height: 0;
|
||
height: 100%;
|
||
}
|
||
|
||
.table-container {
|
||
/* 移除固定高度,弹性填满 upper-table-container 剩余空间 */
|
||
flex: 1 1 auto;
|
||
min-height: 0;
|
||
overflow: auto;
|
||
z-index: 9;
|
||
}
|
||
|
||
.pagination-container {
|
||
padding: 5px 10px;
|
||
border-top: 1px solid #e8e8e8;
|
||
background: #fff;
|
||
display: flex;
|
||
flex-direction: row;
|
||
justify-content: space-between;
|
||
align-items: center;
|
||
flex-wrap: wrap;
|
||
flex-shrink: 0;
|
||
}
|
||
|
||
.pagination-info {
|
||
font-size: 12px;
|
||
color: #606266;
|
||
white-space: nowrap;
|
||
}
|
||
|
||
/* Ensure pagination elements don't disappear on small screens/containers */
|
||
.pagination-container :deep(.el-pagination__sizes),
|
||
.pagination-container :deep(.el-pagination__jump),
|
||
.pagination-container :deep(.el-pagination__total) {
|
||
display: inline-flex !important;
|
||
margin-right: 8px;
|
||
}
|
||
|
||
.pagination-container :deep(.el-pagination) {
|
||
flex-wrap: wrap;
|
||
justify-content: flex-end;
|
||
--el-pagination-button-width: 28px;
|
||
--el-pagination-button-height: 28px;
|
||
}
|
||
|
||
.pagination-container :deep(.el-select--small) {
|
||
width: 80px;
|
||
}
|
||
|
||
.pagination-container :deep(.el-input__wrapper) {
|
||
padding: 0 4px;
|
||
}
|
||
|
||
.empty-table {
|
||
display: flex;
|
||
flex-direction: column;
|
||
align-items: center;
|
||
justify-content: center;
|
||
height: 200px;
|
||
color: #999;
|
||
}
|
||
|
||
.empty-table p {
|
||
margin: 0;
|
||
font-size: 14px;
|
||
margin-top: 10px;
|
||
}
|
||
|
||
/* 自定义选择列样式 */
|
||
.custom-selection-header {
|
||
display: flex;
|
||
align-items: center;
|
||
justify-content: center;
|
||
height: 100%;
|
||
cursor: pointer;
|
||
}
|
||
|
||
.custom-selection-cell {
|
||
display: flex;
|
||
align-items: center;
|
||
justify-content: center;
|
||
height: 100%;
|
||
cursor: pointer;
|
||
}
|
||
|
||
/* 防止复选框点击事件冒泡 */
|
||
.custom-selection-header :deep(.el-checkbox),
|
||
.custom-selection-cell :deep(.el-checkbox) {
|
||
margin: 0;
|
||
pointer-events: none; /* 让父元素处理点击事件 */
|
||
}
|
||
|
||
:deep(.virtual-spacer-row td) {
|
||
padding: 0 !important;
|
||
border: 0 !important;
|
||
background: transparent !important;
|
||
}
|
||
|
||
.virtual-spacer-cell {
|
||
display: block;
|
||
width: 100%;
|
||
height: 100%;
|
||
pointer-events: none;
|
||
}
|
||
|
||
.column-config-toolbar {
|
||
display: flex;
|
||
gap: 8px;
|
||
margin-bottom: 12px;
|
||
}
|
||
|
||
.column-config-list {
|
||
max-height: 380px;
|
||
overflow: auto;
|
||
border: 1px solid #ebeef5;
|
||
border-radius: 4px;
|
||
}
|
||
|
||
.column-config-section {
|
||
border-bottom: 1px solid #e4e7ed;
|
||
}
|
||
|
||
.column-config-section:last-child {
|
||
border-bottom: none;
|
||
}
|
||
|
||
.column-config-section-title {
|
||
padding: 8px 12px 6px;
|
||
font-size: 12px;
|
||
color: #606266;
|
||
background: #fafafa;
|
||
font-weight: 600;
|
||
border-bottom: 1px solid #ebeef5;
|
||
}
|
||
|
||
.column-config-item {
|
||
display: flex;
|
||
align-items: center;
|
||
justify-content: space-between;
|
||
padding: 8px 12px;
|
||
border-bottom: 1px solid #f2f3f5;
|
||
}
|
||
|
||
.column-config-section .column-config-item:last-child {
|
||
border-bottom: none;
|
||
}
|
||
|
||
.column-config-item.is-fixed-column {
|
||
background: #f5f7fa;
|
||
border-left: 3px solid #909399;
|
||
}
|
||
|
||
.column-config-item.is-draggable {
|
||
cursor: move;
|
||
}
|
||
|
||
.column-config-item.is-drag-over {
|
||
background: #f0f9ff;
|
||
border-top: 1px dashed #409eff;
|
||
}
|
||
|
||
.drag-handle--locked {
|
||
color: #dcdfe6;
|
||
cursor: not-allowed;
|
||
user-select: none;
|
||
}
|
||
|
||
.column-config-actions--fixed {
|
||
flex-shrink: 0;
|
||
}
|
||
|
||
.column-config-fixed-hint {
|
||
font-size: 12px;
|
||
color: #909399;
|
||
padding: 0 10px;
|
||
user-select: none;
|
||
}
|
||
|
||
.column-config-main {
|
||
display: flex;
|
||
align-items: center;
|
||
gap: 8px;
|
||
flex: 1;
|
||
min-width: 0;
|
||
}
|
||
|
||
.drag-handle {
|
||
color: #909399;
|
||
font-size: 14px;
|
||
line-height: 1;
|
||
user-select: none;
|
||
}
|
||
|
||
.order-flag-text {
|
||
color: #f56c6c;
|
||
font-weight: 600;
|
||
}
|
||
|
||
.order-flag-copyable {
|
||
cursor: pointer;
|
||
}
|
||
|
||
/* 表格尺寸样式 */
|
||
.upper-table-container.small :deep(.el-table) {
|
||
font-size: 12px;
|
||
}
|
||
|
||
.upper-table-container.small :deep(.el-table td),
|
||
.upper-table-container.small :deep(.el-table th) {
|
||
padding: 6px 0;
|
||
}
|
||
|
||
.upper-table-container.large :deep(.el-table) {
|
||
font-size: 14px;
|
||
}
|
||
|
||
.upper-table-container.large :deep(.el-table td),
|
||
.upper-table-container.large :deep(.el-table th) {
|
||
padding: 12px 0;
|
||
}
|
||
|
||
/* 响应式调整 */
|
||
@media (max-width: 768px) {
|
||
.table-header {
|
||
flex-direction: column;
|
||
align-items: flex-start;
|
||
gap: 12px;
|
||
}
|
||
|
||
.header-right {
|
||
width: 100%;
|
||
justify-content: flex-end;
|
||
}
|
||
}
|
||
</style>
|