WMS_PDA/pages/index/index.vue

1689 lines
45 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>
<view class="pda-home">
<view class="status_bar">
</view>
<view class="compact-header">
<!-- 主体切换 -->
<view class="org-switcher">
<view class="org-info" @click="showStoreSelector">
<text class="org-name">{{ userInfo.store_name || '选择主体' }}</text>
<text class="org-id">{{ userInfo.employees_name || '---' }}</text>
</view>
<u-icon @click="showStoreSelector" name="arrow-down" size="16" color="#666" v-if="userInfo.employees && userInfo.employees.length > 1"></u-icon>
<view class="news-wrapper" @click="toNewsPage">
<u-notice-bar :text="newsList[0]" mode="horizontal" bg-color="transparent" color="#666"
:font-size="12" :padding="0" :radius="0" :volume-icon="false" :more-icon="false" :speed="60"
:height="30" :autoplay="true"></u-notice-bar>
</view>
</view>
<!-- 消息区域 -->
<view class="header-actions">
</view>
</view>
<!-- 主内容区 -->
<view class="main-scroll">
<!-- 快捷入口区域 -->
<view class="quick-section">
<view class="section-title-bar">
<view class="title-left">
<text class="section-title">常用功能</text>
<text class="drag-tip" v-if="quickActions.length > 0">长按可排序/移除</text>
<text v-if="quickActionRemoveMode" class="done-btn" @click="exitQuickActionRemoveMode">完成</text>
</view>
<view class="title-right">
<u-icon name="grid" color="#2979ff" size="20"></u-icon>
<text class="edit-btn" @click="toEditPage">全部功能</text>
<text class="divider">|</text>
<text class="page-indicator">{{ currentPage }}/{{ totalPages }}</text>
</view>
</view>
<!-- 3行4列的快捷入口网格 -->
<view class="quick-grid-container">
<!-- 上一页按钮 -->
<view class="nav-arrow left-arrow" @click="prevPage" :class="{ disabled: currentPage === 1 }">
<u-icon name="arrow-left" size="20" color="#666"></u-icon>
</view>
<!-- 网格内容 -->
<view class="quick-grid-wrapper" @touchstart="handleWrapperTouchStart" @touchmove="handleWrapperTouchMove" @touchend="handleWrapperTouchEnd" @touchcancel="handleWrapperTouchEnd">
<!-- 空状态提示 -->
<view class="empty-state" v-if="!isLoading && quickActions.length === 0">
<u-icon name="grid" size="80" color="#ccc"></u-icon>
<text class="empty-text">暂无可用功能</text>
<text class="empty-hint">请联系仓库管理员检查授权</text>
</view>
<view v-else class="quick-page-shell">
<view class="grid-page" :id="`grid-page-${currentPage - 1}`">
<view
class="grid-item grid-slot"
v-for="slot in renderPageSlots"
:key="slot.key"
:class="[
`page-slot-${currentPage - 1}`,
{
'drag-placeholder': slot.action && isDraggingItem(slot.action),
'drag-disabled': dragState.active,
'empty-item': !slot.action
}
]">
<template v-if="slot.action">
<view
class="grid-item-touch-layer"
@longpress.stop.prevent="handleQuickActionLongPress($event, slot.action, currentPage - 1, slot.index)"
@click.stop.prevent="handleGridItemClick(slot.action)"
></view>
<view
v-if="quickActionRemoveMode"
class="remove-action-btn"
@click.stop="removeQuickAction(slot.action)"
>
<text class="remove-action-icon">{{ removeActionIconGlyph }}</text>
</view>
<view class="grid-item-content">
<view class="item-icon-box" :style="{ background: (slot.action.color || '#2979ff') + '15', color: slot.action.color || '#2979ff' }">
<image
v-if="slot.action.isImageIcon"
class="item-icon-image"
:src="slot.action.resolvedIconSource"
mode="aspectFit"
></image>
<text v-else class="item-icon-font" :style="{ color: slot.action.color || '#2979ff' }">{{ slot.action.resolvedIconGlyph || fallbackIconGlyph }}</text>
</view>
<text class="item-name">{{ slot.action.name || '未命名菜单' }}</text>
<u-badge v-if="Number(slot.action.badge || 0) > 0" :count="Number(slot.action.badge || 0)" size="mini"
type="error" :offset="[-3, 3]" class="item-badge"></u-badge>
</view>
</template>
</view>
</view>
</view>
<view
v-show="dragState.active"
class="drag-preview"
:style="dragPreviewStyle"
>
<text v-if="quickActionRemoveMode" class="preview-remove-action-icon">{{ removeActionIconGlyph }}</text>
<view class="item-icon-box" :style="{ background: (dragPreviewSnapshot.color || '#2979ff') + '15', color: dragPreviewSnapshot.color || '#2979ff' }">
<u-icon name="grid" size="26" :color="dragPreviewSnapshot.color || '#2979ff'"></u-icon>
</view>
<text class="item-name" v-text="dragPreviewSnapshot.name || '未命名菜单'"></text>
</view>
</view>
<!-- 下一页按钮 -->
<view class="nav-arrow right-arrow" @click="nextPage"
:class="{ disabled: currentPage === totalPages }">
<u-icon name="arrow-right" size="20" color="#666"></u-icon>
</view>
</view>
<!-- 分页指示器 -->
<view class="pagination-dots">
<view v-for="n in totalPages" :key="n" class="pagination-dot"
:class="{ active: n === currentPage }"></view>
</view>
</view>
<!-- 加载状态 -->
<view class="loading-state" v-if="isLoading">
<text class="loading-text">加载中...</text>
</view>
</view>
</view>
</template>
<script>
import uviewIcons from '@/uni_modules/uview-ui/components/u-icon/icons.js'
const VALID_UVIEW_ICON_NAMES = new Set(
Object.keys(uviewIcons || {}).map(key => String(key).replace(/^uicon-/, ''))
)
export default {
data() {
return {
isLoading: true,
currentPage: 1,
scrollTop: 0,
userInfo: {},
newsList: [
'欢迎使用PDA仓库管理系统',
'请及时处理待办任务',
'祝您工作愉快'
],
unreadCount: 0,
quickActions: [],
pageSize: 12,
FIXED_MENU_KEY: 'fixed_home_menus',
dragTouchStart: null,
dragState: {
active: false,
item: null,
key: '',
originalIndex: -1,
pageIndex: -1,
hoverIndex: -1,
previewX: 0,
previewY: 0,
slotRects: [],
pageRect: null
},
dragPreviewSnapshot: null,
isSavingOrder: false,
quickActionRemoveMode: false,
suppressItemClick: false,
dragPageSwitching: false,
dragPageSnapshot: [],
wrapperGesture: {
startX: 0,
startY: 0,
deltaX: 0,
deltaY: 0,
startTime: 0
}
}
},
computed: {
normalizedQuickActions() {
return Array.isArray(this.quickActions)
? this.quickActions.filter(Boolean).map(item => this.normalizeAction(item))
: [];
},
displayQuickActions() {
if (!this.dragState.active || !this.dragState.key) {
return this.normalizedQuickActions;
}
const sourceActions = this.normalizedQuickActions;
const sourceIndex = sourceActions.findIndex(item => this.getMenuKey(item) === this.dragState.key);
const targetIndex = this.dragState.hoverIndex;
if (sourceIndex < 0 || targetIndex < 0) {
return sourceActions;
}
const projected = [...sourceActions];
const [dragItem] = projected.splice(sourceIndex, 1);
if (!dragItem) {
return sourceActions;
}
projected.splice(Math.min(targetIndex, projected.length), 0, dragItem);
return projected.filter(Boolean);
},
// 分页后的快捷入口
paginatedActions() {
const pages = [];
for (let i = 0; i < this.displayQuickActions.length; i += this.pageSize) {
pages.push(this.displayQuickActions.slice(i, i + this.pageSize));
}
return pages;
},
currentPageItems() {
return (this.paginatedActions[this.currentPage - 1] || []).filter(Boolean);
},
safeCurrentPageSlots() {
const items = this.currentPageItems
.map(item => this.normalizeAction(item))
.filter(Boolean)
.slice(0, this.pageSize);
return Array.from({ length: this.pageSize }, (_, index) => {
const action = items[index] || null;
return {
index,
action,
key: action ? this.getMenuKey(action) : `empty-slot-${this.currentPage}-${index}`
};
});
},
renderPageSlots() {
if (this.dragState.active && Array.isArray(this.dragPageSnapshot) && this.dragPageSnapshot.length) {
return this.dragPageSnapshot;
}
return this.safeCurrentPageSlots;
},
fallbackIconGlyph() {
return uviewIcons['uicon-grid'] || '\ue673';
},
removeActionIconGlyph() {
return uviewIcons['uicon-minus-circle-fill'] || '\ue652';
},
totalPages() {
return Math.ceil(this.displayQuickActions.length / this.pageSize) || 1;
},
dragPreviewStyle() {
return {
left: `${this.dragState.previewX}px`,
top: `${this.dragState.previewY}px`
};
}
},
async onLoad() {
this.dragPreviewSnapshot = this.createDefaultDragPreviewSnapshot();
await this.loadUserInfo();
},
onShow() {
this.loadUserInfo();
},
onUnload() {
this.unbindGlobalDragListeners();
this.clearPendingLongPress();
},
methods: {
async getLatestUserInfo() {
try {
const latestUser = await this.$store.dispatch('getUserInfo');
if (latestUser && typeof latestUser === 'object') {
this.userInfo = latestUser;
return latestUser;
}
} catch (error) {
console.warn('拉取最新用户信息失败,回退本地用户缓存:', error);
}
const fallbackUser = this.$store.getters.user || this.userInfo || null;
if (fallbackUser && typeof fallbackUser === 'object') {
this.userInfo = fallbackUser;
return fallbackUser;
}
return null;
},
createDefaultDragPreviewSnapshot() {
return {
name: '未命名菜单',
color: '#2979ff',
isImageIcon: false,
resolvedIconName: 'grid',
resolvedIconSource: 'grid',
resolvedIconGlyph: this.fallbackIconGlyph || uviewIcons['uicon-grid'] || '\ue673'
};
},
createDragPreviewSnapshot(action) {
const normalized = this.normalizeAction(action);
if (!normalized) {
return this.createDefaultDragPreviewSnapshot();
}
const name = this.sanitizeText(normalized.name, '未命名菜单');
const color = this.sanitizeText(normalized.color, '#2979ff');
const rawSource = this.sanitizeText(normalized.resolvedIconSource, 'grid');
const isImageIcon = Boolean(normalized.isImageIcon) && rawSource.includes('/');
const resolvedIconName = isImageIcon
? 'grid'
: this.sanitizeText(normalized.resolvedIconName, 'grid');
const resolvedIconGlyph = this.sanitizeText(
normalized.resolvedIconGlyph,
uviewIcons[`uicon-${resolvedIconName}`] || this.fallbackIconGlyph || uviewIcons['uicon-grid'] || '\ue673'
);
return {
name,
color,
isImageIcon,
resolvedIconName,
resolvedIconSource: isImageIcon ? rawSource : resolvedIconName,
resolvedIconGlyph
};
},
sanitizeText(value, fallback = '') {
const text = String(value ?? '').trim();
if (!text || text === 'undefined' || text === 'null') {
return fallback;
}
return text;
},
normalizeAction(action) {
if (!action || typeof action !== 'object' || Array.isArray(action)) {
return null;
}
const name = this.sanitizeText(action.name || action.meta?.title, '未命名菜单');
const rawIcon = this.sanitizeText(action.icon || action.meta?.icon, 'grid');
const color = this.sanitizeText(action.color, '#2979ff');
const path = this.sanitizeText(action.path);
const component = this.sanitizeText(action.component);
const id = this.sanitizeText(action.id || action.menuId || component || path || name);
const isImageIcon = String(rawIcon).includes('/');
const resolvedIconName = isImageIcon
? rawIcon
: (() => {
const iconName = this.sanitizeText(rawIcon, 'grid').replace(/^uicon-/, '');
return VALID_UVIEW_ICON_NAMES.has(iconName) ? iconName : 'grid';
})();
const resolvedIconGlyph = isImageIcon
? (uviewIcons['uicon-grid'] || '\ue673')
: (uviewIcons[`uicon-${resolvedIconName}`] || uviewIcons['uicon-grid'] || '\ue673');
const normalized = {
...action,
id,
name,
icon: rawIcon,
color,
badge: Number(action.badge || 0),
path,
component,
resolvedIconName,
resolvedIconSource: resolvedIconName,
resolvedIconGlyph,
isImageIcon
};
return normalized;
},
getActionName(action) {
return this.normalizeAction(action)?.name || '未命名菜单';
},
getActionIcon(action) {
return this.normalizeAction(action)?.resolvedIconName || 'grid';
},
getActionIconSource(action) {
return this.normalizeAction(action)?.resolvedIconSource || 'grid';
},
isActionImageIcon(action) {
return Boolean(this.normalizeAction(action)?.isImageIcon);
},
getActionIconGlyph(action) {
return this.normalizeAction(action)?.resolvedIconGlyph || uviewIcons['uicon-grid'] || '\ue673';
},
getRenderIcon(action, forceStable = false) {
return this.getActionIcon(action);
},
getActionColor(action) {
return this.normalizeAction(action)?.color || '#2979ff';
},
getActionBadge(action) {
return Number(this.normalizeAction(action)?.badge || 0);
},
buildPageSlots(pageIndex, actions = this.displayQuickActions) {
const sourceActions = Array.isArray(actions)
? actions.map(item => this.normalizeAction(item)).filter(Boolean)
: [];
const start = Math.max(pageIndex, 0) * this.pageSize;
const items = sourceActions.slice(start, start + this.pageSize);
return Array.from({ length: this.pageSize }, (_, index) => {
const action = items[index] || null;
return {
index,
action,
key: action ? this.getMenuKey(action) : `drag-empty-slot-${pageIndex}-${index}`
};
});
},
refreshDragPageSnapshot(pageIndex = this.currentPage - 1) {
this.dragPageSnapshot = this.buildPageSlots(pageIndex);
},
ensureCurrentPageInRange() {
const maxPage = Math.max(this.totalPages, 1);
if (this.currentPage > maxPage) {
this.currentPage = maxPage;
}
if (this.currentPage < 1) {
this.currentPage = 1;
}
},
async loadUserInfo() {
await this.refreshQuickActions();
},
// 刷新快捷入口
async refreshQuickActions() {
this.isLoading = true;
try {
const latestUser = await this.getLatestUserInfo();
if (!latestUser) {
console.log('用户信息不可用,快捷入口置空');
this.quickActions = [];
this.ensureCurrentPageInRange();
return;
}
// 1. 获取用户当前可用的菜单
const userMenus = this.getUserMenus(latestUser);
const latestActions = this.processMenus(userMenus, null);
// 2. 从Vuex获取已固定的菜单
const savedFixedMenus = await this.$store.dispatch('setting/getValue', this.FIXED_MENU_KEY);
const hasSavedConfig = Array.isArray(savedFixedMenus);
// 3. 如果存在已保存的常用配置(包括空数组),优先按配置展示
if (hasSavedConfig) {
const validFixedMenus = this.validateAndFilterMenus(savedFixedMenus, latestActions);
console.log('按已保存常用菜单展示:', validFixedMenus);
this.quickActions = validFixedMenus.map(item => this.normalizeAction(item)).filter(Boolean);
this.ensureCurrentPageInRange();
return;
}
// 4. 如果没有有效的固定菜单,检查用户菜单
if (userMenus && userMenus.length > 0) {
console.log('从用户菜单生成快捷入口:', userMenus);
// 首次登录默认带出前12个菜单,并将收货作业、商品查询前置
const defaultQuickActions = this.prioritizeDefaultQuickActions(latestActions, 12);
this.quickActions = defaultQuickActions.map(item => this.normalizeAction(item)).filter(Boolean);
await this.saveQuickActionsOrder();
} else {
// 5. 如果还是没有菜单,返回空数组
console.log('用户没有可用菜单');
this.quickActions = [];
}
this.ensureCurrentPageInRange();
} catch (error) {
console.error('刷新快捷入口失败:', error);
this.quickActions = [];
this.ensureCurrentPageInRange();
} finally {
this.isLoading = false;
}
},
prioritizeDefaultQuickActions(actions, limit = 12) {
const source = Array.isArray(actions) ? actions.filter(Boolean) : [];
if (!source.length) {
return [];
}
const priorities = [
(menuName) => menuName === '收货作业' || (menuName.includes('收货') && menuName.includes('作业')),
(menuName) => menuName === '商品查询' || (menuName.includes('商品') && menuName.includes('查询'))
];
const selectedKeys = new Set();
const prioritized = [];
priorities.forEach((matcher) => {
const matched = source.find((item) => {
const menuName = this.sanitizeText(item?.name || item?.meta?.title);
const key = this.getMenuKey(item);
return key && !selectedKeys.has(key) && matcher(menuName);
});
if (matched) {
const key = this.getMenuKey(matched);
selectedKeys.add(key);
prioritized.push(matched);
}
});
const remaining = source.filter((item) => {
const key = this.getMenuKey(item);
return key && !selectedKeys.has(key);
});
return [...prioritized, ...remaining].slice(0, limit);
},
// 辅助方法:验证和过滤菜单权限
validateAndFilterMenus(fixedMenus, latestActions) {
if (!Array.isArray(fixedMenus) || !Array.isArray(latestActions)) return [];
const actionMap = new Map();
latestActions.forEach(action => {
actionMap.set(this.getMenuKey(action), action);
});
return fixedMenus
.map(fixedMenu => {
const matched = actionMap.get(this.getMenuKey(fixedMenu));
if (!matched) return null;
return this.normalizeAction({
...matched,
...fixedMenu,
name: matched.name,
path: matched.path,
component: matched.component,
icon: matched.icon || fixedMenu.icon,
id: matched.id || fixedMenu.id
});
})
.filter(Boolean);
},
getMenuKey(menu) {
return this.sanitizeText(
menu?.component ||
menu?.path ||
menu?.id ||
menu?.menuId ||
menu?.name ||
'',
''
);
},
getTouchPoint(event) {
const fallbackPoint = event?.detail?.x || event?.detail?.y
? {
pageX: event.detail.x,
pageY: event.detail.y
}
: null;
const touch = event?.touches?.[0] || event?.changedTouches?.[0] || fallbackPoint;
return {
x: Number(touch?.pageX || touch?.clientX || 0),
y: Number(touch?.pageY || touch?.clientY || 0)
};
},
clearPendingLongPress() {
return;
},
bindGlobalDragListeners() {
if (typeof window === 'undefined' || this._globalDragListenersBound) {
return;
}
this._globalTouchMoveHandler = (event) => {
if (!this.dragState.active) {
return;
}
if (typeof event.preventDefault === 'function') {
event.preventDefault();
}
this.onDragMove(event);
};
this._globalTouchEndHandler = (event) => {
if (!this.dragState.active) {
return;
}
this.endDrag(event);
};
window.addEventListener('touchmove', this._globalTouchMoveHandler, { passive: false });
window.addEventListener('touchend', this._globalTouchEndHandler, { passive: false });
window.addEventListener('touchcancel', this._globalTouchEndHandler, { passive: false });
this._globalDragListenersBound = true;
},
unbindGlobalDragListeners() {
if (typeof window === 'undefined' || !this._globalDragListenersBound) {
return;
}
window.removeEventListener('touchmove', this._globalTouchMoveHandler);
window.removeEventListener('touchend', this._globalTouchEndHandler);
window.removeEventListener('touchcancel', this._globalTouchEndHandler);
this._globalTouchMoveHandler = null;
this._globalTouchEndHandler = null;
this._globalDragListenersBound = false;
},
onGridItemTouchMove(event) {
return;
},
onGridItemTouchEnd() {
return;
},
enterQuickActionRemoveMode() {
if (this.dragState.active) {
return;
}
this.quickActionRemoveMode = true;
},
exitQuickActionRemoveMode() {
this.quickActionRemoveMode = false;
},
handleQuickActionLongPress(event, item, pageIndex, index) {
if (!item || this.dragState.active) {
return;
}
this.enterQuickActionRemoveMode();
this.onGridItemLongPress(event, item, pageIndex, index);
},
onGridItemLongPress(event, item, pageIndex, index) {
if (this.dragState.active) {
return;
}
const point = this.getTouchPoint(event);
this.startDragWithPoint(item, pageIndex, index, point);
},
async removeQuickAction(item) {
const targetKey = this.getMenuKey(item);
if (!targetKey) {
return;
}
const nextActions = this.quickActions.filter(action => this.getMenuKey(action) !== targetKey);
if (nextActions.length === this.quickActions.length) {
return;
}
this.quickActions = nextActions;
this.ensureCurrentPageInRange();
if (!this.quickActions.length) {
this.quickActionRemoveMode = false;
}
await this.saveQuickActionsOrder();
uni.showToast({
title: '已移出常用功能',
icon: 'success'
});
const tools = this.$tools;
if (tools && typeof tools.speakText === 'function') {
try {
const task = tools.speakText('已移出常用功能');
if (task && typeof task.catch === 'function') {
task.catch(error => {
console.warn('[HomeIndex] 语音播报失败:', error);
});
}
} catch (error) {
console.warn('[HomeIndex] 语音播报异常:', error);
}
}
},
handleWrapperTouchStart(event) {
if (this.dragState.active) {
return;
}
const point = this.getTouchPoint(event);
this.wrapperGesture = {
startX: point.x,
startY: point.y,
deltaX: 0,
deltaY: 0,
startTime: Date.now()
};
},
handleWrapperTouchMove(event) {
if (!this.dragState.active) {
const point = this.getTouchPoint(event);
this.wrapperGesture.deltaX = point.x - this.wrapperGesture.startX;
this.wrapperGesture.deltaY = point.y - this.wrapperGesture.startY;
return;
}
if (typeof event?.preventDefault === 'function') {
event.preventDefault();
}
if (typeof event?.stopPropagation === 'function') {
event.stopPropagation();
}
this.onDragMove(event);
},
handleWrapperTouchEnd() {
if (this.dragState.active) {
this.endDrag();
return;
}
const { deltaX, deltaY, startTime } = this.wrapperGesture;
const duration = startTime ? (Date.now() - startTime) : 0;
if (duration > 0 && duration < 320 && Math.abs(deltaX) > 50 && Math.abs(deltaX) > Math.abs(deltaY) + 12) {
if (deltaX < 0 && this.currentPage < this.totalPages) {
this.currentPage += 1;
} else if (deltaX > 0 && this.currentPage > 1) {
this.currentPage -= 1;
}
}
this.wrapperGesture = {
startX: 0,
startY: 0,
deltaX: 0,
deltaY: 0,
startTime: 0
};
},
isDraggingItem(item) {
return this.dragState.active && this.getMenuKey(item) === this.dragState.key;
},
async captureCurrentPageSlots(pageIndex) {
return new Promise((resolve) => {
const query = uni.createSelectorQuery().in(this);
query.select(`#grid-page-${pageIndex}`).boundingClientRect();
query.selectAll(`.page-slot-${pageIndex}`).boundingClientRect();
query.exec((res) => {
resolve({
pageRect: res?.[0] || null,
slotRects: res?.[1] || []
});
});
});
},
async startDragWithPoint(item, pageIndex, index, startPoint) {
if (!item || this.dragState.active || this.quickActions.length <= 1) {
return;
}
const point = startPoint || { x: 0, y: 0 };
this.clearPendingLongPress();
this.suppressItemClick = true;
const safeItem = this.normalizeAction(item);
const originalIndex = this.quickActions.findIndex(action => this.getMenuKey(action) === this.getMenuKey(safeItem));
this.dragPreviewSnapshot = this.createDragPreviewSnapshot(safeItem);
this.dragState = {
active: true,
item: safeItem,
key: this.getMenuKey(safeItem),
originalIndex,
pageIndex,
hoverIndex: originalIndex >= 0 ? originalIndex : (pageIndex * this.pageSize + index),
previewX: (point.x || 0) - 60,
previewY: (point.y || 0) - 60,
slotRects: [],
pageRect: null
};
this.refreshDragPageSnapshot(pageIndex);
this.bindGlobalDragListeners();
const { pageRect, slotRects } = await this.captureCurrentPageSlots(pageIndex);
if (!this.dragState.active) {
return;
}
if (pageRect && slotRects && slotRects.length) {
const slotRect = slotRects[index] || slotRects[0];
const dragStartPoint = (point.x || point.y)
? point
: {
x: (slotRect?.left || 0) + ((slotRect?.width || 0) / 2),
y: (slotRect?.top || 0) + ((slotRect?.height || 0) / 2)
};
this.dragState = {
...this.dragState,
previewX: dragStartPoint.x - ((slotRect?.width || 120) / 2),
previewY: dragStartPoint.y - ((slotRect?.height || 120) / 2),
slotRects,
pageRect
};
}
},
getPageAbsoluteIndex(pageIndex, slotIndex) {
const pageStart = pageIndex * this.pageSize;
return Math.min(pageStart + Math.max(slotIndex, 0), this.quickActions.length - 1);
},
async switchDragPage(targetPageIndex, point) {
if (!this.dragState.active || this.dragPageSwitching) {
return false;
}
if (targetPageIndex < 0 || targetPageIndex >= this.totalPages || targetPageIndex === this.dragState.pageIndex) {
return false;
}
this.dragPageSwitching = true;
const fallbackIndex = targetPageIndex < this.dragState.pageIndex
? Math.min(((targetPageIndex + 1) * this.pageSize) - 1, this.quickActions.length - 1)
: Math.min(targetPageIndex * this.pageSize, this.quickActions.length - 1);
let nextHoverIndex = fallbackIndex;
const preciseSlotIndex = this.findClosestSlotIndex(point);
if (preciseSlotIndex >= 0) {
nextHoverIndex = this.getPageAbsoluteIndex(targetPageIndex, preciseSlotIndex);
}
this.dragState = {
...this.dragState,
pageIndex: targetPageIndex,
hoverIndex: nextHoverIndex
};
this.currentPage = targetPageIndex + 1;
this.refreshDragPageSnapshot(targetPageIndex);
await this.$nextTick();
await new Promise(resolve => setTimeout(resolve, 16));
const { pageRect, slotRects } = await this.captureCurrentPageSlots(targetPageIndex);
if (pageRect && slotRects && slotRects.length) {
this.dragState = {
...this.dragState,
pageRect,
slotRects
};
const refreshedSlotIndex = this.findClosestSlotIndex(point);
if (refreshedSlotIndex >= 0) {
this.dragState.hoverIndex = this.getPageAbsoluteIndex(targetPageIndex, refreshedSlotIndex);
this.refreshDragPageSnapshot(targetPageIndex);
}
}
this.dragPageSwitching = false;
return true;
},
async maybeSwitchDragPage(point) {
if (this.dragPageSwitching) {
return true;
}
const pageRect = this.dragState.pageRect;
if (!pageRect) {
return false;
}
const edgeThreshold = 50;
if (point.x <= pageRect.left + edgeThreshold && this.dragState.pageIndex > 0) {
return this.switchDragPage(this.dragState.pageIndex - 1, point);
}
if (point.x >= pageRect.right - edgeThreshold && this.dragState.pageIndex < this.totalPages - 1) {
return this.switchDragPage(this.dragState.pageIndex + 1, point);
}
return false;
},
findClosestSlotIndex(point) {
const { slotRects } = this.dragState;
if (!Array.isArray(slotRects) || !slotRects.length) {
return -1;
}
let closestIndex = -1;
let minDistance = Infinity;
slotRects.forEach((rect, index) => {
if (!rect) {
return;
}
const inside = point.x >= rect.left && point.x <= rect.right && point.y >= rect.top && point.y <= rect.bottom;
if (inside) {
closestIndex = index;
minDistance = 0;
return;
}
if (minDistance === 0) {
return;
}
const centerX = rect.left + rect.width / 2;
const centerY = rect.top + rect.height / 2;
const distance = Math.pow(point.x - centerX, 2) + Math.pow(point.y - centerY, 2);
if (distance < minDistance) {
minDistance = distance;
closestIndex = index;
}
});
return closestIndex;
},
reorderQuickActions(dragKey, targetIndex) {
const fromIndex = this.quickActions.findIndex(item => this.getMenuKey(item) === dragKey);
if (fromIndex < 0) {
return;
}
const maxIndex = Math.max(this.quickActions.length - 1, 0);
const safeTargetIndex = Math.min(Math.max(targetIndex, 0), maxIndex);
if (fromIndex === safeTargetIndex) {
return;
}
const nextActions = [...this.quickActions];
const [movedItem] = nextActions.splice(fromIndex, 1);
if (!movedItem) {
return;
}
nextActions.splice(safeTargetIndex, 0, movedItem);
this.quickActions = nextActions.filter(Boolean);
this.ensureCurrentPageInRange();
},
async onDragMove(event) {
if (!this.dragState.active) {
return;
}
if (typeof event?.preventDefault === 'function') {
event.preventDefault();
}
const point = this.getTouchPoint(event);
this.dragState.previewX = point.x - 60;
this.dragState.previewY = point.y - 60;
const switched = await this.maybeSwitchDragPage(point);
if (switched) {
return;
}
const slotIndex = this.findClosestSlotIndex(point);
if (slotIndex < 0) {
return;
}
const pageStart = this.dragState.pageIndex * this.pageSize;
const targetIndex = Math.min(pageStart + slotIndex, this.quickActions.length - 1);
this.dragState.hoverIndex = targetIndex;
this.refreshDragPageSnapshot(this.dragState.pageIndex);
},
async saveQuickActionsOrder() {
if (this.isSavingOrder) {
return;
}
this.isSavingOrder = true;
try {
const normalizedActions = this.quickActions.map(item => this.normalizeAction(item)).filter(Boolean);
this.quickActions = normalizedActions;
await this.$store.dispatch('setting/setValue', {
key: this.FIXED_MENU_KEY,
value: normalizedActions
});
} catch (error) {
console.error('保存常用功能排序失败:', error);
uni.showToast({
title: '排序保存失败',
icon: 'none'
});
} finally {
this.isSavingOrder = false;
}
},
async endDrag() {
this.clearPendingLongPress();
if (!this.dragState.active) {
this.unbindGlobalDragListeners();
return;
}
const finalHoverIndex = this.dragState.hoverIndex >= 0
? this.dragState.hoverIndex
: this.dragState.originalIndex;
if (finalHoverIndex >= 0 && finalHoverIndex !== this.dragState.originalIndex) {
this.reorderQuickActions(this.dragState.key, finalHoverIndex);
}
if (finalHoverIndex >= 0) {
this.currentPage = Math.floor(finalHoverIndex / this.pageSize) + 1;
}
this.ensureCurrentPageInRange();
this.dragState = {
active: false,
item: null,
key: '',
originalIndex: -1,
pageIndex: -1,
hoverIndex: -1,
previewX: 0,
previewY: 0,
slotRects: [],
pageRect: null
};
this.dragPreviewSnapshot = this.createDefaultDragPreviewSnapshot();
this.dragPageSnapshot = [];
this.dragTouchStart = null;
this.dragPageSwitching = false;
this.unbindGlobalDragListeners();
this.suppressItemClick = false;
await this.saveQuickActionsOrder();
},
handleGridItemClick(item) {
if (this.dragState.active || this.suppressItemClick || this.quickActionRemoveMode) {
return;
}
this.toPath(item);
},
// 获取用户菜单
getUserMenus(userData = null) {
const user = userData || this.userInfo || this.$store.getters.user;
if (!user) return [];
// 从用户信息中获取菜单
return user.menus || user.permissions || [];
},
// 处理菜单数据
processMenus(menus, limit = 24) {
// 1. 展平所有子菜单(使用 flatMap 替代 map + filter)
const allChildren = menus.flatMap(item =>
item.children || [] // 确保 children 存在,否则返回空数组
);
// 2. 过滤有效菜单并限制数量
let validMenus = allChildren.filter(menu =>
menu &&
menu.component &&
menu.component !== 'Layout' &&
menu.meta &&
menu.meta.title
);
if (typeof limit === 'number' && limit > 0) {
validMenus = validMenus.slice(0, limit); // 默认最多显示24个
}
// 3. 生成随机颜色的函数
const generateRandomColor = () => {
const colorPool = [
'#FF6B6B', '#4ECDC4', '#FFD166', '#06D6A0', '#118AB2',
'#EF476F', '#26547C', '#FFD166', '#06D6A0', '#118AB2',
'#7209B7', '#3A86FF', '#FB5607', '#8338EC', '#3A86FF'
];
return colorPool[Math.floor(Math.random() * colorPool.length)];
};
// 4. 转换为目标格式
return validMenus.map(menu => {
return {
id: menu.id || menu.menuId || menu.component || menu.path || menu.meta?.title || '',
name: menu.meta?.title || '未命名菜单',
path: menu.path || '',
component: menu.component || '',
permissions: menu.permissions || [],
icon: menu.meta?.icon || '',
color: generateRandomColor(), // 随机颜色
isFixed: true // 标记为已固定
};
});
},
showStoreSelector() {
if (!this.userInfo.employees || this.userInfo.employees.length <= 1) {
return;
}
// 提取店铺名称列表
const storeList = this.userInfo.employees.map(emp => emp.store_name);
uni.showActionSheet({
itemList: storeList,
success: (res) => {
const selectedIndex = res.tapIndex;
if (selectedIndex >= 0 && selectedIndex < this.userInfo.employees.length) {
const selectedEmployee = this.userInfo.employees[selectedIndex];
this.handleStoreSwitch(selectedEmployee);
}
},
fail: (err) => {
console.log('用户取消选择', err);
}
});
},
async handleStoreSwitch(selectedEmployee) {
try {
// 显示加载中
uni.showLoading({
title: '切换中...',
mask: true
});
const result = await this.$store.dispatch('changeEmployee', selectedEmployee.id);
this.loadUserInfo();
} catch (error) {
uni.hideLoading();
}
},
toPath(item) {
const menuName = String(item?.name || '').trim();
const isGoodsQuery = menuName === '商品查询' || (menuName.includes('商品') && menuName.includes('查询'));
const isOrderPicking = menuName === '订单拣货' || (menuName.includes('订单') && menuName.includes('拣货'));
const isScatterWaveStrategy = menuName === '散单波次策略' || (menuName.includes('散单') && menuName.includes('波次'));
const rawPath = item?.component || item?.path || '';
const normalizedPath = rawPath ? (rawPath.startsWith('/') ? rawPath : `/${rawPath}`) : '';
const isRelocation = menuName === '移库作业' || normalizedPath === '/pages/work/storage/relocation';
if (isRelocation) {
uni.showToast({
title: '该功能只支持在商品查询页面使用!',
icon: 'none',
duration: 2500
});
return;
}
const targetPath = isGoodsQuery
? '/pages/work/product/query'
: (isOrderPicking
? '/pages/work/order/picking'
: (isScatterWaveStrategy ? '/pages/work/order/scatter-wave-strategy' : normalizedPath));
if (!targetPath) {
uni.showToast({
title: '功能暂未开放',
icon: 'none',
duration: 1500
});
return;
}
this.$tools.routerTo(targetPath);
},
toMessagePage() {
uni.navigateTo({
url: '/pages/message/index'
});
},
toNewsPage() {
uni.switchTab({
url: '/pages/oa/index'
});
},
toEditPage() {
uni.navigateTo({
url: '/pages/home/edit-quick-actions'
});
},
prevPage() {
if (this.dragState.active) {
return;
}
if (this.currentPage > 1) {
this.currentPage--;
}
},
nextPage() {
if (this.dragState.active) {
return;
}
if (this.currentPage < this.totalPages) {
this.currentPage++;
}
}
}
}
</script>
<style lang="scss" scoped>
@font-face {
font-family: 'uicon-iconfont';
src: url('https://at.alicdn.com/t/font_2225171_8kdcwk4po24.ttf') format('truetype');
}
.pda-home {
display: flex;
flex-direction: column;
background: #f8f9fa;
}
// 紧凑型头部
.compact-header {
padding:0 20rpx;
background: white;
border-bottom: 1rpx solid #f0f0f0;
.org-switcher {
display: flex;
align-items: center;
margin-bottom: 6px;
.org-icon {
margin-right: 15rpx;
}
.org-info {
flex: 1;
.org-name {
font-size: 28rpx;
font-weight: 600;
color: #333;
display: block;
line-height: 1.4;
}
.org-id {
font-size: 22rpx;
color: #909399;
display: block;
}
}
}
.header-actions {
display: flex;
align-items: center;
justify-content: space-between;
.news-wrapper {
flex: 1;
margin-right: 20rpx;
overflow: hidden;
::v-deep .u-notice-bar {
height: 30rpx !important;
line-height: 30rpx !important;
}
}
.message-bell {
position: relative;
width: 60rpx;
height: 60rpx;
display: flex;
align-items: center;
justify-content: center;
border-radius: 50%;
&:active {
background: #f0f0f0;
}
}
}
}
// 主滚动区域
.main-scroll {
flex: 1;
overflow: hidden;
}
// 快捷入口区域
.quick-section {
padding: 20rpx 20rpx 30rpx;
background: white;
margin: 20rpx;
border-radius: 16rpx;
box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);
.section-title-bar {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 25rpx;
padding-bottom: 15rpx;
border-bottom: 1rpx solid #f0f0f0;
.title-left {
display: flex;
align-items: center;
.section-title {
font-size: 32rpx;
font-weight: 600;
color: #333;
margin-left: 10rpx;
}
.drag-tip {
margin-left: 16rpx;
font-size: 22rpx;
color: #909399;
}
.done-btn {
font-size: 24rpx;
color: #2979ff;
padding: 6rpx 12rpx;
border-radius: 6rpx;
margin-left: 12rpx;
&:active {
background: #f0f7ff;
}
}
}
.title-right {
display: flex;
align-items: center;
.edit-btn {
font-size: 24rpx;
color: #2979ff;
padding: 6rpx 12rpx;
border-radius: 6rpx;
&:active {
background: #f0f7ff;
}
}
.divider {
color: #e0e0e0;
margin: 0 15rpx;
}
.page-indicator {
font-size: 24rpx;
color: #909399;
}
}
}
}
// 网格容器
.quick-grid-container {
display: flex;
align-items: center;
margin-bottom: 20rpx;
.nav-arrow {
width: 20rpx;
height: 60rpx;
display: flex;
align-items: center;
justify-content: center;
border-radius: 50%;
background: #f8f9fa;
&:active:not(.disabled) {
background: #e9ecef;
}
&.disabled {
opacity: 0.3;
}
}
.quick-grid-wrapper {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
position: relative;
.quick-page-shell {
width: 100%;
min-height: 540rpx;
}
.quick-swiper {
width: 100%;
height: 540rpx; // 3行 × 180rpx
&.drag-source-hidden {
opacity: 0.01;
}
}
.grid-page {
display: grid;
grid-template-columns: repeat(4, 1fr);
grid-template-rows: repeat(3, 1fr);
gap: 10rpx;
padding: 0 10rpx;
.grid-item {
height: 170rpx;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
position: relative;
border-radius: 12rpx;
transition: transform 0.18s ease, opacity 0.18s ease, background 0.18s ease;
.grid-item-touch-layer {
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
z-index: 3;
background: transparent;
}
.remove-action-btn {
position: absolute;
top: 8rpx;
right: 8rpx;
z-index: 4;
width: 40rpx;
height: 40rpx;
display: flex;
align-items: center;
justify-content: center;
.remove-action-icon {
font-family: 'uicon-iconfont' !important;
font-size: 44rpx;
line-height: 1;
font-style: normal;
font-weight: normal;
color: #ff4d4f;
display: block;
}
}
.grid-item-content {
position: relative;
z-index: 1;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
width: 100%;
height: 100%;
pointer-events: none;
}
.item-icon-box {
width: 100rpx;
height: 100rpx;
border-radius: 20rpx;
display: flex;
align-items: center;
justify-content: center;
margin-bottom: 12rpx;
.item-icon-image {
width: 52rpx;
height: 52rpx;
}
.item-icon-font {
font-family: 'uicon-iconfont' !important;
font-size: 52rpx;
line-height: 1;
font-style: normal;
font-weight: normal;
display: block;
}
.drag-icon-placeholder {
width: 44rpx;
height: 44rpx;
display: grid;
grid-template-columns: repeat(2, 1fr);
grid-template-rows: repeat(2, 1fr);
gap: 6rpx;
&__dot {
width: 100%;
height: 100%;
background: currentColor;
border-radius: 8rpx;
display: block;
opacity: 0.72;
}
}
}
.item-name {
font-size: 30rpx;
font-weight: bold;
color: #333;
text-align: center;
line-height: 1.3;
padding: 0 5rpx;
}
.item-badge {
position: absolute;
top: 10rpx;
right: 10rpx;
}
&:active {
background: #f8f9fa;
}
&.drag-placeholder {
opacity: 0.2;
transform: scale(0.92);
}
&.drag-disabled {
transition: none;
}
&.empty-item {
opacity: 0;
}
}
}
.drag-preview {
position: fixed;
z-index: 999;
width: 120rpx;
height: 170rpx;
border-radius: 12rpx;
background: rgba(255, 255, 255, 0.96);
box-shadow: 0 12rpx 32rpx rgba(0, 0, 0, 0.16);
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
pointer-events: none;
transform: scale(1.05);
.preview-remove-action-icon {
position: absolute;
top: 8rpx;
right: 8rpx;
font-family: 'uicon-iconfont' !important;
font-size: 44rpx;
line-height: 1;
font-style: normal;
font-weight: normal;
color: #ff4d4f;
display: block;
}
.item-icon-box {
width: 100rpx;
height: 100rpx;
border-radius: 20rpx;
display: flex;
align-items: center;
justify-content: center;
margin-bottom: 12rpx;
.item-icon-image {
width: 52rpx;
height: 52rpx;
}
.item-icon-font {
font-family: 'uicon-iconfont' !important;
font-size: 52rpx;
line-height: 1;
font-style: normal;
font-weight: normal;
display: block;
}
}
.item-name {
font-size: 26rpx;
font-weight: bold;
color: #333;
text-align: center;
line-height: 1.3;
padding: 0 6rpx;
}
}
.drag-grid-layer {
position: absolute;
left: 0;
top: 0;
right: 0;
z-index: 5;
}
}
}
// 分页指示器
.pagination-dots {
display: flex;
justify-content: center;
margin-top: 20rpx;
.pagination-dot {
width: 10rpx;
height: 10rpx;
border-radius: 50%;
background: #e0e0e0;
margin: 0 6rpx;
&.active {
background: #2979ff;
width: 30rpx;
border-radius: 5rpx;
}
}
}
// 加载状态
.loading-state {
padding: 100rpx 0;
display: flex;
flex-direction: column;
align-items: center;
.loading-text {
margin-top: 20rpx;
color: #909399;
font-size: 24rpx;
}
}
// 空状态提示
.empty-state {
padding: 80rpx 0;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
.empty-text {
display: block;
font-size: 32rpx;
color: #999;
margin-top: 30rpx;
margin-bottom: 15rpx;
}
.empty-hint {
display: block;
font-size: 26rpx;
color: #ccc;
}
}
</style>