You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
dianshang-qianduan/src/views/courseResources/Management.vue

337 lines
24 KiB
Vue

<template>
<main v-loading="loading || sorting" class="course-management app-container">
<header class="page-head">
<h1>课程资源</h1>
<div class="actions">
<el-button v-if="isTeacher" @click="openVisibility">班级可见范围</el-button>
<el-button @click="setExpanded(true)">展开全部</el-button>
<el-button @click="setExpanded(false)">收起全部</el-button>
<el-button type="primary" :icon="Plus" @click="addNode()">新增章</el-button>
</div>
</header>
<div v-if="loadFailed" class="load-error"><el-result icon="error" title="课程资源加载失败"><template #extra><el-button @click="load">重新加载</el-button></template></el-result></div>
<div v-else class="management-columns">
<section class="outline-panel">
<div class="panel-head"><div class="outline-heading"><h2>课程资源大纲</h2><span>拖拽可排序 · 悬停行出现操作按钮</span></div><el-input v-model="keyword" :prefix-icon="Search" clearable placeholder="搜索目录或资源" /></div>
<el-tree ref="treeRef" class="outline-tree" :data="tree" node-key="id" :props="{ label: 'name', children: 'children' }" :expand-on-click-node="false" :filter-node-method="filterNode" :current-node-key="selectedId" :default-expanded-keys="expandedKeys" highlight-current @node-click="selectNode" @node-expand="rememberExpand" @node-collapse="rememberCollapse">
<template #default="{ data }">
<div class="outline-row" :class="{ 'is-selected': selectedId === data.id, 'drop-before': dropTarget?.id === data.id && !dropTarget.after, 'drop-after': dropTarget?.id === data.id && dropTarget.after }" :data-resource-node="data.id" :draggable="data.editable && !loading && !sorting && !keyword.trim()" @dragstart="startNodeDrag($event, data)" @dragover="overNode($event, data)" @drop="dropNode($event, data)" @dragend="endNodeDrag">
<span class="node-number">{{ data.number }}</span>
<span class="node-name" :title="data.name">{{ data.name }}</span>
<el-tag v-if="isTeacher && !data.ownerId" size="small" type="info">内置</el-tag>
<span class="file-count" :class="{ 'is-empty': !data.files.length }" :aria-label="`${data.name}本级资源${data.files.length}个`"><el-icon v-if="data.files.length"><Paperclip /></el-icon>{{ data.files.length || '空' }}</span>
<div class="node-actions" @click.stop>
<el-button link :icon="Paperclip" data-node-action="upload" title="上传资源" :aria-label="`上传资源到${data.name}`" @click="pickFiles(data)" />
<el-button v-if="data.depth < 3" link :icon="Plus" data-node-action="add" title="新增下级目录" :aria-label="`在${data.name}下新增目录`" @click="addNode(data)" />
<template v-if="data.editable">
<el-button link :icon="EditPen" data-node-action="rename" title="重命名" :aria-label="`重命名${data.name}`" @click="nodeAction('rename', data)" />
<el-button link :icon="Top" data-node-action="up" title="上移" :aria-label="`上移${data.name}`" :disabled="!canMove(data, -1)" @click="nodeAction('up', data)" />
<el-button link :icon="Bottom" data-node-action="down" title="下移" :aria-label="`下移${data.name}`" :disabled="!canMove(data, 1)" @click="nodeAction('down', data)" />
<el-button link :icon="Delete" data-node-action="delete" title="删除目录" :aria-label="`删除${data.name}`" @click="nodeAction('delete', data)" />
</template>
</div>
</div>
</template>
<template #empty><el-empty description="暂无目录" :image-size="72" /></template>
</el-tree>
</section>
<section class="resources-panel">
<template v-if="selected">
<div class="panel-head detail-head"><div><div class="breadcrumb">{{ selectedPath }}</div><h2>{{ selected.number }} {{ selected.name }}</h2></div><el-button type="primary" :icon="Upload" :loading="uploading" @click="pickFiles(selected)">上传资源</el-button></div>
<div class="drop-zone" :class="{ dragging }" @dragover.prevent="dragging = true" @dragleave.prevent="dragging = false" @drop.prevent="dropFiles">
<el-icon><UploadFilled /></el-icon><span>将文件拖到此处,或<button type="button" @click="pickFiles(selected)">选择文件</button></span>
</div>
<el-progress v-if="uploading" :percentage="uploadPercent" />
<div class="resource-toolbar"><span>{{ selected.files.length }} 个资源</span><el-select v-model="typeFilter" placeholder="资源类型"><el-option label="全部类型" value="all" /><el-option v-for="type in resourceTypes" :key="type" :label="type" :value="type" /></el-select></div>
<el-table :data="filteredFiles" class="resource-table">
<el-table-column label="资源名称" min-width="220"><template #default="{ row }"><div class="file-title"><span :class="['file-icon', resourceType(row.name).kind]">{{ resourceType(row.name).label }}</span><div><button class="file-link" type="button" @click="previewRef.open(row)">{{ row.name }}</button><div class="file-meta">{{ formatResourceSize(row.size) }} · {{ row.ownerId ? row.uploaderName : '系统内置' }}</div></div></div></template></el-table-column>
<el-table-column label="上传时间" width="156"><template #default="{ row }">{{ formatResourceDate(row.createdAt) }}</template></el-table-column>
<el-table-column label="操作" width="160" fixed="right"><template #default="{ row }"><el-button link type="primary" @click="previewRef.open(row)">预览</el-button><el-button link type="primary" @click="download(row)">下载</el-button><el-button v-if="row.editable" link type="danger" @click="removeFile(row)">删除</el-button></template></el-table-column>
<template #empty><el-empty description="该目录暂无资源" :image-size="80" /></template>
</el-table>
</template>
<el-empty v-else description="选择左侧目录查看资源" />
</section>
</div>
<input ref="fileInput" type="file" multiple hidden @change="filesSelected" />
<ResourcePreview ref="previewRef" />
<el-dialog v-model="visibilityOpen" title="班级可见范围" width="min(1100px, 94vw)" append-to-body destroy-on-close>
<div class="visibility-note">按目录设置各班级可见范围,资源跟随目录。父目录隐藏时,其下级一并隐藏。</div>
<el-table v-if="classes.length" :data="flatTree" max-height="55vh" border class="visibility-table">
<el-table-column label="大纲目录" min-width="270" fixed><template #default="{ row }"><span :style="{ paddingLeft: `${(row.depth - 1) * 18}px` }">{{ row.number }} {{ row.name }}</span></template></el-table-column>
<el-table-column label="全部班级" width="100" align="center"><template #default="{ row }"><el-checkbox :model-value="allVisible(row)" :indeterminate="someVisible(row) && !allVisible(row)" :aria-label="`${row.name}全部班级可见`" @change="value => toggleAll(row, value)" /></template></el-table-column>
<el-table-column v-for="schoolClass in classes" :key="schoolClass.id" :label="schoolClass.name" min-width="110" align="center"><template #default="{ row }"><span v-if="parentHidden(row, schoolClass.id)" class="inherited">随父级隐藏</span><el-checkbox v-else :model-value="draftValue(row, schoolClass.id)" :aria-label="`${row.name}对${schoolClass.name}可见`" @change="value => toggleVisibility(row, schoolClass.id, value)" /></template></el-table-column>
</el-table>
<el-empty v-else description="暂无本人创建的教学班" />
<template #footer><el-button @click="visibilityOpen = false">取消</el-button><el-button type="primary" :loading="savingVisibility" :disabled="!classes.length" @click="saveVisibility">保存设置</el-button></template>
</el-dialog>
</main>
</template>
<script setup>
import { ref, computed, watch, nextTick, onActivated } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Upload, UploadFilled, Paperclip, EditPen, Top, Bottom, Delete } from '@element-plus/icons-vue'
import useUserStore from '@/store/modules/user'
import * as api from '@/api/courseResource'
import { buildResourceTree, flattenResourceTree, resourceType, resourceMatches, formatResourceSize, formatResourceDate, visibleForClass, downloadCourseFile } from '@/utils/courseResource'
import ResourcePreview from './ResourcePreview.vue'
const userStore = useUserStore()
const isTeacher = computed(() => Number(userStore.userInfo.roleId) === 3)
const loading = ref(false)
const sorting = ref(false)
const draggedNode = ref(null)
const dropTarget = ref(null)
const loadFailed = ref(false)
const nodes = ref([])
const classes = ref([])
const permissions = ref([])
const tree = computed(() => buildResourceTree(nodes.value))
const flatTree = computed(() => flattenResourceTree(tree.value))
const selectedId = ref(null)
const selected = computed(() => flatTree.value.find(node => node.id === selectedId.value))
const expandedKeys = ref([])
const keyword = ref('')
const typeFilter = ref('all')
const treeRef = ref()
const previewRef = ref()
const fileInput = ref()
const uploading = ref(false)
const uploadPercent = ref(0)
const dragging = ref(false)
const resourceTypes = computed(() => [...new Set((selected.value?.files || []).map(file => resourceType(file.name).label))])
const filteredFiles = computed(() => (selected.value?.files || []).filter(file => typeFilter.value === 'all' || resourceType(file.name).label === typeFilter.value))
const selectedPath = computed(() => {
const path = []
let node = selected.value
while (node) { path.unshift(node.name); node = flatTree.value.find(item => item.id === node.parentId) }
return path.join(' / ')
})
let uploadTarget = null
async function load() {
loading.value = true
loadFailed.value = false
try {
const { data } = await api.getCourseResourceManagement()
nodes.value = data.nodes
classes.value = data.classes
permissions.value = data.permissions
if (!nodes.value.some(node => node.id === selectedId.value)) selectedId.value = tree.value[0]?.id || null
await nextTick()
treeRef.value?.filter(keyword.value)
treeRef.value?.setCurrentKey(selectedId.value)
} catch { loadFailed.value = true }
finally { loading.value = false }
}
onActivated(load)
watch(keyword, value => treeRef.value?.filter(value))
function filterNode(value, data) { return resourceMatches(data, value) }
function selectNode(node) { selectedId.value = node.id; typeFilter.value = 'all' }
function rememberExpand(node) { if (!expandedKeys.value.includes(node.id)) expandedKeys.value.push(node.id) }
function rememberCollapse(node) { expandedKeys.value = expandedKeys.value.filter(id => id !== node.id) }
function setExpanded(value) {
expandedKeys.value = value ? flatTree.value.map(node => node.id) : []
flatTree.value.forEach(node => { const internal = treeRef.value?.getNode(node.id); if (internal) internal.expanded = value })
}
async function focusNode(id) {
keyword.value = ''
selectedId.value = id
let node = nodes.value.find(node => node.id === id)
while (node) { rememberExpand(node); node = nodes.value.find(item => item.id === node.parentId) }
await nextTick()
treeRef.value?.setCurrentKey(id)
await nextTick()
treeRef.value?.$el.querySelector(`[data-resource-node="${id}"]`)?.scrollIntoView({ block: 'nearest' })
}
async function addNode(parent) {
try {
const { value } = await ElMessageBox.prompt('请输入目录名称', parent ? '新增下级目录' : '新增章', { inputValidator: value => !!value?.trim() && value.trim().length <= 200 || '请输入1至200个字符', confirmButtonText: '确定', cancelButtonText: '取消' })
const { data: id } = await api.createCourseResourceNode({ parentId: parent?.id || null, name: value.trim() })
await load()
await focusNode(id)
ElMessage.success('新增成功')
} catch (error) { if (error !== 'cancel' && error !== 'close') console.error(error) }
}
function canMove(node, direction) {
const siblings = flatTree.value.filter(item => item.parentId === node.parentId && item.ownerId === node.ownerId)
const target = siblings.findIndex(item => item.id === node.id) + direction
return target >= 0 && target < siblings.length
}
function startNodeDrag(event, node) {
if (event.target.closest('.node-actions')) { event.preventDefault(); return }
draggedNode.value = node
event.dataTransfer.effectAllowed = 'move'
event.dataTransfer.setData('text/plain', String(node.id))
}
function endNodeDrag() { draggedNode.value = null; dropTarget.value = null }
function canDropNode(target) {
const node = draggedNode.value
return node && !sorting.value && node.id !== target.id && node.editable && target.editable
&& node.parentId === target.parentId && node.ownerId === target.ownerId
}
function overNode(event, target) {
if (!canDropNode(target)) { dropTarget.value = null; return }
event.preventDefault()
event.dataTransfer.dropEffect = 'move'
const bounds = event.currentTarget.getBoundingClientRect()
dropTarget.value = { id: target.id, after: event.clientY >= bounds.top + bounds.height / 2 }
}
async function dropNode(event, target) {
if (!canDropNode(target)) { endNodeDrag(); return }
event.preventDefault()
const node = draggedNode.value
const bounds = event.currentTarget.getBoundingClientRect()
const after = event.clientY >= bounds.top + bounds.height / 2
endNodeDrag()
const siblings = nodes.value.filter(item => item.parentId === node.parentId && item.ownerId === node.ownerId)
const from = siblings.findIndex(item => item.id === node.id)
const destination = siblings.filter(item => item.id !== node.id).findIndex(item => item.id === target.id) + (after ? 1 : 0)
const distance = destination - from
sorting.value = true
selectNode(node)
try {
for (let step = 0; step < Math.abs(distance); step++) await api.moveCourseResourceNode(node.id, Math.sign(distance))
if (distance) ElMessage.success('排序已保存')
} catch {
// The request interceptor displays the server error; reload any completed moves below.
} finally {
await load()
sorting.value = false
treeRef.value?.$el.querySelector(`[data-resource-node="${node.id}"] [data-node-action="upload"]`)?.focus()
}
}
async function nodeAction(command, node) {
selectNode(node)
try {
if (command === 'rename') {
const { value } = await ElMessageBox.prompt('请输入目录名称', '重命名', { inputValue: node.name, inputValidator: value => !!value?.trim() && value.trim().length <= 200 || '请输入1至200个字符', confirmButtonText: '确定', cancelButtonText: '取消' })
await api.renameCourseResourceNode(node.id, value.trim())
} else if (command === 'up' || command === 'down') {
await api.moveCourseResourceNode(node.id, command === 'up' ? -1 : 1)
} else if (command === 'delete') {
const warning = !node.ownerId ? '该目录及其全部下级目录、资源将一并删除,包括教师在其下新增的目录和资源,教师端和学生端将同步移除。' : '该目录及其全部下级目录、资源将一并删除。'
await ElMessageBox.confirm(node.depth < 3 ? warning : '确定删除该目录及其中的全部资源?', `删除「${node.name}」`, { type: 'warning', confirmButtonText: '确认删除', cancelButtonText: '取消' })
await api.deleteCourseResourceNode(node.id)
}
await load()
const row = treeRef.value?.$el.querySelector(`[data-resource-node="${node.id}"]`)
;(row?.querySelector(`[data-node-action="${command}"]:not(:disabled)`) || row?.querySelector('.node-actions button:not(:disabled)'))?.focus()
ElMessage.success('操作成功')
} catch (error) { if (error !== 'cancel' && error !== 'close') console.error(error) }
}
function pickFiles(node) {
if (uploading.value) return
selectNode(node)
uploadTarget = node.id
fileInput.value.value = ''
fileInput.value.click()
}
function filesSelected(event) { uploadFiles([...event.target.files], uploadTarget) }
function dropFiles(event) { dragging.value = false; if (selected.value) uploadFiles([...event.dataTransfer.files], selected.value.id) }
async function uploadFiles(files, nodeId) {
if (!files.length || uploading.value) return
uploading.value = true
uploadPercent.value = 0
let completed = 0
try {
for (const file of files) {
const data = new FormData()
data.append('file', file)
await api.uploadCourseResource(nodeId, data, event => {
uploadPercent.value = Math.round((completed + (event.total ? event.loaded / event.total : 0)) / files.length * 100)
})
completed++
}
ElMessage.success(`已上传 ${completed} 个资源`)
} finally {
uploading.value = false
typeFilter.value = 'all'
await load()
await focusNode(nodeId)
}
}
async function removeFile(file) {
try {
await ElMessageBox.confirm(`确定删除「${file.name}」?`, '删除资源', { type: 'warning', confirmButtonText: '删除', cancelButtonText: '取消' })
await api.deleteCourseResourceFile(file.id)
await load()
ElMessage.success('删除成功')
} catch (error) { if (error !== 'cancel' && error !== 'close') console.error(error) }
}
async function download(file) { await downloadCourseFile(file, api.getCourseResourceContent) }
const visibilityOpen = ref(false)
const savingVisibility = ref(false)
const draft = ref([])
function openVisibility() { draft.value = permissions.value.map(rule => ({ ...rule })); visibilityOpen.value = true }
function draftValue(node, classId) { return visibleForClass(node, classId, draft.value) }
function toggleVisibility(node, classId, visible) {
const rule = draft.value.find(rule => rule.nodeId === node.id && rule.classId === classId)
if (rule) rule.visible = visible
else draft.value.push({ nodeId: node.id, classId, visible })
}
function parentHidden(node, classId) {
let parent = flatTree.value.find(item => item.id === node.parentId)
while (parent) {
if (!draftValue(parent, classId)) return true
parent = flatTree.value.find(item => item.id === parent.parentId)
}
return false
}
function allVisible(node) { return classes.value.every(item => !parentHidden(node, item.id) && draftValue(node, item.id)) }
function someVisible(node) { return classes.value.some(item => !parentHidden(node, item.id) && draftValue(node, item.id)) }
function toggleAll(node, visible) { classes.value.forEach(item => toggleVisibility(node, item.id, visible)) }
async function saveVisibility() {
savingVisibility.value = true
try {
const changes = draft.value.filter(rule => visibleForClass(flatTree.value.find(node => node.id === rule.nodeId) || {}, rule.classId, permissions.value) !== rule.visible)
if (changes.length) await api.saveCourseResourceVisibility(changes.map(({ nodeId, classId, visible }) => ({ nodeId, classId, visible })))
visibilityOpen.value = false
await load()
ElMessage.success('已保存班级可见范围')
} finally { savingVisibility.value = false }
}
</script>
<style scoped lang="scss">
.course-management { color: var(--text-strong, #1f2937); padding: 20px 24px; }
.page-head, .actions, .panel-head, .outline-row, .resource-toolbar, .file-title { display: flex; align-items: center; }
.page-head { justify-content: space-between; gap: 16px; margin-bottom: 20px; }
h1 { margin: 0; font-size: var(--fs-page, 18px); font-weight: 600; }
h2 { margin: 0; font-size: var(--fs-card, 14px); font-weight: 600; }
.actions { flex-wrap: wrap; gap: 8px; :deep(.el-button + .el-button) { margin-left: 0; } }
.management-columns { display: grid; grid-template-columns: minmax(520px, 60%) minmax(0, 1fr); gap: 16px; align-items: start; }
.outline-panel, .resources-panel { background: #fff; border: 1px solid var(--border-color, #e5e7eb); border-radius: var(--r-card, 12px); min-width: 0; overflow: hidden; }
.panel-head { padding: 16px; gap: 12px; border-bottom: 1px solid #edf0f4; justify-content: space-between; }
.panel-head > h2 { white-space: nowrap; flex-shrink: 0; }
.outline-heading { display: flex; align-items: baseline; flex-wrap: wrap; gap: 5px 10px; min-width: 0; h2 { white-space: nowrap; } span { color: #94a3b8; font-size: 11px; } }
.panel-head :deep(.el-input) { width: 190px; min-width: 0; }
.outline-tree { min-height: 480px; max-height: calc(100vh - 236px); overflow: auto; padding: 12px 6px; :deep(.el-tree-node__content) { height: 40px; border-radius: 6px; } :deep(.el-tree-node.is-current > .el-tree-node__content) { background: #e8f2fd; box-shadow: inset 3px 0 #3b658f; } }
.outline-row { position: relative; flex: 1; min-width: 0; gap: 8px; padding-right: 10px; height: 100%; &[draggable="true"] .node-name { cursor: grab; } &.drop-before::before, &.drop-after::after { content: ''; position: absolute; left: 0; right: 0; height: 2px; background: #3b658f; pointer-events: none; } &.drop-before::before { top: 0; } &.drop-after::after { bottom: 0; } }
.node-number { flex-shrink: 0; padding: 1px 7px; border: 1px solid #f1dca7; border-radius: 5px; background: #fcf5e5; font-size: 11px; font-weight: 600; color: #ad821e; font-variant-numeric: tabular-nums; }
.node-name { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 12px; }
.file-count { display: inline-flex; flex-shrink: 0; align-items: center; justify-content: center; gap: 3px; min-width: 34px; padding: 2px 8px; border-radius: 12px; background: #e8f2fd; color: #3b658f; font-size: 11px; font-weight: 600; line-height: 16px; &.is-empty { color: #94a3b8; background: #f0f4f8; } }
.node-actions { display: none; flex-shrink: 0; align-items: center; gap: 1px; :deep(.el-button) { width: 25px; height: 26px; padding: 4px; margin: 0; color: #94a3b8; font-size: 15px; &:hover, &:focus-visible { color: #3b658f; background: #dceaf8; } &.is-disabled { color: #cbd5e1; } } :deep([data-node-action="rename"]) { color: #f07859; } }
.outline-row.is-selected .node-actions, .outline-row:hover .node-actions, .outline-row:focus-within .node-actions, .outline-tree :deep(.el-tree-node:focus > .el-tree-node__content .node-actions) { display: flex; }
.resources-panel { min-height: 530px; padding-bottom: 16px; }
.detail-head { align-items: flex-start; }
.detail-head > div { flex: 1; min-width: 0; }
.detail-head h2 { overflow-wrap: anywhere; line-height: 1.5; }
.detail-head > .el-button { flex-shrink: 0; }
.breadcrumb { font-size: 11px; line-height: 1.5; color: #94a3b8; margin-bottom: 7px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.drop-zone { margin: 16px; border: 1px dashed #cbd5e1; border-radius: 8px; background: #fafcff; padding: 24px 12px; display: flex; flex-direction: column; align-items: center; gap: 10px; font-size: 12px; color: #6b7280; .el-icon { font-size: 28px; color: #94a3b8; } button { border: 0; background: none; color: var(--edu-primary, #3b82f6); cursor: pointer; } &.dragging { border-color: #3b82f6; background: #eff6ff; } }
.resource-toolbar { margin: 16px; justify-content: space-between; font-size: 12px; color: #64748b; :deep(.el-select) { width: 130px; } }
.resource-table { width: calc(100% - 32px); margin: 0 16px; font-size: 12px; }
.file-title { gap: 10px; min-width: 0; > div { min-width: 0; } }
.file-icon { width: 40px; height: 42px; border-radius: 8px; display: inline-flex; align-items: center; justify-content: center; background: #eff6ff; color: #2563eb; font-size: 10px; font-weight: 600; flex-shrink: 0; &.image { color: #0f766e; background: #f0fdfa; } &.video, &.audio { color: #7c3aed; background: #f5f3ff; } }
.file-link { border: 0; background: none; text-align: left; padding: 0; color: #334155; cursor: pointer; word-break: break-all; line-height: 1.6; &:hover { color: #2563eb; } }
.file-meta { font-size: 11px; color: #94a3b8; line-height: 1.8; }
.visibility-note { color: #64748b; font-size: 12px; margin-bottom: 14px; }
.visibility-table { font-size: 12px; }
.inherited { color: #94a3b8; font-size: 11px; }
@media (max-width: 1200px) { .management-columns { grid-template-columns: 1fr; } .course-management { padding: 16px; } .outline-tree { min-height: 280px; max-height: 440px; } }
@media (max-width: 760px) { .page-head { align-items: flex-start; flex-direction: column; } .management-columns { grid-template-columns: 1fr; } .outline-tree { min-height: 200px; max-height: 350px; } }
@media (max-width: 540px) { .outline-tree :deep(.el-tree-node__content) { height: auto; min-height: 40px; } .outline-row { flex-wrap: wrap; gap: 5px; padding-top: 6px; padding-bottom: 6px; } .node-name { min-width: 55px; } .node-actions { flex-basis: 100%; justify-content: flex-end; } .panel-head { padding: 12px; gap: 8px; } }
</style>