Files
bj_power/bj_power_mes/frontend/src/layouts/MainLayout.vue
T

429 lines
17 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>
<el-container class="layout">
<!-- 移动端遮罩 -->
<div v-if="isMobile && mobileOpen" class="drawer-mask" @click="mobileOpen = false"></div>
<el-aside :width="asideWidth" class="aside"
:class="{ 'drawer': isMobile, 'drawer-open': isMobile && mobileOpen }">
<div class="logo">
<el-icon :size="22"><Monitor /></el-icon>
<span v-show="!isCollapse">MES 产线控制</span>
</div>
<el-menu v-if="menus.length" :key="menuKey" :default-active="$route.path" :default-openeds="defaultOpeneds"
router background-color="#001529" text-color="#a6adb4" active-text-color="#409eff"
style="border-right:none" :collapse="isCollapse && !isMobile">
<el-sub-menu v-for="g in menus" :key="g.title" :index="'group:' + g.title">
<template #title>
<el-icon style="margin-right:8px"><component :is="g.icon" /></el-icon>
<span>{{ g.title }}</span>
</template>
<el-menu-item v-for="m in g.children" :key="m.path" :index="m.path">
<el-icon style="margin-right:8px"><component :is="m.icon" /></el-icon>
<span>{{ m.name }}</span>
<span v-if="badgeOf(m.path) > 0" class="todo-badge">{{ badgeOf(m.path) }}</span>
</el-menu-item>
</el-sub-menu>
</el-menu>
<div v-else class="no-menu">
<p>无可用菜单</p>
<p class="sub">请联系管理员分配权限</p>
</div>
</el-aside>
<el-container>
<el-header class="header">
<div class="header-left">
<el-icon class="collapse-btn" @click="toggleAside">
<Expand v-if="isMobile ? !mobileOpen : isCollapse" />
<Fold v-else />
</el-icon>
<span class="page-title">{{ $route.meta.title || '' }}</span>
</div>
<div class="spacer"></div>
<div class="header-right">
<el-badge :value="unreadAlerts" :hidden="unreadAlerts === 0" :max="99" class="alert-badge">
<el-tooltip content="异常告警" placement="bottom">
<el-button class="alert-btn" text @click="goAlertCenter">
<el-icon :size="18" :class="{ 'alert-ring': unreadAlerts > 0 }"><Bell /></el-icon>
</el-button>
</el-tooltip>
</el-badge>
<el-button class="board-btn" text @click="openBoard">生产看板大屏</el-button>
<el-button class="help-btn" text @click="openHelp">帮助</el-button>
<el-dropdown trigger="click" @command="onUserCmd">
<span class="user-name">{{ userName }} <span class="caret">▾</span></span>
<template #dropdown>
<el-dropdown-menu>
<el-dropdown-item command="password">修改密码</el-dropdown-item>
<el-dropdown-item divided command="logout">退出登录</el-dropdown-item>
</el-dropdown-menu>
</template>
</el-dropdown>
</div>
</el-header>
<el-main class="main">
<NextStepBar />
<router-view />
</el-main>
</el-container>
</el-container>
</template>
<script setup>
import { ref, computed, onMounted, onBeforeUnmount, watch } from 'vue'
import { useRouter } from 'vue-router'
import {
Document, Calendar, Box, ShoppingCart, Monitor, Tools,
Operation, Link, DataLine, Search, CircleCheck, Clock, User,
Key, Fold, Expand, Warning, Paperclip, Tickets, Bell, Setting, Van
} from '@element-plus/icons-vue'
import { ElNotification } from 'element-plus'
import NextStepBar from '../components/NextStepBar.vue'
import { getUser, logout } from '../utils/auth'
import request from '../utils/request'
const router = useRouter()
// ===== 响应式侧边栏:桌面可折叠,移动端抽屉 =====
const isCollapse = ref(false) // 桌面端默认展开(汉堡菜单展开态);系统管理分组靠 defaultOpeneds 默认收起
const isMobile = ref(false) // 移动端(≤767px)
const mobileOpen = ref(false) // 移动端抽屉展开
const asideWidth = computed(() => (isMobile.value ? '210px' : isCollapse.value ? '64px' : '210px'))
function toggleAside() {
if (isMobile.value) {
mobileOpen.value = !mobileOpen.value
} else {
isCollapse.value = !isCollapse.value
}
}
function onScreenChange() {
const mq = window.matchMedia('(max-width: 767px)')
isMobile.value = mq.matches
if (!isMobile.value) mobileOpen.value = false
}
// 路由切换后自动收起移动端抽屉
watch(() => router.currentRoute.value.path, () => {
if (isMobile.value) mobileOpen.value = false
})
onMounted(() => {
onScreenChange()
window.addEventListener('resize', onScreenChange)
})
onBeforeUnmount(() => {
window.removeEventListener('resize', onScreenChange)
if (alertTimer) clearInterval(alertTimer)
closeTodoWs()
})
const menus = computed(() => {
const me = getUser()
if (!me) return menuGroups.map((g) => ({ ...g, children: [...g.children] }))
const owned = me.permissionCodes || []
const ok = (c) => me.roleCode === 'SUPER_ADMIN' || owned.includes('*') || owned.includes(c)
return menuGroups
.map((g) => ({ ...g, children: g.children.filter((m) => ok(m.code)) }))
.filter((g) => g.children.length > 0)
})
// 侧栏菜单按业务环节分 7 组:计划与排产 / 产品与工艺 / 现场作业 / 物料与配送 /
// 设备与底层 / AGV与车辆 / 系统管理。组无权限码,子项各自带 code 过滤,组内子项全被过滤则整组隐藏,
// SUPER_ADMIN / '*' 全放行。二级菜单显示名一律沿用拍板名,不发明新词;
// 业务路径与业务页面不动,菜单码与权限种子保持对齐(改名只动显示名,不动 code)。
// AGV管理 / 人工派车 各用独立菜单码 produce.agv / produce.agv.manual;
// 异常告警 / 告警配置 沿用 sys.alert / sys.alertrule 两码,只改显示名。
// 「系统管理」组名保持不变,defaultOpeneds 默认收起它。
const menuGroups = [
{
title: '计划与排产', icon: Calendar, children: [
{ code: 'produce.workorder', name: '工单管理', path: '/work-order', icon: Document },
{ code: 'produce.dailyplan', name: '日排产', path: '/daily-plan', icon: Calendar },
{ code: 'produce.producible', name: '齐套测算', path: '/producible-support', icon: DataLine },
{ code: 'produce.performance', name: '绩效报表', path: '/performance', icon: DataLine }
]
},
{
title: '产品与工艺', icon: Box, children: [
{ code: 'produce.product', name: '成品档案', path: '/product-type', icon: Box },
{ code: 'produce.processflow', name: '产品工艺', path: '/process-flow', icon: Operation },
{ code: 'produce.station', name: '工位管理', path: '/station', icon: Link }
]
},
{
title: '现场作业', icon: Operation, children: [
{ code: 'produce.processcard', name: '生产流程卡', path: '/process-card', icon: Tickets },
{ code: 'produce.wip', name: '在制品追踪', path: '/wip', icon: Clock },
{ code: 'produce.trace', name: '工件追溯', path: '/trace', icon: Search },
{ code: 'sys.inspect', name: '巡检终端', path: '/inspect', icon: CircleCheck },
{ code: 'produce.audit', name: '签字复核', path: '/audit-pending', icon: CircleCheck },
{ code: 'produce.quality', name: '质量检验', path: '/quality', icon: CircleCheck },
{ code: 'produce.trial', name: '成品试验', path: '/trial-register', icon: CircleCheck }
]
},
{
title: '物料与配送', icon: ShoppingCart, children: [
{ code: 'produce.material', name: '叫料单', path: '/material-request', icon: ShoppingCart },
{ code: 'produce.shortage', name: '补料审批', path: '/shortage', icon: ShoppingCart },
{ code: 'produce.qty', name: '收料差异登记', path: '/qty-report', icon: Warning },
{ code: 'produce.loss', name: '损耗台账', path: '/loss-ledger', icon: Warning },
{ code: 'produce.transfer', name: '生产退料', path: '/transfer-return', icon: Van }
]
},
{
title: '设备与底层', icon: Monitor, children: [
{ code: 'produce.line.manage', name: '产线管理', path: '/line-management', icon: Operation },
{ code: 'produce.plc', name: '工位下发', path: '/plc-send', icon: Monitor },
{ code: 'produce.plc.monitor', name: 'PLC管理', path: '/plc-monitor', icon: Monitor },
{ code: 'sys.torqueconfig', name: '拧紧枪配置', path: '/torque-gun-config', icon: Setting }
]
},
{
title: 'AGV与车辆', icon: Van, children: [
{ code: 'produce.agv', name: 'AGV管理', path: '/agv', icon: Van },
{ code: 'produce.agv.manual', name: '人工派车', path: '/agv-manual', icon: Setting }
]
},
{
title: '系统管理', icon: Key, children: [
{ code: 'sys.account', name: '账号管理', path: '/account', icon: User },
{ code: 'sys.role', name: '角色管理', path: '/role', icon: Key },
{ code: 'sys.eventlog', name: '操作日志', path: '/event-log', icon: Clock },
{ code: 'sys.alert', name: '异常告警', path: '/alert-center', icon: Warning },
{ code: 'sys.alertrule', name: '告警配置', path: '/alert-rule', icon: Setting },
{ code: 'sys.syncfailure', name: '同步失败台账', path: '/sync-failure', icon: Warning },
{ code: 'sys.attachment', name: '附件中心', path: '/attachment', icon: Paperclip },
{ code: 'sys.backup', name: '数据归档', path: '/data-archive', icon: Tools },
{ code: 'sys.settings', name: '基础设置', path: '/settings', icon: Setting }
]
}
]
// 默认展开分组:七组菜单除「系统管理」外全部展开(一进系统就能看到每个业务域能干什么);
// 系统管理默认收起,需手动点开。
// 折叠→展开时重建菜单使 default-openeds 重新生效
// (Element Plus 折叠会清空内部 openedMenus,default-openeds 仅在初始化时读取一次,
// 故用 key 变化强制重建实例 —— 同 WMS 的处理)
const collapsedGroups = ['系统管理']
const defaultOpeneds = computed(() =>
menus.value
.map((g) => 'group:' + g.title)
.filter((k) => !collapsedGroups.includes(k.replace('group:', '')))
)
const menuKey = ref(0)
watch(isCollapse, (collapsed) => {
if (!collapsed) menuKey.value++
})
const userName = computed(() => {
const me = getUser()
return me ? (me.name || me.username) : '未登录'
})
onMounted(async () => {
try {
const u = await request.get('/userinfo')
localStorage.setItem('user', JSON.stringify(u))
} catch { /* ignore */ }
// 顶部预警铃铛:立即拉一次未读数,随后每 30s 轮询
pollAlerts()
alertTimer = setInterval(pollAlerts, 30000)
// 菜单待办角标:先拉一次全量统计,再建立 WebSocket 增量通道
await loadTodoStats()
connectTodoWs()
})
// 说明:数据归档清理提醒已从顶栏角标移除,统一由「异常告警」承载
// (后端在备份超期时写入 backup_overdue 预警,处理入口为「数据归档」页)。
const unreadAlerts = ref(0)
let alertTimer = null
let alertInited = false
async function pollAlerts() {
try {
const list = await request.get('/alerts', { params: { status: 'UNREAD' } })
const n = Array.isArray(list) ? list.length : 0
// 首轮仅初始化角标;之后未读数增加时弹提示,避免反复骚扰
if (alertInited && n > unreadAlerts.value) {
ElNotification({
title: '新预警',
message: `有 ${n - unreadAlerts.value} 条新的未读预警,请及时处理`,
type: 'warning',
duration: 5000,
position: 'bottom-right'
})
}
unreadAlerts.value = n
alertInited = true
} catch { /* 忽略轮询异常 */ }
}
// ===== 菜单待办角标:初始化拉全量 + WebSocket 增量推送 =====
// 6 个固定 menuCode → 菜单 path;只给已渲染(即有权限)的菜单项挂角标
const TODO_PATH = {
'produce.call': '/material-request',
'produce.return': '/transfer-return',
'produce.shortage': '/shortage',
'produce.qtyreport': '/qty-report',
'produce.sign': '/audit-pending',
'produce.alert': '/alert-center',
}
const todoCounts = ref({}) // menuCode -> 待办数
function badgeOf(path) {
let n = 0
for (const code in TODO_PATH) {
if (TODO_PATH[code] === path) n += todoCounts.value[code] || 0
}
return n
}
function applyTodoItems(items) {
const map = {}
if (Array.isArray(items)) {
for (const it of items) {
if (it && typeof it.menuCode === 'string') map[it.menuCode] = Number(it.count) || 0
}
}
todoCounts.value = map
}
async function loadTodoStats() {
try {
// request baseURL=/api/v1 → GET /api/v1/todos/stats
const res = await request.get('/todos/stats')
if (res && Array.isArray(res.items)) applyTodoItems(res.items)
} catch { /* 待办统计不可用时不阻塞布局 */ }
}
function todoWsUrl() {
// token 字段名与 utils/auth.js 一致(localStorage 'token')
const token = localStorage.getItem('token') || ''
const proto = window.location.protocol === 'https:' ? 'wss' : 'ws'
return `${proto}://${window.location.host}/api/v1/todos/ws?token=${encodeURIComponent(token)}`
}
let todoWs = null
let todoReconnectTimer = null
let todoRetry = 0
let todoAlive = true
function connectTodoWs() {
if (!todoAlive) return
const token = localStorage.getItem('token') || ''
if (!token) return
let ws
try {
ws = new WebSocket(todoWsUrl())
} catch {
scheduleTodoReconnect()
return
}
todoWs = ws
ws.onopen = () => { todoRetry = 0 }
ws.onmessage = (ev) => {
try {
const msg = JSON.parse(ev.data)
if (msg && Array.isArray(msg.items)) applyTodoItems(msg.items)
} catch { /* 忽略单条异常推送 */ }
}
ws.onerror = () => { /* 交由 onclose 统一重连 */ }
ws.onclose = () => {
if (todoWs === ws) todoWs = null
if (todoAlive) scheduleTodoReconnect()
}
}
function scheduleTodoReconnect() {
if (todoReconnectTimer || !todoAlive) return
const delay = Math.min(30000, 2000 * Math.pow(2, todoRetry))
todoRetry = Math.min(todoRetry + 1, 5)
todoReconnectTimer = setTimeout(() => {
todoReconnectTimer = null
connectTodoWs()
}, delay)
}
function closeTodoWs() {
todoAlive = false
if (todoReconnectTimer) { clearTimeout(todoReconnectTimer); todoReconnectTimer = null }
if (todoWs) {
todoWs.onclose = null
todoWs.close()
todoWs = null
}
}
function goAlertCenter() {
router.push('/alert-center')
}
function doLogout() {
// 尽力通知后端记录"退出登录"操作日志,失败不阻塞本地退出
request.post('/logout').catch(() => {})
logout()
router.replace('/login')
}
// 打开当前页面帮助(PageHelp 监听该全局事件弹出抽屉)
function openHelp() {
window.dispatchEvent(new CustomEvent('mes:open-page-help'))
}
// 生产看板大屏:/board 在路由免登录白名单 publicPaths,无需登录
function openBoard() {
window.open('/board', '_blank')
}
function onUserCmd(cmd) {
if (cmd === 'password') {
router.push('/change-password')
} else if (cmd === 'logout') {
doLogout()
}
}
</script>
<style scoped>
.layout { height: 100vh; }
.aside { background: #001529; transition: width .2s ease; overflow: auto; }
.main { background: #f0f2f5; padding: 14px; overflow: auto; }
.drawer { position: fixed; left: 0; top: 0; bottom: 0; z-index: 1001; transform: translateX(-100%); transition: transform .3s ease; }
.drawer-open { transform: translateX(0); }
.drawer-mask { position: fixed; inset: 0; background: rgba(0, 0, 0, .45); z-index: 1000; }
.logo { display: flex; align-items: center; justify-content: center; gap: 8px; color: #fff; font-size: 17px; font-weight: 600; height: 60px; white-space: nowrap; }
.no-menu { padding: 24px 10px; text-align: center; color: #a6adb4; font-size: 14px; }
.no-menu .sub { margin-top: 6px; font-size: 12px; color: #6b7684; }
.header { display: flex; align-items: center; justify-content: space-between; background: #fff; border-bottom: 1px solid #eee; }
.header-left { display: flex; align-items: center; gap: 8px; min-width: 0; }
.collapse-btn { font-size: 20px; cursor: pointer; color: #303133; display: flex; align-items: center; flex-shrink: 0; }
.collapse-btn:hover { color: #1668dc; }
.page-title { font-size: 16px; font-weight: 600; color: #303133; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.spacer { flex: 1; }
.header-right { display: flex; align-items: center; gap: 6px; flex-shrink: 0; }
.alert-badge { margin-right: 4px; }
.alert-btn { color: #606266; padding: 4px 6px; }
.alert-btn:hover { color: #1668dc; background: #f2f6fc; }
.alert-ring { color: #e6a23c; animation: alert-ring 1.1s ease-in-out infinite; transform-origin: top center; }
@keyframes alert-ring {
0%, 60%, 100% { transform: rotate(0); }
10% { transform: rotate(14deg); }
20% { transform: rotate(-12deg); }
30% { transform: rotate(9deg); }
40% { transform: rotate(-6deg); }
50% { transform: rotate(0); }
}
.board-btn { font-size: 13px; color: #1668dc; }
.board-btn:hover { background: #f2f6fc; }
.help-btn { font-size: 13px; color: #606266; }
.user-name { display: inline-flex; align-items: center; gap: 4px; cursor: pointer; font-size: 14px; color: #303133; outline: none; padding: 4px 6px; border-radius: 4px; }
.user-name:hover { color: #1668dc; background: #f2f6fc; }
.caret { font-size: 10px; color: #909399; }
/* 菜单待办角标:靠右、数量 0 时由 v-if 隐藏 */
.todo-badge { margin-left: auto; flex-shrink: 0; min-width: 18px; height: 18px; line-height: 18px; padding: 0 5px; border-radius: 9px; background: #f56c6c; color: #fff; font-size: 11px; text-align: center; font-variant-numeric: tabular-nums; }
</style>