Files
banben/frontend/src/views/search/SearchView.vue
T
SUNJIAJINGS 3626939ccb feat(admin): 添加列表显示字段配置功能
- 新增 list_field_config 表及后端接口,支持查询、保存、恢复默认字段配置
- 管理后台新增“列表字段配置”页签,可增删字段、调整顺序、修改显示名与可见性
- version_resource 表新增作者单位、来源资源库名字段及升级脚本
- 引入 xlsx 依赖以支持列表导出
2026-10-22 17:33:34 +08:00

632 lines
21 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.
<script setup lang="ts">
import { computed, onMounted, reactive, ref, watch } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import * as XLSX from 'xlsx'
import { listFields, type ListFieldConfig } from '@/api/admin'
import { getSearchDetail, getSimilar, unifiedSearch, searchList, type FacetItem, type SearchQuery } from '@/api/search'
import type { VersionResource } from '@/api/resource'
const route = useRoute()
const loading = ref(false)
const searched = ref(false)
const rows = ref<VersionResource[]>([])
const total = ref(0)
const costMs = ref(0)
const mediaFacets = ref<FacetItem[]>([])
const libraryFacets = ref<FacetItem[]>([])
const query = reactive<SearchQuery>({
current: 1,
size: 50,
mediaType: ''
})
/** 概览页每页条数选项(默认 50,可切 100/200;20 便于数据量小时演示翻页) */
const pageSizes = [20, 50, 100, 200]
// ==================== 检索结果展示字段(管理员在后台配置) ====================
/** 展示字段配置:取不到配置时用默认的 8 个字段兜底 */
const listFieldConfig = ref<ListFieldConfig[]>([])
const metaFields = computed(() =>
listFieldConfig.value.filter((f) => f.visible !== 0 && f.fieldKey !== 'title')
)
async function fetchListFields() {
try {
listFieldConfig.value = await listFields('SEARCH')
} catch {
listFieldConfig.value = []
}
}
/** 按字段键取值(含高亮所需原文),未配置值返回空串 */
function metaValue(row: VersionResource, key: string): string {
const v = (row as unknown as Record<string, unknown>)[key]
return v === null || v === undefined ? '' : String(v)
}
/** 输入框内容(与查询参数分离,避免按途径分发后被清空) */
const input = ref('')
const field = ref('综合')
const fields = ['综合', '题名', '责任者', '关键词', '出版社', 'ISBN']
/** 检索途径 → 查询参数字段 */
const fieldParamMap: Record<string, 'keyword' | 'title' | 'author' | 'publisher' | 'isbn'> = {
综合: 'keyword',
题名: 'title',
责任者: 'author',
关键词: 'keyword',
出版社: 'publisher',
ISBN: 'isbn'
}
// ==================== 命中位置标注与高亮 ====================
/** 各检索途径对应的检查字段(综合途经覆盖全部文本字段) */
const hitFieldMap: Record<string, string[]> = {
综合: ['title', 'author', 'keywords', 'summary', 'publisher'],
题名: ['title'],
责任者: ['author'],
关键词: ['keywords'],
出版社: ['publisher'],
ISBN: ['isbn']
}
const fieldLabels: Record<string, string> = {
title: '正题名',
author: '责任者',
keywords: '关键词',
summary: '摘要',
publisher: '出版者',
isbn: 'ISBN'
}
/** 当前检索词(空格分词) */
const terms = computed(() => input.value.trim().split(/\s+/).filter(Boolean))
function escapeHtml(s: string) {
return s.replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[c] as string)
}
/** 文本高亮:命中的关键词包一层 span(先转义再包裹,避免注入) */
function highlight(text?: string): string {
if (!text || !terms.value.length) return escapeHtml(text || '')
let out = escapeHtml(text)
for (const t of terms.value) {
const esc = escapeHtml(t)
if (esc) out = out.split(esc).join(`<span class="hl">${esc}</span>`)
}
return out
}
/** 命中字段的上下文摘录(标题外命中时展示,如「出版者:…军事科学出版社…」) */
function snippets(row: VersionResource): { label: string; html: string }[] {
const keys = (hitFieldMap[field.value] || []).filter((k) => k !== 'title')
const out: { label: string; html: string }[] = []
for (const k of keys) {
const v = (row as unknown as Record<string, string | undefined>)[k]
if (!v) continue
const hit = terms.value.find((t) => v.includes(t))
if (!hit) continue
const idx = v.indexOf(hit)
const start = Math.max(0, idx - 12)
const end = Math.min(v.length, idx + hit.length + 28)
const text = (start > 0 ? '…' : '') + v.slice(start, end) + (end < v.length ? '…' : '')
out.push({ label: fieldLabels[k], html: highlight(text) })
}
return out
}
async function doSearch() {
loading.value = true
searched.value = true
// 按所选途径分发检索词;多词用空格分隔,词与词之间为 AND
const kw = input.value.trim()
query.title = query.author = query.publisher = query.isbn = query.keyword = ''
;(query as unknown as Record<string, string>)[fieldParamMap[field.value]] = kw
try {
const res = await unifiedSearch({ ...query })
rows.value = res.page?.records || []
total.value = res.page?.total || 0
costMs.value = res.costMs || 0
mediaFacets.value = res.mediaTypeFacets || []
libraryFacets.value = res.sourceLibraryFacets || []
} finally {
loading.value = false
}
}
function pick(type: 'mediaType' | 'sourceLibrary', v: string) {
query[type] = v
query.current = 1
doSearch()
}
function goPage(p: number) {
query.current = p
doSearch()
scrollToListTop()
}
/** 切换每页条数:回到第一页重新检索 */
function goSize(s: number) {
query.size = s
query.current = 1
doSearch()
scrollToListTop()
}
/** 翻页后回到结果列表顶部,避免停在长列表中间 */
function scrollToListTop() {
window.scrollTo({ top: 0, behavior: 'smooth' })
}
// ==================== 批量导出 Excel ====================
/** 可导出字段(key 对应 VersionResource 字段) */
const exportFields: { key: string; label: string }[] = [
{ key: 'processNo', label: '加工编号' },
{ key: 'title', label: '正题名' },
{ key: 'otherTitle', label: '其他题名' },
{ key: 'author', label: '责任者' },
{ key: 'authorOrg', label: '作者单位' },
{ key: 'responsibility', label: '责任方式' },
{ key: 'publisher', label: '出版者' },
{ key: 'sourceRepo', label: '来源资源库名' },
{ key: 'publishPlace', label: '出版地' },
{ key: 'publishDate', label: '出版日期' },
{ key: 'publishYear', label: '出版年份' },
{ key: 'edition', label: '版本' },
{ key: 'isbn', label: 'ISBN' },
{ key: 'clcCode', label: '中图分类' },
{ key: 'keywords', label: '关键词' },
{ key: 'summary', label: '摘要' },
{ key: 'mediaType', label: '媒体类型' },
{ key: 'format', label: '格式' },
{ key: 'language', label: '语种' },
{ key: 'pageCount', label: '页码' },
{ key: 'sourceLibrary', label: '来源馆' },
{ key: 'cdoi', label: 'CDOI' },
{ key: 'governStatus', label: '治理状态' },
{ key: 'fulltextUrl', label: '全文地址' }
]
/** 默认勾选的常用字段 */
const defaultFields = ['processNo', 'title', 'author', 'publisher', 'publishYear', 'isbn', 'clcCode', 'mediaType', 'sourceLibrary']
const exportVisible = ref(false)
const exporting = ref(false)
const exportScope = ref<'selected' | 'page' | 'all'>('all')
const exportFieldsChecked = ref<string[]>([...defaultFields])
/** 已勾选的记录(跨当前页保留) */
const selectedIds = ref<Set<number>>(new Set())
const selectedCount = computed(() => selectedIds.value.size)
function toggleSelect(row: VersionResource) {
const id = row.id as number
const next = new Set(selectedIds.value)
next.has(id) ? next.delete(id) : next.add(id)
selectedIds.value = next
}
function selectAllOnPage() {
const next = new Set(selectedIds.value)
rows.value.forEach((r) => next.add(r.id as number))
selectedIds.value = next
}
function clearSelection() {
selectedIds.value = new Set()
}
/** 取值:兼容 undefined / null,并按字段做必要的展示转换 */
function cellText(row: VersionResource, key: string): string {
const raw = ((row as unknown as Record<string, unknown>) || {})[key]
if (raw === null || raw === undefined) return ''
if (typeof raw === 'object') return JSON.stringify(raw)
// Excel 单格上限 32767 字符,超长摘要做截断保护
const s = String(raw)
return s.length > 32000 ? s.slice(0, 32000) + '…' : s
}
async function confirmExport() {
if (!exportFieldsChecked.value.length) {
ElMessage.warning('请至少选择一个导出字段')
return
}
exporting.value = true
try {
let list: VersionResource[] = []
if (exportScope.value === 'selected') {
if (!selectedIds.value.size) {
ElMessage.warning('请先在结果列表中勾选要导出的记录')
return
}
list = rows.value.filter((r) => selectedIds.value.has(r.id as number))
if (list.length < selectedIds.value.size) {
// 勾选可能来自其他页,需从后端按当前检索条件捞取后过滤
const all = await searchList({ ...query })
const wanted = new Set([...selectedIds.value])
list = all.filter((r) => wanted.has(r.id as number))
}
} else if (exportScope.value === 'page') {
list = rows.value
} else {
list = await searchList({ ...query })
}
if (!list.length) {
ElMessage.warning('没有可导出的数据')
return
}
const fields = exportFields.filter((f) => exportFieldsChecked.value.includes(f.key))
const aoa: (string | number)[][] = [fields.map((f) => f.label)]
for (const row of list) {
aoa.push(fields.map((f) => cellText(row, f.key)))
}
const sheet = XLSX.utils.aoa_to_sheet(aoa)
sheet['!cols'] = fields.map((f) => ({ wch: Math.max(12, f.label.length * 2 + 6) }))
const wb = XLSX.utils.book_new()
XLSX.utils.book_append_sheet(wb, sheet, '检索结果')
const name = `${input.value.trim() || '全部资源'}-${list.length}条-${new Date().toISOString().slice(0, 10)}.xlsx`
XLSX.writeFile(wb, name)
ElMessage.success(`已导出 ${list.length} 条 / ${fields.length} 个字段`)
exportVisible.value = false
} finally {
exporting.value = false
}
}
const drawer = ref(false)
const detail = ref<VersionResource | null>(null)
const similar = ref<VersionResource[]>([])
async function openDetail(row: VersionResource) {
detail.value = row
similar.value = []
drawer.value = true
const d = await getSearchDetail(row.id as number)
if (d) detail.value = d
similar.value = await getSimilar(row.id as number, 6)
}
onMounted(() => {
const kw = route.query.keyword as string
const f = route.query.field as string
// 主页带来的检索途径(题名/责任者/…),合法则沿用
if (f && fields.includes(f)) {
field.value = f
}
// 检索条件为空时也执行检索 → 后端返回全部版本资源
input.value = kw || ''
fetchListFields()
doSearch()
})
// 已在检索页时,主页/热词再次带词跳转也能触发新检索
watch(
() => route.query.keyword,
(kw) => {
if (route.path !== '/search') return
input.value = (kw as string) || ''
doSearch()
}
)
</script>
<template>
<div class="search-page">
<div class="bar">
<el-input v-model="input" size="large" placeholder="请输入检索词,支持多词检索(空格分隔,命中任一词即返回)" clearable @keyup.enter="doSearch">
<template #prepend>
<el-select v-model="field" style="width: 96px" @change="searched && doSearch()">
<el-option v-for="f in fields" :key="f" :label="f" :value="f" />
</el-select>
</template>
<template #append><el-button type="primary" @click="doSearch">检索</el-button></template>
</el-input>
</div>
<div class="body" v-if="searched">
<aside class="side">
<div class="side-title">资源类型</div>
<div v-for="f in mediaFacets" :key="f.name" class="side-item"
:class="{ on: query.mediaType === f.name }" @click="pick('mediaType', f.name)">
<span>{{ f.name }}</span><em>{{ f.value }}</em>
</div>
<div class="side-title">来源院校</div>
<div v-for="f in libraryFacets" :key="f.name" class="side-item"
:class="{ on: query.sourceLibrary === f.name }" @click="pick('sourceLibrary', f.name)">
<span>{{ f.name }}</span><em>{{ f.value }}</em>
</div>
</aside>
<section class="list">
<div class="toolbar">
<div class="count">共 <b>{{ total }}</b> 条,耗时 {{ costMs }} ms<template v-if="selectedCount">,已勾选 <b>{{ selectedCount }}</b> 条</template></div>
<div class="ops">
<el-checkbox
:model-value="rows.length > 0 && rows.every((r) => selectedIds.has(r.id as number))"
:indeterminate="selectedCount > 0 && selectedCount < rows.length"
@change="(v: boolean) => (v ? selectAllOnPage() : clearSelection())"
>全选本页</el-checkbox>
<el-button size="small" :disabled="!selectedCount" @click="clearSelection">清空选择</el-button>
<el-button size="small" type="primary" @click="exportVisible = true">批量导出 Excel</el-button>
</div>
</div>
<div v-loading="loading" class="cards">
<div v-for="r in rows" :key="r.id" class="card" :class="{ checked: selectedIds.has(r.id as number) }" @click="openDetail(r)">
<div class="pick" @click.stop>
<el-checkbox :model-value="selectedIds.has(r.id as number)" @change="toggleSelect(r)" />
</div>
<div class="cover">{{ (r.title || '').slice(0, 2) }}</div>
<div class="info">
<div class="t" v-html="highlight(r.title)"></div>
<div class="metas">
<div v-for="f in metaFields" :key="f.fieldKey" class="cmeta">
<span class="cmeta-k">{{ f.fieldLabel }}:</span>
<span v-if="metaValue(r, f.fieldKey)" v-html="highlight(metaValue(r, f.fieldKey))"></span>
<span v-else class="empty">-</span>
</div>
</div>
<div v-for="s in snippets(r)" :key="s.label" class="snippet">
<span class="snippet-label">{{ s.label }}:</span>
<span v-html="s.html"></span>
</div>
</div>
</div>
</div>
<el-pagination class="pager" background
layout="total, sizes, prev, pager, next, jumper"
:total="total"
:current-page="query.current"
:page-size="query.size"
:page-sizes="pageSizes"
:pager-count="7"
@current-change="goPage"
@size-change="goSize" />
</section>
</div>
<el-empty v-else description="请输入检索词开始检索" />
<!-- 批量导出:选择范围与字段 -->
<el-dialog v-model="exportVisible" title="批量导出检索结果" width="620px">
<el-form label-width="88px">
<el-form-item label="导出范围">
<el-radio-group v-model="exportScope">
<el-radio value="all">全部检索结果(最多 1 万条,约 {{ total }} 条)</el-radio>
<el-radio value="page">当前页({{ rows.length }} 条)</el-radio>
<el-radio value="selected" :disabled="!selectedCount">仅勾选记录({{ selectedCount }} 条)</el-radio>
</el-radio-group>
</el-form-item>
<el-form-item label="导出字段">
<div class="field-box">
<div class="field-ops">
<el-button link type="primary" @click="exportFieldsChecked = exportFields.map((f) => f.key)">全选</el-button>
<el-button link @click="exportFieldsChecked = [...defaultFields]">恢复默认</el-button>
<span class="hint">已选 {{ exportFieldsChecked.length }} / {{ exportFields.length }}</span>
</div>
<el-checkbox-group v-model="exportFieldsChecked">
<el-checkbox v-for="f in exportFields" :key="f.key" :value="f.key" class="field-item">{{ f.label }}</el-checkbox>
</el-checkbox-group>
</div>
</el-form-item>
</el-form>
<template #footer>
<el-button @click="exportVisible = false">取消</el-button>
<el-button type="primary" :loading="exporting" @click="confirmExport">导出 Excel</el-button>
</template>
</el-dialog>
<el-drawer v-model="drawer" title="文献细览" size="46%">
<template v-if="detail">
<h3 class="dt">{{ detail.title }}</h3>
<el-descriptions :column="1" border size="small">
<el-descriptions-item label="责任者">{{ detail.author || '-' }}</el-descriptions-item>
<el-descriptions-item label="出版者">{{ detail.publisher || '-' }}</el-descriptions-item>
<el-descriptions-item label="出版年份">{{ detail.publishYear || '-' }}</el-descriptions-item>
<el-descriptions-item label="媒体类型">{{ detail.mediaType || '-' }}</el-descriptions-item>
<el-descriptions-item label="中图分类">{{ detail.clcCode || '-' }}</el-descriptions-item>
<el-descriptions-item label="来源院校">{{ detail.sourceLibrary || '-' }}</el-descriptions-item>
<el-descriptions-item label="关键词">{{ detail.keywords || '-' }}</el-descriptions-item>
<el-descriptions-item label="摘要">{{ detail.summary || '-' }}</el-descriptions-item>
</el-descriptions>
<div style="margin: 14px 0">
<el-button v-if="detail.fulltextUrl" type="primary" tag="a" :href="detail.fulltextUrl" target="_blank">下载全文</el-button>
<el-button v-else type="primary" disabled>暂无全文地址</el-button>
</div>
<div v-if="similar.length" class="sim">
<div class="side-title">相似文献推荐</div>
<div v-for="s in similar" :key="s.id" class="sim-item" @click="openDetail(s)">{{ s.title }}</div>
</div>
</template>
</el-drawer>
</div>
</template>
<style scoped lang="scss">
.bar {
max-width: 860px;
margin: 8px auto 20px;
:deep(.el-input-group__append) {
background: var(--brand-primary);
border-color: var(--brand-primary);
color: #fff;
padding: 0;
.el-button {
background: transparent;
color: #fff;
border: none;
height: 100%;
padding: 0 22px;
}
}
}
.body {
display: flex;
gap: 16px;
max-width: 1240px;
margin: 0 auto;
}
.side {
width: 210px;
flex: none;
background: #fff;
border: 1px solid var(--card-border);
border-radius: var(--radius-sm);
padding: 12px;
height: fit-content;
.side-title {
font-size: 13px;
font-weight: 600;
margin: 10px 0 6px;
}
.side-item {
display: flex;
justify-content: space-between;
font-size: 13px;
color: #5b6472;
padding: 4px 6px;
border-radius: 4px;
cursor: pointer;
&:hover { background: var(--brand-light); }
&.on { background: var(--brand-light); color: var(--brand-primary); }
em { color: #9aa3b2; font-style: normal; }
}
}
.list { flex: 1; }
.toolbar {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
flex-wrap: wrap;
margin-bottom: 10px;
.count { font-size: 13px; color: #6b7280; }
.ops { display: flex; align-items: center; gap: 10px; }
}
.cards {
display: flex;
flex-direction: column;
gap: 14px;
}
.card {
display: flex;
gap: 12px;
background: #fff;
border: 1px solid var(--card-border);
border-radius: var(--radius-sm);
padding: 14px;
cursor: pointer;
transition: box-shadow 0.2s;
&:hover { box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1); }
&.checked { border-color: var(--brand-primary); box-shadow: inset 0 0 0 1px var(--brand-primary); }
}
.pick {
display: flex;
align-items: center;
padding-right: 2px;
cursor: default;
}
.cover {
width: 56px;
height: 76px;
flex: none;
border-radius: 4px;
background: var(--brand-primary);
color: #fff;
display: flex;
align-items: center;
justify-content: center;
font-size: 18px;
}
.info {
min-width: 0;
.t { font-size: 14px; font-weight: 600; color: #1f2937; margin-bottom: 6px; }
.d { font-size: 12px; color: #8b93a1; }
}
/* 按管理员配置的字段渲染出的元信息区(两列自适应) */
.metas {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
gap: 2px 16px;
}
.cmeta {
font-size: 12px;
color: #6b7280;
line-height: 1.7;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
.cmeta-k { color: #8b93a1; }
.empty { color: #b6bcc7; }
}
/* 命中关键词高亮(v-html 动态插入的节点不带 scoped 属性,需用 :deep 穿透) */
:deep(.hl) {
background: #ffe6a3;
color: #8a4b00;
border-radius: 2px;
padding: 0 1px;
}
.snippet {
margin-top: 4px;
font-size: 12px;
color: #7b8493;
line-height: 1.5;
word-break: break-all;
}
.snippet-label {
color: #4b5563;
}
.field-box {
border: 1px solid var(--card-border);
border-radius: var(--radius-sm);
padding: 8px 10px;
.field-ops { display: flex; align-items: center; gap: 10px; margin-bottom: 6px; }
.hint { font-size: 12px; color: #8b93a1; }
.field-item { width: 25% !important; margin-right: 0 !important; }
}
.pager {
margin-top: 18px;
justify-content: center;
flex-wrap: wrap;
/* 页码较多时自动换行,保证页码按钮与跳转框都能点到 */
:deep(.el-pagination__jump) { margin-left: 12px; }
}
.dt { margin: 0 0 12px; font-size: 17px; }
.sim-item { font-size: 13px; padding: 6px 0; border-bottom: 1px dashed #eee; cursor: pointer; }
</style>