Commit 41e38b7e by liimin

feat(store-switch): 重构门店切换流程,优化全局同步体验

- 新增全局门店切换广播事件,实现多页面自动同步门店信息
- 抽离通用门店选择组件与组合式函数,提升代码复用性
- 优化门店选择交互,改为底部抽屉弹窗而非页面跳转
- 修复storage工具类的类型安全与防御性检查问题
- 调整项目配置与页面样式,比如禁用APP端页面回弹、优化首页模块高度
1 parent 49a74733
<template>
<un-popup :show="visible"
mode="bottom"
closeOnClickOverlay
:z-index="10090"
:closeable="true"
@close="handleClose">
<view class="switch-store-sheet" :style="sheetStyle">
<view class="switch-store-header">
<view class="switch-store-header-bar"></view>
<view class="switch-store-header-text">
<text class="switch-store-header-title">切换门店</text>
<text class="switch-store-header-desc">选择门店后自动返回当前页面</text>
</view>
</view>
<view v-if="stores.length > 0" class="switch-store-summary">
<view class="switch-store-summary-card">
<text class="switch-store-summary-label">当前门店</text>
<text class="switch-store-summary-value">{{ currentStoreDisplayName }}</text>
</view>
<view class="switch-store-summary-count">
<text class="switch-store-summary-count-label">可切换</text>
<text class="switch-store-summary-count-value">{{ stores.length }}</text>
</view>
</view>
<view v-if="stores.length == 0" class="switch-store-empty">
<text class="switch-store-empty-text">暂无可用门店</text>
</view>
<StoreGrid
v-else
class="store-grid-flex"
:stores="stores"
:selectedStoreCode="selectedStoreCode"
:currentStoreCode="originalStoreCode"
@select="onGridSelect" />
</view>
</un-popup>
</template>
<script setup lang="uts">
import { ref, computed, watch } from "vue";
import { toObj, type AnyOrNull } from "@/utils/common.uts";
import StoreGrid from "@/pages/common/selectStore/StoreGrid.uvue";
import {
useStoreSelection,
readStoreListFromStorage,
getStoreCode,
getStoreName
} from "@/pages/common/selectStore/useStoreSelection";
type Props = {
visible?: boolean
}
const props = withDefaults(defineProps<Props>(), {
visible: false
});
const emit = defineEmits<{
"update:visible": [value: boolean]
"switched": [store: UTSJSONObject]
}>();
const {
stores,
selectedStoreCode,
currentStoreCode,
loadCurrentStoreInfo,
selectStore,
setStores
} = useStoreSelection();
/** 打开抽屉时的原始门店 code,用于标记"当前"标签 */
const originalStoreCode = ref<string>("");
/** 抽屉整体固定高度:屏幕高度 × 70% */
const sheetStyle = computed((): UTSJSONObject => {
const info = uni.getWindowInfo();
const sheetH = Math.round(info.windowHeight * 0.7);
return { "height": `${sheetH}px` } as UTSJSONObject;
});
const currentStoreDisplayName = computed((): string => {
const code = originalStoreCode.value;
if (code === "") {
return "未选择门店";
}
for (let i = 0; i < stores.value.length; i++) {
const item = stores.value[i];
if (getStoreCode(item) == code) {
const name = getStoreName(item);
return name !== "" ? name : "当前门店";
}
}
return "当前门店";
});
function handleClose(): void {
emit("update:visible", false);
}
/** 打开抽屉时加载数据 */
watch((): boolean => props.visible, (val: boolean) => {
if (val) {
const arr = readStoreListFromStorage("pendingShukeStores");
setStores(arr);
// loadCurrentStoreInfo 会自动设置 currentStoreInfo 和 selectedStoreCode
loadCurrentStoreInfo();
// 记录原始门店 code(用于标记"当前"标签)
originalStoreCode.value = currentStoreCode.value;
}
});
/** StoreGrid 选中回调 */
function onGridSelect(item: any, _index: number): void {
if (item == null) return;
// 如果选中原始门店,直接关闭
const code = currentStoreCode.value;
if (code !== "") {
const itemCode = getStoreCode(item);
if (itemCode !== "" && itemCode == code) {
handleClose();
return;
}
}
// 使用共享的选择逻辑(更新选中状态 + 保存 storeInfo)
const ok = selectStore(item);
if (!ok) return;
// 通知父组件门店已切换
const o = toObj(item);
emit("switched", o);
handleClose();
}
</script>
<style scoped lang="scss">
.switch-store-sheet {
width: 100%;
padding: 20px 16px 24px;
box-sizing: border-box;
background: #ffffff;
border-top-left-radius: 20px;
border-top-right-radius: 20px;
display: flex;
flex-direction: column;
overflow: hidden;
}
.switch-store-header {
flex-direction: row;
align-items: center;
margin-bottom: 16px;
}
.switch-store-header-bar {
width: 4px;
height: 24px;
border-radius: 2px;
background: #2563eb;
margin-right: 12px;
}
.switch-store-header-text {
flex: 1;
}
.switch-store-header-title {
font-size: 18px;
font-weight: 700;
color: #0f172a;
}
.switch-store-header-desc {
font-size: 12px;
color: #94a3b8;
margin-top: 2px;
}
.switch-store-summary {
flex-shrink: 0;
display: flex;
flex-direction: row;
align-items: stretch;
margin-bottom: 14px;
}
.switch-store-summary-card {
flex: 1;
min-width: 0;
border-radius: 16px;
background-color: #f8fbff;
border-width: 1px;
border-style: solid;
border-color: #dbeafe;
padding: 12px 14px;
box-sizing: border-box;
}
.switch-store-summary-label {
font-size: 12px;
line-height: 16px;
color: #64748b;
}
.switch-store-summary-value {
margin-top: 6px;
font-size: 15px;
line-height: 20px;
font-weight: 700;
color: #0f172a;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.switch-store-summary-count {
flex-shrink: 0;
width: 84px;
margin-left: 10px;
border-radius: 16px;
background-color: #eff6ff;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
box-sizing: border-box;
}
.switch-store-summary-count-label {
font-size: 11px;
line-height: 14px;
color: #64748b;
}
.switch-store-summary-count-value {
margin-top: 4px;
font-size: 22px;
line-height: 26px;
font-weight: 700;
color: #2563eb;
}
.switch-store-empty {
padding: 40px 0;
align-items: center;
}
.switch-store-empty-text {
font-size: 14px;
color: #999;
}
.store-grid-flex {
flex: 1;
min-height: 0;
width: 100%;
}
</style>
......@@ -39,7 +39,7 @@
<!-- ✅ 切换门店按钮 -->
<view class="hf-landscape-footer-btn"
@tap="emit('switchStore')">
@tap="handleSwitchStore">
<image class="hf-landscape-footer-icon"
mode="aspectFit"
src="/static/images/home/scene-change.png" />
......@@ -73,6 +73,7 @@ const emit = defineEmits<{
tabChange: [name: string | number]
setting: []
jumpPersonCenter: []
/** 切换门店:打开弹窗 */
switchStore: []
}>();
......@@ -91,6 +92,10 @@ onMounted(() => {
function onTabItemClick(index: number): void {
emit("tabChange", index);
}
function handleSwitchStore(): void {
emit("switchStore");
}
</script>
<style scoped lang="scss">
......
......@@ -25,7 +25,12 @@
</view>
<!-- ✅ 统一的设置弹窗(横竖屏共用) -->
<SettingBox :visible="showSetting"
@update:visible="onSettingVisible" />
@update:visible="onSettingVisible"
@switch-store="onSwitchStore" />
<!-- ✅ 切换门店抽屉 -->
<SwitchStoreSheet :visible="showSwitchStore"
@update:visible="onSwitchStoreVisible"
@switched="onSwitchStoreDone" />
</layout-root>
</template>
......@@ -33,6 +38,7 @@
import { computed, onMounted, onShow, type Ref } from "vue";
import SettingBox from "@/pages/person/SettingBox.uvue";
import SwitchStoreSheet from "@/components/SwitchStoreSheet.uvue";
import { updateOrientation, useOrientation } from "@/services/adapter/hooks/index.uts";
import { requestRecordPermission } from "@/utils/permission.uts";
import { storage } from "@/utils/storage.uts";
......@@ -89,10 +95,13 @@ const tabbarSource: HomeFrameTabbarSource = {
const _tabbar = useHomeFrameTabbar(tabbarSource);
const userName = _tabbar.userName;
const showSetting = _tabbar.showSetting;
const showSwitchStore = _tabbar.showSwitchStore;
const onSettingVisible = _tabbar.onSettingVisible;
const onSetting = _tabbar.onSetting;
const jumpPersonCenter = _tabbar.jumpPersonCenter;
const onSwitchStore = _tabbar.onSwitchStore;
const onSwitchStoreVisible = _tabbar.onSwitchStoreVisible;
const onSwitchStoreDone = _tabbar.onSwitchStoreDone;
/** 统一处理 tab 切换:导航页面 + 转发事件给外部 */
function onTabChange(name: string | number): void {
......
import { computed, ref } from "vue";
import { hideNativeTabBar } from "@/utils/tabBarShell.uts";
import { navigateToSelectStoreWithSessionStores } from "@/utils/shukeSelectStoreNav.uts";
export type HomeFrameTabbarSource = {
getTabIndex: () => number
......@@ -141,6 +140,7 @@ export function navigateToTab(index: number, currentTabIndex: number): void {
export function useHomeFrameTabbar(source: HomeFrameTabbarSource) {
const showSetting = ref(false);
const showSwitchStore = ref(false);
const currentTabIndex = computed((): number => {
return source.getTabIndex();
......@@ -171,27 +171,30 @@ export function useHomeFrameTabbar(source: HomeFrameTabbarSource) {
uni.navigateTo({ url: "/pages/person/attendance" });
};
/** 横屏侧栏底栏「切换」:进选店页(非 tab) */
const onSwitchStore = async (): Promise<void> => {
try {
uni.showLoading({ title: "加载中", mask: true });
await navigateToSelectStoreWithSessionStores();
} catch (error) {
const msg = error != null ? `${error}` : "操作失败";
uni.showToast({ title: msg, icon: "none" });
} finally {
uni.hideLoading();
}
const onSwitchStore = (): void => {
showSwitchStore.value = true;
};
const onSwitchStoreVisible = (v: boolean): void => {
showSwitchStore.value = v;
};
const onSwitchStoreDone = (_store: UTSJSONObject): void => {
showSwitchStore.value = false;
showSetting.value = false;
};
return {
showSetting,
showSwitchStore,
currentTabIndex,
userName,
onTabChange,
onSettingVisible,
onSetting,
jumpPersonCenter,
onSwitchStore
onSwitchStore,
onSwitchStoreVisible,
onSwitchStoreDone
};
}
......@@ -158,7 +158,13 @@
"pageOrientation": "auto",
// ✅ 性能优化:使用淡入淡出动画,减少 GPU 负载
"animationType": "fade-in",
"animationDuration": 150
"animationDuration": 150,
"app-plus": {
"bounce": "none"
}
},
"style": {
"allowsBounceVertical": "NO"
},
"tabBar": {
"color": "#8a98b5",
......
<template>
<view class="store-card"
:class="[
isSelected ? 'store-card-active' : '',
isPressed ? 'store-card-pressed' : '',
isCurrent ? 'store-card-current' : ''
]"
:style="safeCardStyle"
@touchstart="onTouchStart"
@touchend="onTouchEnd"
@click="onTap">
<view class="store-card-accent"></view>
<view class="store-card-main">
<view class="store-card-top">
<text class="store-card-title">{{ storeName }}</text>
<view class="store-card-top-right">
<view v-if="isCurrent" class="store-card-current-badge">
<text class="store-card-current-badge-text">当前</text>
</view>
<view class="store-card-check"
:class="[isSelected ? 'store-card-check-active' : '']">
<view v-if="isSelected" class="store-card-check-dot"></view>
</view>
</view>
</view>
<view class="store-card-meta-panel">
<view class="store-card-meta-inline">
<text class="store-card-code-label">编号</text>
<text class="store-card-code-value">{{ storeCode }}</text>
<text v-if="storePhone !== ''" class="store-card-inline-sep">|</text>
<text v-if="storePhone !== ''" class="store-card-meta-inline-phone">{{ storePhone }}</text>
</view>
<text v-if="storeAddr !== ''" class="store-card-addr">{{ storeAddr }}</text>
</view>
</view>
</view>
</template>
<script setup lang="uts">
import { computed } from "vue";
type Props = {
storeName: string
storeCode: string
storeAddr?: string
storePhone?: string
isSelected?: boolean
isPressed?: boolean
isCurrent?: boolean
cardStyle?: UTSJSONObject | null
}
const props = withDefaults(defineProps<Props>(), {
storeAddr: "",
storePhone: "",
isSelected: false,
isPressed: false,
isCurrent: false,
cardStyle: null
});
/** 处理 null,给 :style 一个非 null 的 UTSJSONObject */
const safeCardStyle = computed((): UTSJSONObject => {
if (props.cardStyle != null) {
return props.cardStyle!;
}
return {} as UTSJSONObject;
});
const emit = defineEmits<{
"select": []
"touchstart": []
"touchend": []
}>();
function onTap(): void {
emit("select");
}
function onTouchStart(): void {
emit("touchstart");
}
function onTouchEnd(): void {
emit("touchend");
}
</script>
<style scoped lang="scss">
.store-card {
width: 100%;
min-height: var(--store-card-min-height, 84px);
background-color: #ffffff;
border-radius: 14px;
padding: 10px 12px;
display: flex;
flex-direction: column;
justify-content: center;
box-sizing: border-box;
border-width: 1px;
border-style: solid;
border-color: #e9eef5;
position: relative;
overflow: hidden;
pointer-events: auto;
box-shadow: 0 2px 8px rgba(15, 23, 42, 0.03);
}
.store-card-pressed {
opacity: 0.96;
}
.store-card-active {
background-color: #f7faff;
border-color: #5b8def;
box-shadow: 0 6px 14px rgba(44, 102, 247, 0.08);
}
.store-card-current {
border-color: #cfe0fb;
}
.store-card-accent {
position: absolute;
left: 0;
top: 8px;
bottom: 8px;
width: 3px;
border-radius: 0 2px 2px 0;
background-color: #2c66f7;
opacity: var(--accent-opacity, 0);
}
.store-card-main {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
justify-content: center;
}
.store-card-top {
display: flex;
flex-direction: row;
align-items: center;
justify-content: space-between;
}
.store-card-current-badge {
height: 18px;
padding: 0 6px;
border-radius: 9px;
background-color: #edf4ff;
display: flex;
flex-direction: row;
align-items: center;
justify-content: center;
box-sizing: border-box;
}
.store-card-current-badge-text {
font-size: 10px;
line-height: 12px;
font-weight: 700;
color: #2c66f7;
}
.store-card-title {
font-size: 16px;
line-height: 20px;
font-weight: 700;
color: #0f172a;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
flex: 1;
min-width: 0;
padding-right: 10px;
}
.store-card-top-right {
flex-shrink: 0;
display: flex;
flex-direction: row;
align-items: center;
}
.store-card-check {
width: 16px;
height: 16px;
margin-left: 6px;
border-radius: 8px;
border-width: 1.5px;
border-style: solid;
border-color: #cbd5e1;
background-color: #ffffff;
display: flex;
flex-direction: row;
align-items: center;
justify-content: center;
box-sizing: border-box;
}
.store-card-check-active {
border-color: #2c66f7;
background-color: #eaf2ff;
}
.store-card-check-dot {
width: 6px;
height: 6px;
border-radius: 3px;
background-color: #2c66f7;
}
.store-card-meta-panel {
margin-top: 4px;
display: flex;
flex-direction: column;
box-sizing: border-box;
}
.store-card-meta-inline {
display: flex;
flex-direction: row;
align-items: center;
}
.store-card-code-label {
flex-shrink: 0;
font-size: 11px;
line-height: 14px;
color: #94a3b8;
margin-right: 4px;
}
.store-card-code-value {
flex-shrink: 1;
min-width: 0;
font-size: 11px;
line-height: 14px;
font-weight: 700;
color: #334155;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.store-card-inline-sep {
flex-shrink: 0;
font-size: 11px;
line-height: 14px;
color: #94a3b8;
margin-left: 6px;
margin-right: 6px;
}
.store-card-meta-inline-phone {
flex-shrink: 1;
min-width: 0;
font-size: 11px;
line-height: 14px;
color: #64748b;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.store-card-addr {
margin-top: 3px;
font-size: 11px;
line-height: 14px;
color: #64748b;
lines: 1;
text-overflow: ellipsis;
overflow: hidden;
}
</style>
<template>
<list-view class="store-scroll" :show-scrollbar="false" :rebound="false">
<list-item>
<view class="grid-container" :style="columnCssVars">
<view v-for="(item, index) in stores"
:key="_getStoreCodeField(item)"
class="grid-item">
<StoreCard
:store-name="_getStoreNameField(item)"
:store-code="_getStoreCodeField(item)"
:store-addr="_getStoreAddr(item)"
:store-phone="_getStorePhone(item)"
:is-selected="selectedStoreCode == _getStoreCodeField(item)"
:is-current="_isCurrent(item)"
:is-pressed="pressedIndex == index"
:card-style="getCardStyle(item)"
@select="onSelect(item, index)"
@touchstart="onTouchStart(index)"
@touchend="onTouchEnd" />
</view>
</view>
</list-item>
</list-view>
</template>
<script setup lang="uts">
import { ref } from "vue";
import { useColumnLayout } from "@/services/adapter/hooks";
import StoreCard from "./StoreCard.uvue";
import { getStoreCodeField, getStoreNameField, getStoreCode, getStoreAddr, getStorePhone } from "./useStoreSelection";
type Props = {
stores: any[]
selectedStoreCode: string
/** 当前已登录的门店 code,用于标记"当前"标签(应用内切换场景) */
currentStoreCode?: string
}
const props = withDefaults(defineProps<Props>(), {
currentStoreCode: ""
});
const emit = defineEmits<{
"select": [item: any, index: number]
}>();
const { cssVars: columnCssVars } = useColumnLayout();
const pressedIndex = ref<number>(-1);
/** 模板包装函数(UTS 模板不支持直接调用导入的外部函数) */
function _getStoreCodeField(item: any): string {
return getStoreCodeField(item);
}
function _getStoreNameField(item: any): string {
return getStoreNameField(item);
}
function _getStoreAddr(item: any): string {
return getStoreAddr(item);
}
function _getStorePhone(item: any): string {
return getStorePhone(item);
}
function _isCurrent(item: any): boolean {
if (props.currentStoreCode === "") return false;
const code = getStoreCode(item);
return code !== "" && code == props.currentStoreCode;
}
function getCardStyle(item: any): UTSJSONObject {
const code = _getStoreCodeField(item);
const isSelected = props.selectedStoreCode == code;
return {
"--accent-opacity": isSelected ? "1" : "0"
} as UTSJSONObject;
}
function onTouchStart(index: number): void {
pressedIndex.value = index;
}
function onTouchEnd(): void {
pressedIndex.value = -1;
}
function onSelect(item: any, index: number): void {
emit("select", item, index);
}
</script>
<style scoped lang="scss">
.store-scroll {
flex: 1;
min-height: 0;
height: 0;
width: 100%;
box-sizing: border-box;
}
.grid-container {
display: flex;
flex-direction: row;
flex-wrap: wrap;
width: 100%;
padding-top: 2px;
padding-bottom: 2px;
box-sizing: border-box;
margin-left: var(--grid-row-margin-left, 0px);
margin-right: var(--grid-row-margin-right, 0px);
}
.grid-item {
width: var(--column-width, 100%);
flex-shrink: 0;
box-sizing: border-box;
padding-left: var(--grid-cell-padding-left, 0px);
padding-right: var(--grid-cell-padding-right, 0px);
padding-bottom: 6px;
}
</style>
......@@ -5,19 +5,19 @@ export default {
'--store-section-gap': '12px',
'--store-panel-radius': '18px',
'--store-panel-padding': '14px',
'--store-card-radius': '16px',
'--store-card-min-height': '92px',
'--store-card-radius': '14px',
'--store-card-min-height': '84px',
'--store-title-size': '24px',
'--store-subtitle-size': '13px',
'--store-stat-width': '120px',
'--store-stat-width': '146px',
'--store-banner-layout': 'row',
},
portrait: {
'--store-page-padding-x': '14px',
'--store-page-padding-y': '12px',
'--store-banner-layout': 'column',
'--store-stat-width': '100%',
'--store-banner-layout': 'row',
'--store-stat-width': '126px',
},
landscape: {
......@@ -32,21 +32,23 @@ export default {
'--store-page-padding-x': '12px',
'--store-page-padding-y': '10px',
'--store-panel-padding': '12px',
'--store-title-size': '22px'
'--store-title-size': '22px',
'--store-stat-width': '118px'
},
'portrait-414x736': {
'--store-page-padding-x': '12px',
'--store-page-padding-y': '10px'
'--store-page-padding-y': '10px',
'--store-stat-width': '118px'
},
'landscape-816x393': {
'--store-page-padding-x': '10px',
'--store-page-padding-y': '8px',
'--store-panel-padding': '10px',
'--store-card-min-height': '82px',
'--store-stat-width': '112px'
'--store-card-min-height': '78px',
'--store-stat-width': '136px'
},
'landscape-1024x640': {
'--store-stat-width': '120px'
'--store-stat-width': '146px'
},
'landscape-1174x768': {
'--store-page-padding-x': '20px',
......
import { ref, nextTick, type Ref } from "vue";
import { storage } from "@/utils/storage.uts";
import { notifyStoreSwitched } from "@/utils/storeSwitchEvents.uts";
import { toStr, toObj, isEmptyStr, isNotEmptyStr, type AnyOrNull, type ObjOrNull, type StrOrNull, type AnyArrOrNull } from "@/utils/common.uts";
/** Composable 返回类型,供 UTS 编译器正确推断解构 */
export type UseStoreSelectionReturn = {
stores: Ref<any[]>
selectedStoreCode: Ref<string>
currentStoreCode: Ref<string>
selectedStore: Ref<any | null>
currentStoreInfo: Ref<UTSJSONObject | null>
loadCurrentStoreInfo: () => void
isCurrentStore: (item: AnyOrNull) => boolean
selectStore: (item: AnyOrNull) => boolean
loadStoresData: (options: ObjOrNull) => Promise<void>
setStores: (list: any[]) => void
parseStoresFromOptions: (options: ObjOrNull) => AnyArrOrNull
}
/**
* 门店选择共享逻辑 composable
*
* 供 selectStore 页面(登录流程)和 SwitchStoreSheet(应用内切换)共用。
* 包含:数据读取/归一化、门店字段提取、当前门店检测、选择处理。
*/
// ─── 门店字段提取工具函数 ───
export function getStoreCode(item: AnyOrNull): string {
if (item == null) {
return "";
}
const o = toObj(item);
const c1 = toStr(o["storeCode"]);
if (isNotEmptyStr(c1)) {
return c1;
}
const c2 = toStr(o["spCode"]);
return c2 != null ? c2 : "";
}
export function getStoreName(item: AnyOrNull): string {
if (item == null) {
return "";
}
const o = toObj(item);
return toStr(o["storeName"]);
}
export function getStoreCodeField(item: AnyOrNull): string {
if (item == null) {
return "";
}
const o = toObj(item);
return toStr(o["_code"]);
}
export function getStoreNameField(item: AnyOrNull): string {
if (item == null) {
return "";
}
const o = toObj(item);
return toStr(o["_name"]);
}
export function getStoreId(item: AnyOrNull): string {
if (item == null) return "";
const o = toObj(item);
return toStr(o["storeId"]);
}
export function getStoreAddr(item: AnyOrNull): string {
if (item == null) return "";
const o = toObj(item);
return toStr(o["storeAddr"]);
}
export function getStorePhone(item: AnyOrNull): string {
if (item == null) return "";
const o = toObj(item);
const tel = toStr(o["storeTel"]);
if (tel !== "") return tel;
return toStr(o["phone"]);
}
// ─── 数据归一化 ───
/** 同步处理门店数据(用于小数据量或需要立即完成的场景) */
export function normalizeStoreList(list: any[]): any[] {
const result: any[] = [];
for (let i = 0; i < list.length; i++) {
const item = list[i];
const o = toObj(item);
let code = "";
const c1 = toStr(o["storeCode"]);
if (c1 != null && c1 !== "") {
code = c1;
} else {
const c2 = toStr(o["spCode"]);
code = c2 != null ? c2 : "";
}
const name = toStr(o["storeName"]);
o["_code"] = code;
o["_name"] = name;
result.push(item);
}
return result;
}
/** 异步分批处理门店数据(动态递增 batchSize,平衡首屏速度和总时间) */
export function normalizeStoreListAsync(list: any[]): Promise<any[]> {
return new Promise((resolve) => {
const result: any[] = [];
let currentIndex = 0;
let batchIndex = 0;
const getBatchSize = (index: number): number => {
if (index == 0) return 5;
if (index == 1) return 20;
if (index == 2) return 40;
return 60;
};
function processBatch(): void {
const batchSize = getBatchSize(batchIndex);
const endIndex = Math.min(currentIndex + batchSize, list.length);
for (let i = currentIndex; i < endIndex; i++) {
const item = list[i];
const o = toObj(item);
let code = "";
const c1 = toStr(o["storeCode"]);
if (c1 != null && c1 !== "") {
code = c1;
} else {
const c2 = toStr(o["spCode"]);
code = c2 != null ? c2 : "";
}
const n = toStr(o["storeName"]);
const name = n != null ? n : "";
o["_code"] = code;
o["_name"] = name;
result.push(item);
}
currentIndex = endIndex;
batchIndex++;
if (currentIndex < list.length) {
void nextTick(() => {
processBatch();
});
} else {
resolve(result);
}
}
processBatch();
});
}
// ─── Storage 读取 ───
/** 兼容 storage 中 JSON 字符串和数组两种格式 */
export function readStoreListFromStorage(key: string): any[] {
const raw = storage.get(key);
if (raw == null) {
return [];
}
if (typeof raw === "string") {
try {
const parsed = JSON.parse(raw as string);
if (Array.isArray(parsed)) {
return parsed as any[];
}
} catch (e) {
console.error(`[readStoreListFromStorage] JSON 解析失败:`, e);
}
return [];
}
if (Array.isArray(raw)) {
return raw as any[];
}
return [];
}
// ─── 选择完成后的默认处理:保存门店信息到 storage ───
function saveStoreInfo(item: AnyOrNull): void {
if (item == null) return;
const storeObj = toObj(item);
const storeId = toStr(storeObj["storeId"]);
const storeName = getStoreName(item);
const storeCode = getStoreCode(item);
const storeAddr = getStoreAddr(item);
const storeTel = getStorePhone(item);
const nextStoreInfo = {
storeId: storeId,
storeName: storeName,
storeCode: storeCode,
storeAddr: storeAddr,
storeTel: storeTel
} as UTSJSONObject;
storage.set("storeInfo", nextStoreInfo, 0);
// 同步 userInfo 中的门店字段,保证首页/我的/业务页读取一致
const userInfo = storage.getUserInfo();
userInfo["currentStoreId"] = storeId;
userInfo["shopMerchantId"] = storeId;
userInfo["shopMerchantName"] = storeName !== "" ? storeName : "门店";
storage.set("userInfo", userInfo, 0);
notifyStoreSwitched(nextStoreInfo);
}
// ─── Composable 主函数 ───
export function useStoreSelection(): UseStoreSelectionReturn {
const stores = ref<any[]>([]);
const selectedStoreCode = ref<string>("");
/** 当前门店 code(从 storage 加载,用于标记"当前"标签) */
const currentStoreCode = ref<string>("");
const selectedStore = ref<any | null>(null);
const currentStoreInfo = ref<UTSJSONObject | null>(null);
/** 加载当前门店信息(用于标记"当前门店",同时自动设置 selectedStoreCode) */
function loadCurrentStoreInfo(): void {
const raw = storage.get("storeInfo");
if (raw == null) {
currentStoreInfo.value = null;
return;
}
let info: UTSJSONObject | null = null;
if (typeof raw === "string") {
try {
info = JSON.parse(raw as string) as UTSJSONObject;
} catch (_e) {
info = null;
}
} else {
info = toObj(raw);
}
currentStoreInfo.value = info;
// 自动设置当前门店 code(用于标记"当前"标签)
if (info != null) {
const code = toStr(info["storeCode"]);
if (code !== "") {
currentStoreCode.value = code;
selectedStoreCode.value = code;
}
}
}
/** 判断是否为当前门店 */
function isCurrentStore(item: AnyOrNull): boolean {
const current = currentStoreInfo.value;
if (current == null) return false;
const currentCode = getStoreCode(current);
const itemCode = getStoreCode(item);
if (currentCode !== "" && currentCode == itemCode) return true;
const currentId = getStoreId(current);
const itemId = getStoreId(item);
return currentId !== "" && currentId == itemId;
}
/** 处理门店选择:更新选中状态 + 保存 storeInfo */
function selectStore(item: AnyOrNull): boolean {
if (item == null) return false;
const code = getStoreCode(item);
if (code === "") return false;
selectedStoreCode.value = code;
selectedStore.value = item;
saveStoreInfo(item);
return true;
}
/** 从 URL options 中解析门店数据 */
function parseStoresFromOptions(options: ObjOrNull): AnyArrOrNull {
if (options == null) {
return null;
}
const rawStores = options["stores"] as StrOrNull;
if (isEmptyStr(rawStores)) {
return null;
}
try {
const decodedRaw = decodeURIComponent(rawStores ?? "");
const decoded = decodedRaw != null ? `${decodedRaw}` : "";
if (decoded === "") {
return null;
}
const parsed = JSON.parse(decoded) as any[] | null;
if (parsed != null && Array.isArray(parsed) && parsed.length > 0) {
return parsed;
}
} catch (_e) {
}
return null;
}
/** 异步加载门店数据(优先 URL 参数,兜底 storage) */
async function loadStoresData(options: ObjOrNull): Promise<void> {
const fromUrl = parseStoresFromOptions(options);
if (fromUrl != null) {
console.log('[selectStore] 从 URL 参数获取门店数据:', fromUrl.length);
const normalized = await normalizeStoreListAsync(fromUrl);
stores.value = normalized;
storage.setAsync("pendingShukeStores", fromUrl, 0);
} else {
const arr = readStoreListFromStorage("pendingShukeStores");
if (arr.length > 0) {
const normalized = await normalizeStoreListAsync(arr);
stores.value = normalized;
}
}
await nextTick();
if (stores.value.length == 0) {
return;
}
}
/** 同步设置门店列表(用于 SwitchStoreSheet 等简单场景) */
function setStores(list: any[]): void {
stores.value = normalizeStoreList(list);
}
return {
stores,
selectedStoreCode,
currentStoreCode,
selectedStore,
currentStoreInfo,
loadCurrentStoreInfo: (): void => { loadCurrentStoreInfo(); },
isCurrentStore: (item: AnyOrNull): boolean => { return isCurrentStore(item); },
selectStore: (item: AnyOrNull): boolean => { return selectStore(item); },
loadStoresData: (options: ObjOrNull): Promise<void> => { return loadStoresData(options); },
setStores: (list: any[]): void => { setStores(list); },
parseStoresFromOptions: (options: ObjOrNull): AnyArrOrNull => { return parseStoresFromOptions(options); }
};
}
......@@ -102,7 +102,7 @@ export default {
// 大屏平板竖屏 (768x1174) - 产品介绍占 65%
// 可用高度 = 1174 - 44(状态栏) - 54(标题) - 70(TabBar) ≈ 1006px
'portrait-768x1174': {
'--module-box-height': '450px',
'--module-box-height': '650px',
'--swiper-height': 'calc(var(--module-box-height) - 40px)', // 510px
'--common-title-height': '54px',
'--entrance-icon-size': '64px',
......
......@@ -25,7 +25,7 @@
<view :class="personSecondaryClassName">
<view class="person-stack-card person-stack-card-first">
<CommonFunctions
@select-store="goSelectStore"
@select-store="onSelectStore"
@attendance="goAttendance"
@setting="onSetting"
@reception-entry="goReceptionCenter" />
......@@ -41,23 +41,28 @@
<un-icon name="fingerprint" size="16" color="#94a3b8" />
</view>
<SettingBox :visible="showSetting"
@update:visible="onSettingVisible" />
@update:visible="onSettingVisible"
@switch-store="onSelectStore" />
<SwitchStoreSheet :visible="showSwitchStore"
@update:visible="onSwitchStoreVisible"
@switched="onSwitchStoreDone" />
</view>
</template>
<script setup lang="uts">
import { computed, onMounted, ref, nextTick } from "vue";
import { computed, onMounted, onUnmounted, ref, nextTick } from "vue";
import { navigateToSelectStoreWithSessionStores } from "@/utils/shukeSelectStoreNav.uts";
import { useOrientation, useScreenVars } from "@/services/adapter/hooks";
import SettingBox from "./SettingBox.uvue";
import SwitchStoreSheet from "@/components/SwitchStoreSheet.uvue";
import ProfileCard from "./components/ProfileCard.uvue";
import AccountInfo from "./components/AccountInfo.uvue";
import CommonFunctions from "./components/CommonFunctions.uvue";
import pageVars from "./styles/index.vars.uts";
import { toObj,toStr } from "@/utils/common.uts";
import { storage } from "@/utils/storage.uts";
import { STORE_SWITCHED } from "@/utils/storeSwitchEvents.uts";
const emit = defineEmits<{
/** ✅ 组件加载完成通知 */
......@@ -65,6 +70,7 @@ const emit = defineEmits<{
}>();
const showSetting = ref(false);
const showSwitchStore = ref(false);
const screenVars = useScreenVars(pageVars);
const orientation = useOrientation();
......@@ -128,6 +134,10 @@ function extractUserInfo(): void {
shopMerchantId.value = toStr(storeInfo["storeId"] ?? "");
}
function handleStoreSwitched(_storeInfo: UTSJSONObject): void {
extractUserInfo();
}
/**
* 获取设备 ID(APP 编码)
*/
......@@ -160,6 +170,7 @@ onMounted(() => {
try {
extractUserInfo();
getDeviceId();
uni.$on(STORE_SWITCHED, handleStoreSwitched);
} catch (e) {
console.error("[MyCenterMain] extractUserInfo/getDeviceId error:", e);
}
......@@ -168,6 +179,14 @@ onMounted(() => {
});
});
onShow((): void => {
extractUserInfo();
});
onUnmounted((): void => {
uni.$off(STORE_SWITCHED, handleStoreSwitched);
});
function onSettingVisible(v: boolean): void {
showSetting.value = v;
}
......@@ -176,6 +195,20 @@ function onSetting(): void {
showSetting.value = true;
}
function onSelectStore(): void {
showSwitchStore.value = true;
}
function onSwitchStoreVisible(v: boolean): void {
showSwitchStore.value = v;
}
function onSwitchStoreDone(_store: UTSJSONObject): void {
showSwitchStore.value = false;
showSetting.value = false;
extractUserInfo();
}
function goAttendance(): void {
uni.navigateTo({ url: "/pages/person/attendance" });
}
......@@ -183,19 +216,6 @@ function goAttendance(): void {
function goReceptionCenter(): void {
uni.navigateTo({ url: "/pages/receptionCenter/center" });
}
async function goSelectStore(): Promise<void> {
try {
uni.showLoading({ title: "加载中", mask: true });
await navigateToSelectStoreWithSessionStores();
extractUserInfo();
} catch (error) {
const msg = error != null ? `${error}` : "操作失败";
uni.showToast({ title: msg, icon: "none" });
} finally {
uni.hideLoading();
}
}
</script>
<style scoped lang="scss">
......
......@@ -45,7 +45,6 @@
<script setup lang="uts">
import { computed, ref, defineExpose } from 'vue'
import { navigateToSelectStoreWithSessionStores } from "@/utils/shukeSelectStoreNav.uts";
import { storage } from "@/utils/storage.uts";
import ConfirmDialog from "@/components/ConfirmDialog.uvue";
......@@ -55,7 +54,8 @@ const props = defineProps<{
}>()
const emit = defineEmits<{
'update:visible': [value: boolean]
'update:visible': [value: boolean],
'switch-store': []
}>()
const internalVisible = ref(false)
......@@ -86,19 +86,10 @@ function handleCheck(): void {
uni.showToast({ title: '目前已是最新版本', icon: 'none' })
}
async function changeAccount(): Promise<void> {
// ✅ 切换账号:打开切换门店抽屉
function changeAccount(): void {
emit("switch-store");
close();
try {
uni.showLoading({ title: "加载中", mask: true });
storage.remove("storeInfo");
storage.remove("userInfo");
await navigateToSelectStoreWithSessionStores();
} catch (error) {
const msg = error != null ? `${error}` : "操作失败";
uni.showToast({ title: msg, icon: "none" });
} finally {
uni.hideLoading();
}
}
const logoutDialog = ref<ComponentPublicInstance | null>(null);
......
......@@ -104,10 +104,15 @@ class Storage {
const info = uni.getStorageInfoSync();
// 创建空对象用于存放所有数据
const d = {};
const d: UTSJSONObject = {};
// 防御性检查:info 或 info.keys 可能为 null
if (info == null || info.keys == null) {
return d;
}
// 遍历所有键名,获取对应的值
info.keys.forEach((e) => {
info.keys.forEach((e: string) => {
d[e] = this.get(e);
});
......
/** 门店切换广播:供“我的”等页面同步刷新门店展示信息 */
export const STORE_SWITCHED = "store-switched";
export function notifyStoreSwitched(storeInfo: UTSJSONObject): void {
uni.$emit(STORE_SWITCHED, storeInfo);
}
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!