Commit 61578096 by liimin

refactor(tabbar): 重构TabBar组件体系,清理旧项目冗余代码

- 迁移原components/HomeFrame下的TabBar相关组件与工具函数至components/TabBar目录
- 删除大量废弃文件:包括config/activeityCenterBg.png、image-cache配置与文档、旧HomeFrame相关组件与样式
- 更新pages.json自定义路由,移除废弃的home-frame路由配置
- 修复多处组件导入路径,适配新的目录结构
- 重构部分类型定义:将SceneItem改为class类型,调整useRecordService返回值结构
- 优化首页、个人中心与二手车场景页面布局,移除冗余的Layout与HomeFrame嵌套
- 新增首页场景切换逻辑与RecordStart接待按钮组件
1 parent caadebd6
Showing 41 changed files with 614 additions and 3167 deletions
<template>
<view class="main-tab-shell-root">
<view class="main-tab-shell-body main-tab-shell-body-landscape">
<HomeFrameTabbarLandscape :user-name="userName"
:current-tab-index="currentTabIndex"
:scene-type-list="sceneTypeList"
:show-scene-popup="showScenePopup"
:show-setting="showSetting"
@tab-change="onTabChange"
@scene-popup-visible="onScenePopupVisible"
@setting-visible="onSettingVisible"
@scene-change="onSceneChange"
@setting="onSetting"
@choose-scene="onChooseScene"
@jump-person-center="jumpPersonCenter" />
<view class="main-tab-shell-slot main-tab-shell-slot-landscape">
<slot :user-info="slotUserInfo"></slot>
</view>
</view>
</view>
</template>
<script setup lang="uts">
import { computed, inject, type Ref } from "vue";
import HomeFrameTabbarLandscape from "./TabbarLandscape.uvue";
import type { HomeFrameTabbarSource } from "./tabbarShared.uts";
import { SCENE_SHELL_USER_INFO_INJECT_KEY, useHomeFrameTabbar } from "./tabbarShared.uts";
import { storage } from "@/utils/storage.uts";
type MainTabShellSlotProps = {
userInfo: UTSJSONObject
};
type MainTabShellSlots = {
default(props: MainTabShellSlotProps): any
};
defineSlots<MainTabShellSlots>();
const props = defineProps<{
activeTabIndex: number
}>();
const shellUserInfoRef = inject(SCENE_SHELL_USER_INFO_INJECT_KEY, null) as Ref<UTSJSONObject> | null;
const tabbarSource: HomeFrameTabbarSource = {
getTabIndex: (): number => props.activeTabIndex,
getUserInfo: (): null | UTSJSONObject => {
const r = shellUserInfoRef;
if (r != null) {
return r.value as UTSJSONObject;
}
return storage.get("userInfo") as null | UTSJSONObject;
}
};
const _tabbar = useHomeFrameTabbar(tabbarSource);
const userName = _tabbar.userName;
const currentTabIndex = _tabbar.currentTabIndex;
const sceneTypeList = _tabbar.sceneTypeList;
const showScenePopup = _tabbar.showScenePopup;
const showSetting = _tabbar.showSetting;
const onTabChange = _tabbar.onTabChange;
const onScenePopupVisible = _tabbar.onScenePopupVisible;
const onSettingVisible = _tabbar.onSettingVisible;
const onSceneChange = _tabbar.onSceneChange;
const onSetting = _tabbar.onSetting;
const onChooseScene = _tabbar.onChooseScene;
const jumpPersonCenter = _tabbar.jumpPersonCenter;
const slotUserInfo = computed((): UTSJSONObject => {
const r = shellUserInfoRef;
if (r != null) {
return r.value as UTSJSONObject;
}
const raw = storage.get("userInfo");
return raw != null ? raw as UTSJSONObject : ({} as UTSJSONObject);
});
</script>
<style scoped lang="scss">
.main-tab-shell-root {
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
min-height: 0;
min-width: 0;
}
.main-tab-shell-body-landscape {
flex: 1;
display: flex;
flex-direction: row;
width: 100%;
height: 100%;
min-height: 0;
min-width: 0;
overflow: hidden;
}
.main-tab-shell-slot-landscape {
flex: 1 1 0%;
min-width: 0;
min-height: 0;
display: flex;
flex-direction: column;
overflow: hidden;
}
</style>
<template>
<view class="main-tab-shell-root">
<view class="main-tab-shell-body main-tab-shell-body-portrait">
<view class="main-tab-shell-slot main-tab-shell-slot-portrait">
<slot :user-info="slotUserInfo"></slot>
</view>
<HomeFrameTabbarPortrait :current-tab-index="currentTabIndex"
:scene-type-list="sceneTypeList"
:show-scene-popup="showScenePopup"
:show-setting="showSetting"
@tab-change="onTabChange"
@scene-popup-visible="onScenePopupVisible"
@setting-visible="onSettingVisible"
@choose-scene="onChooseScene" />
</view>
</view>
</template>
<script setup lang="uts">
import { computed, inject, type Ref } from "vue";
import HomeFrameTabbarPortrait from "./TabbarPortrait.uvue";
import type { HomeFrameTabbarSource } from "./tabbarShared.uts";
import { SCENE_SHELL_USER_INFO_INJECT_KEY, useHomeFrameTabbar } from "./tabbarShared.uts";
import { storage } from "@/utils/storage.uts";
type MainTabShellSlotProps = {
userInfo: UTSJSONObject
};
type MainTabShellSlots = {
default(props: MainTabShellSlotProps): any
};
defineSlots<MainTabShellSlots>();
const props = defineProps<{
activeTabIndex: number
}>();
const shellUserInfoRef = inject(SCENE_SHELL_USER_INFO_INJECT_KEY, null) as Ref<UTSJSONObject> | null;
const tabbarSource: HomeFrameTabbarSource = {
getTabIndex: (): number => props.activeTabIndex,
getUserInfo: (): null | UTSJSONObject => {
const r = shellUserInfoRef;
if (r != null) {
return r.value as UTSJSONObject;
}
return storage.get("userInfo") as null | UTSJSONObject;
}
};
const _tabbar = useHomeFrameTabbar(tabbarSource);
const currentTabIndex = _tabbar.currentTabIndex;
const sceneTypeList = _tabbar.sceneTypeList;
const showScenePopup = _tabbar.showScenePopup;
const showSetting = _tabbar.showSetting;
const onTabChange = _tabbar.onTabChange;
const onScenePopupVisible = _tabbar.onScenePopupVisible;
const onSettingVisible = _tabbar.onSettingVisible;
const onChooseScene = _tabbar.onChooseScene;
const slotUserInfo = computed((): UTSJSONObject => {
const r = shellUserInfoRef;
if (r != null) {
return r.value as UTSJSONObject;
}
const raw = storage.get("userInfo");
return raw != null ? raw as UTSJSONObject : ({} as UTSJSONObject);
});
</script>
<style scoped lang="scss">
.main-tab-shell-root {
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
min-height: 0;
min-width: 0;
}
.main-tab-shell-body-portrait {
flex: 1;
display: flex;
flex-direction: column;
width: 100%;
height: 100%;
min-height: 0;
min-width: 0;
overflow: hidden;
}
.main-tab-shell-slot-portrait {
flex: 1 1 0%;
min-height: 0;
min-width: 0;
display: flex;
flex-direction: column;
overflow: hidden;
}
</style>
<template>
<scroll-view class="message-index" scroll-y="true">
<view class="message-placeholder">
<view class="placeholder-item">
<text class="placeholder-date">2026-01-16</text>
<view class="placeholder-row">
<view class="placeholder-icon"></view>
<text class="placeholder-title">活动中心</text>
<text class="placeholder-time">17:47</text>
</view>
</view>
<view class="placeholder-item">
<text class="placeholder-date">2026-01-13</text>
<view class="placeholder-row">
<view class="placeholder-icon"></view>
<text class="placeholder-title">企业通知</text>
<text class="placeholder-time">16:11</text>
</view>
</view>
<text class="coming-soon">敬请期待</text>
</view>
</scroll-view>
</template>
<script setup lang="uts">
</script>
<style scoped lang="scss">
.message-index {
width: 100%;
height: 100%;
}
.message-placeholder {
padding: var(--l-spacing-md);
display: flex;
flex-direction: column;
}
.placeholder-item {
display: flex;
flex-direction: column;
margin-bottom: var(--l-spacing-md);
padding-bottom: var(--l-spacing-md);
border-bottom: 1px solid #eee;
}
.placeholder-date {
font-size: var(--l-font-xs);
color: #999;
margin-bottom: var(--l-spacing-xs);
}
.placeholder-row {
display: flex;
flex-direction: row;
align-items: center;
}
.placeholder-icon {
width: var(--l-font-2xl);
height: var(--l-font-2xl);
background-color: #4673ff;
border-radius: var(--l-radius-lg);
margin-right: var(--l-spacing-xs);
}
.placeholder-title {
flex: 1;
font-size: var(--l-font-sm);
color: #333;
}
.placeholder-time {
font-size: var(--l-font-xs);
color: #999;
}
.coming-soon {
font-size: var(--l-font-sm);
color: #999;
text-align: center;
margin-top: var(--l-spacing-lg);
}
</style>
<template>
<!-- 物理 tab 三页共用:横/竖两套壳 + 默认槽;方向由 updateOrientation + useOrientation 驱动 -->
<MainTabShellPortrait v-if="shellIsPortrait"
:active-tab-index="props.activeTabIndex">
<template #default="{ userInfo: u }">
<slot :user-info="u"></slot>
</template>
</MainTabShellPortrait>
<MainTabShellLandscape v-else
:active-tab-index="props.activeTabIndex">
<template #default="{ userInfo: u }">
<slot :user-info="u"></slot>
</template>
</MainTabShellLandscape>
</template>
<script setup lang="uts">
import { computed, defineExpose, onMounted, onResize, provide, ref, type Ref } from "vue";
import { updateOrientation, useOrientation } from "@/services/adapter/hooks/index.uts";
import { requestRecordPermission } from "@/utils/permission.uts";
import { storage } from "@/utils/storage.uts";
import { hideNativeTabBar } from "@/utils/tabBarShell.uts";
import MainTabShellLandscape from "./MainTabShellLandscape.uvue";
import MainTabShellPortrait from "./MainTabShellPortrait.uvue";
import { SCENE_SHELL_USER_INFO_INJECT_KEY } from "./tabbarShared.uts";
type SceneShellSlotProps = {
userInfo: UTSJSONObject
};
type SceneShellSlots = {
default(props: SceneShellSlotProps): any
};
defineSlots<SceneShellSlots>();
const props = defineProps<{
/** 当前 tab 页下标:0 首页、1 接待、2 我的(与 un-tabbar 高亮一致) */
activeTabIndex: number
}>();
updateOrientation();
const orientationHook = useOrientation();
const shellIsPortrait = computed((): boolean => {
const ip = orientationHook.isPortrait as Ref<boolean>;
return ip.value == true;
});
onMounted((): void => {
// await requestRecordPermission();
hideNativeTabBar();
updateOrientation();
});
onResize((_res: any): void => {
updateOrientation();
});
const userInfo = ref<UTSJSONObject>({});
provide(SCENE_SHELL_USER_INFO_INJECT_KEY, userInfo);
function updateApp(): void {
const info = storage.get("userInfo");
if (info != null) {
userInfo.value = info as UTSJSONObject;
}
}
onShow(() => {
hideNativeTabBar();
});
defineExpose({
updateApp
});
</script>
<template>
<HomeFrameTabbarLandscape v-if="!isPortraitMode"
:user-name="userName"
:current-tab-index="currentTabIndex"
:scene-type-list="sceneTypeList"
:show-scene-popup="showScenePopup"
:show-setting="showSetting"
@tab-change="onTabChange"
@scene-popup-visible="onScenePopupVisible"
@setting-visible="onSettingVisible"
@scene-change="onSceneChange"
@setting="onSetting"
@choose-scene="onChooseScene"
@jump-person-center="jumpPersonCenter" />
<HomeFrameTabbarPortrait v-else
:current-tab-index="currentTabIndex"
:scene-type-list="sceneTypeList"
:show-scene-popup="showScenePopup"
:show-setting="showSetting"
@tab-change="onTabChange"
@scene-popup-visible="onScenePopupVisible"
@setting-visible="onSettingVisible"
@choose-scene="onChooseScene" />
</template>
<script setup lang="uts">
import { computed, type Ref } from "vue";
import { useOrientation } from "@/services/adapter/hooks/index.uts";
import HomeFrameTabbarLandscape from "./TabbarLandscape.uvue";
import HomeFrameTabbarPortrait from "./TabbarPortrait.uvue";
import type { HomeFrameTabbarSource } from "./tabbarShared.uts";
import { useHomeFrameTabbar } from "./tabbarShared.uts";
const props = defineProps<{
tabIndex?: number
userInfo?: null | UTSJSONObject
}>();
const orientationHook = useOrientation();
const isPortraitMode = computed((): boolean => {
const ip = orientationHook.isPortrait as Ref<boolean>;
return ip.value == true;
});
const tabbarSource: HomeFrameTabbarSource = {
getTabIndex: (): number => props.tabIndex != null ? (props.tabIndex as number) : 0,
getUserInfo: (): null | UTSJSONObject => props.userInfo as null | UTSJSONObject
};
const _tabbar = useHomeFrameTabbar(tabbarSource);
const currentTabIndex = _tabbar.currentTabIndex;
const sceneTypeList = _tabbar.sceneTypeList;
const userName = _tabbar.userName;
const showScenePopup = _tabbar.showScenePopup;
const showSetting = _tabbar.showSetting;
const onTabChange = _tabbar.onTabChange;
const onScenePopupVisible = _tabbar.onScenePopupVisible;
const onSettingVisible = _tabbar.onSettingVisible;
const onSceneChange = _tabbar.onSceneChange;
const onSetting = _tabbar.onSetting;
const onChooseScene = _tabbar.onChooseScene;
const jumpPersonCenter = _tabbar.jumpPersonCenter;
</script>
<template>
<view class="home-tabbar home-tabbar-landscape">
<!-- <image class="home-tabbar-bg-img"
mode="aspectFill"
src="/static/images/home/left-bg.png" /> -->
<view class="hf-landscape-column">
<view class="user-box user-box-clickable hf-landscape-user"
@click="emit('jumpPersonCenter')">
<view class="hf-landscape-profile">
<un-avatar :text="avatarText"
shape="circle"
size="42"
bgColor="#2f6af7"
color="#ffffff"
fontSize="20" />
<text class="hf-landscape-name">{{ userName }}</text>
</view>
</view>
</view>
<view class="landscape-tabbar-wrap">
<view class="landscape-un-tabbar landscape-vertical-tabs">
<view v-for="(item, index) in tabs"
:key="index"
class="landscape-vertical-tabs__item"
:class="index === currentTabIndex ? 'landscape-vertical-tabs__item--active' : ''"
@click="onTabItemClick(index)">
<view class="landscape-vertical-tabs__inner">
<image class="landscape-vertical-tabs__icon"
mode="aspectFit"
:src="index === currentTabIndex ? item.iconSrcActive : item.iconSrcInactive" />
<text class="landscape-vertical-tabs__label">{{ item.label }}</text>
</view>
</view>
</view>
</view>
<view class="home-tabbar-footer flex-col hf-landscape-footer">
<view class="hf-landscape-footer-btn"
@tap="emit('sceneChange')">
<image class="hf-landscape-footer-icon"
mode="aspectFit"
src="/static/images/home/scene-change.png" />
</view>
<view class="hf-landscape-footer-btn hf-landscape-footer-btn--after"
@tap="emit('setting')">
<image class="hf-landscape-footer-icon"
mode="aspectFit"
src="/static/images/home/setting.png" />
</view>
</view>
<CenterPopup :list="sceneTypeList"
title="选择场景"
:visible="showScenePopup"
@choose="emit('chooseScene', $event)"
@update:visible="emit('scenePopupVisible', $event)" />
<SettingBox :visible="showSetting"
@update:visible="emit('settingVisible', $event)" />
</view>
</template>
<script setup lang="uts">
import { computed } from "vue";
import CenterPopup from "@/components/CenterPopup.uvue";
import SettingBox from "@/pages/person/SettingBox.uvue";
import { HOME_FRAME_TABS } from "./tabbarShared.uts";
const props = defineProps<{
userName: string
currentTabIndex: number
sceneTypeList: UTSJSONObject[]
showScenePopup: boolean
showSetting: boolean
}>();
const emit = defineEmits<{
tabChange: [name: string | number]
scenePopupVisible: [v: boolean]
settingVisible: [v: boolean]
sceneChange: []
setting: []
chooseScene: [index: number]
jumpPersonCenter: []
}>();
const tabs = HOME_FRAME_TABS;
/** 与 MyCenterMain 一致:姓名首字,空则「我」 */
const avatarText = computed((): string => {
const n = props.userName;
if (n == null || n === "") {
return "我";
}
const s = n as string;
if (s.length <= 0) {
return "我";
}
return s.substring(0, 1);
});
function onTabItemClick(index: number): void {
emit("tabChange", index);
}
</script>
<style scoped lang="scss">
@import "./styles/common.scss";
/* 顶部用户区:仅内容高度,不把中间 Tab 区挤没 */
.hf-landscape-column {
flex-shrink: 0;
width: 100%;
display: flex;
flex-direction: column;
align-items: center;
box-sizing: border-box;
padding: 14px 10px 0;
position: relative;
z-index: 1;
}
/* 横屏侧栏:用户区 / Tab / 底按钮同一竖直中轴 */
.hf-landscape-user {
width: 100%;
display: flex;
flex-direction: column;
align-items: center;
box-sizing: border-box;
padding-top: 0;
flex-shrink: 0;
}
.hf-landscape-profile {
width: 100%;
display: flex;
flex-direction: column;
align-items: center;
}
/* 与 MyCenterMain .name 一致;与 Tab 文案同宽便于视觉对齐 */
.hf-landscape-name {
margin-top: 10px;
font-size: 14px;
font-weight: 600;
color: #1a2433;
line-height: 24px;
text-align: center;
width: 100%;
max-width: 104px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.hf-landscape-footer {
width: 100%;
display: flex;
flex-direction: column;
align-items: center;
box-sizing: border-box;
flex-shrink: 0;
padding-left: 10px;
padding-right: 10px;
}
.hf-landscape-footer-btn {
width: 44px;
height: 44px;
display: flex;
flex-direction: row;
align-items: center;
justify-content: center;
}
.hf-landscape-footer-btn--after {
margin-top: 12px;
}
.hf-landscape-footer-icon {
width: 40px;
height: 40px;
flex-shrink: 0;
}
/* 横屏侧栏 Tab:占满中间 landscape-tabbar-wrap,条目在剩余高度内垂直居中 */
.landscape-vertical-tabs {
flex: 1;
min-height: 0;
width: 100%;
padding-left: var(--tabbar-padding, 16px);
padding-right: var(--tabbar-padding, 16px);
padding-top: 8px;
padding-bottom: 8px;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
box-sizing: border-box;
}
.landscape-vertical-tabs__item {
width: 100%;
display: flex;
flex-direction: row;
justify-content: center;
align-items: center;
padding: 18px 0;
box-sizing: border-box;
}
.landscape-vertical-tabs__item + .landscape-vertical-tabs__item {
margin-top: 10px;
}
.landscape-vertical-tabs__inner {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.landscape-vertical-tabs__icon {
width: var(--tabbar-icon-size, 28px);
height: var(--tabbar-icon-size, 28px);
flex-shrink: 0;
}
.landscape-vertical-tabs__label {
margin-top: 6px;
font-size: 12px;
color: #8a98b5;
text-align: center;
width: 100%;
max-width: 104px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.landscape-vertical-tabs__item--active .landscape-vertical-tabs__label {
color: #3773f8;
font-weight: 500;
}
</style>
<template>
<view class="home-tabbar home-tabbar-portrait home-tabbar-portrait-pad">
<un-tabbar :model-value="currentTabIndex"
class="portrait-un-tabbar"
:fixed="true"
:placeholder="false"
:safe-area-inset-bottom="true"
active-color="#3773f8"
inactive-color="#8a98b5"
bg-color="#ffffff"
@change="emit('tabChange', ($event as string | number))">
<un-tabbar-item v-for="(item, index) in tabs"
:key="index"
:name="index"
:text="item.label">
<template #icon="{ active }">
<image v-if="active === true"
class="tabbar-icon-img"
mode="aspectFit"
:src="item.iconSrcActive" />
<image v-else
class="tabbar-icon-img"
mode="aspectFit"
:src="item.iconSrcInactive" />
</template>
</un-tabbar-item>
</un-tabbar>
<CenterPopup :list="sceneTypeList"
title="选择场景"
:visible="showScenePopup"
@choose="emit('chooseScene', $event)"
@update:visible="emit('scenePopupVisible', $event)" />
<SettingBox :visible="showSetting"
@update:visible="emit('settingVisible', $event)" />
</view>
</template>
<script setup lang="uts">
import CenterPopup from "@/components/CenterPopup.uvue";
import SettingBox from "@/pages/person/SettingBox.uvue";
import { HOME_FRAME_TABS } from "./tabbarShared.uts";
defineProps<{
currentTabIndex: number
sceneTypeList: UTSJSONObject[]
showScenePopup: boolean
showSetting: boolean
}>();
const emit = defineEmits<{
tabChange: [name: string | number]
scenePopupVisible: [v: boolean]
settingVisible: [v: boolean]
chooseScene: [index: number]
}>();
const tabs = HOME_FRAME_TABS;
</script>
<style scoped lang="scss">
@import "./styles/common.scss";
/* 与 layout-root 注入的 index.vars.uts 中 --tabbar-icon-size 一致;横屏侧栏见 TabbarLandscape .landscape-vertical-tabs__icon */
.tabbar-icon-img {
width: var(--tabbar-icon-size, 24px);
height: var(--tabbar-icon-size, 24px);
}
</style>
<template>
<!-- <view class="home-frame-container scene-shell-root hf-embed-in-tab-slot"> -->
<!-- 主导航 Tabbar 由 TabBarShell 横/竖壳承担;此处仅内容区 -->
<!-- <view class="home-content hf-content-without-tabbar"> -->
<!-- <view class="right-side"> -->
<!-- 仅「场景首页」:接待中心 / 我的 为独立路由页(见 HomeFrameTabbar) -->
<!-- 三卡片布局:轻改 / 权益等使用 swiperCustom -->
<view class="app-content-box">
<!-- ✅ 性能优化:骨架屏 + 异步加载 -->
<StartReceptionSkeleton v-if="!startReceptionLoaded" />
<view v-else-if="props.showStartReception"
class="start"
hover-class="start-hover"
@click="onStartClick">
<view class="start-inner">
<view class="start-icon-wrap">
<un-icon name="play-right-fill" size="14" color="#1677ff"></un-icon>
</view>
<text class="start-text">开始接待</text>
</view>
</view>
<view class="right-content-box flex-row">
<view class="content-left">
<view class="module-box box-class">
<!-- ✅ 性能优化:骨架屏 + 异步加载 -->
<ProductIntroSkeleton v-if="!productIntroLoaded" />
<view v-else-if="props.swiperCustom" class="content-box">
<ProductIntroSwiper
:load-complete="props.introLoadComplete ?? false"
:swiper-list="props.introSwiperList ?? []"
:modules="props.introModules ?? []"
:eyebrow="props.introEyebrow ?? '权益中心'"
:empty-title="props.introEmptyTitle ?? '权益配置中'"
:empty-text="props.introEmptyText ?? '敬请期待'"
:show-switch-product="props.introShowSwitchProduct ?? false"
@swiper-change="onIntroSwiperChange"
@slide-tap="onIntroSlideTap"
@switchProduct="onIntroSwitchProduct" />
</view>
<view v-else class="content-box swiper-placeholder">
<text class="placeholder-text">敬请期待</text>
</view>
</view>
<view class="tool-box box-class">
<view class="common-title">
<text class="title-text">{{ props.toolBoxTitle ?? '展业工具' }}</text>
</view>
<view class="content-box tool-content-box">
<!-- 展业工具骨架屏 -->
<ToolSkeleton v-if="!toolBoxLoaded" :count="4" />
<view v-else class="swiper-placeholder">
<un-empty
mode="data"
text="敬请期待"
>
</un-empty>
</view>
</view>
</view>
</view>
<!-- <view class="content-right box-class">
<view class="common-title">
<text class="title-text">服务中心</text>
</view>
<view class="content-box">
<HomeFrameMessageIndex class="message-box" />
</view>
</view> -->
</view>
</view>
<!-- </view> -->
<!-- </view> -->
<!-- </view> -->
</template>
<script setup lang="uts">
import { defineExpose, onMounted, ref } from "vue";
// ✅ 从 uview-unix 模块导入 UnSwiperItem 类型
import type { UnSwiperItem } from "@/uni_modules/uview-unix";
import ProductIntroSkeleton from "@/components/Skeleton/ProductIntroSkeleton.uvue";
import StartReceptionSkeleton from "@/components/Skeleton/StartReceptionSkeleton.uvue";
import ToolSkeleton from "@/components/Skeleton/ToolSkeleton.uvue";
import { delay } from "@/utils/delay.uts"; // ✅ 导入延迟执行工具函数
// import { cssClassRef, useResolutionConfig } from "@/services/adapter";
// import { layoutService } from "@/services/LayoutService.uts";
import { requestRecordPermission } from "@/utils/permission.uts";
import ProductIntroSwiper from "./ProductIntroSwiper.uvue";
const props = withDefaults(defineProps<{
showFooter?: boolean
swiperCustom?: boolean
/** 产品介绍区:与 swiperCustom 配套,由页面传入列表与文案 */
introLoadComplete?: boolean
introSwiperList?: UnSwiperItem[]
introModules?: any[]
introEyebrow?: string
introEmptyTitle?: string
introEmptyText?: string
introSwiperHeight?: number | null
/** 精品 Pad:产品介绍区展示「切换产品」按钮(对齐 simgle_app HomeSlot) */
introShowSwitchProduct?: boolean
/** 是否显示「开始接待」按钮;未传或为 true 时显示 */
showStartReception?: boolean
/** 展业工具区块标题,默认「展业工具」 */
toolBoxTitle?: string
/**
* 嵌入 `pages/index/index` 的 TabBarShell 槽内:与外层壳叠加时作为 flex 子项占满剩余区域。
* 独立整页使用 HomeFrame 时不要传(默认 false)。
*/
embedInTabSlot?: boolean
}>(), {
showStartReception: true,
introShowSwitchProduct: false,
embedInTabSlot: false,
});
const emit = defineEmits<{
start: []
introSwiperChange: [index: number]
introSlideTap: [index: number]
introSwitchProduct: []
}>();
function onIntroSwiperChange(index: number): void {
emit("introSwiperChange", index);
}
function onIntroSlideTap(index: number): void {
emit("introSlideTap", index);
}
function onIntroSwitchProduct(): void {
emit("introSwitchProduct");
}
/** ✅ 性能优化:分模块异步加载状态管理 */
const startReceptionLoaded = ref<boolean>(false); // 开始接待按钮加载状态
const productIntroLoaded = ref<boolean>(false); // 产品介绍模块加载状态
const toolBoxLoaded = ref<boolean>(false); // 展业工具加载状态
// ✅ 性能优化:updateApp 保留供外部调用,但当前无实际逻辑
function updateApp(): void {
// TODO: 如需刷新用户信息,在此添加逻辑
}
function onStartClick(): void {
emit("start");
}
onMounted((): void => {
requestRecordPermission();
// ✅ 性能优化:分模块异步加载,避免低端机白屏
// 初始状态已为 false,无需重复设置
// startReceptionLoaded.value = false; // ← 冗余,移除
// productIntroLoaded.value = false; // ← 冗余,移除
// toolBoxLoaded.value = false; // ← 冗余,移除
// ✅ 修复白屏:增加首次延迟时间,确保骨架屏完全渲染后再开始显示内容
// 低端机上骨架屏渲染可能需要 50-100ms
delay(() => {
// 1. 第一个模块:开始接待按钮(最快)
startReceptionLoaded.value = true;
delay(() => {
// 2. 第二个模块:产品介绍
productIntroLoaded.value = true;
delay(() => {
// 3. 第三个模块:展业工具(最慢)
toolBoxLoaded.value = true;
}, 2); // 约 32ms
}, 2); // 约 32ms
}, 4); // ✅ 增加到 64ms,给骨架屏足够的渲染时间
});
defineExpose({
updateApp
});
</script>
<style scoped lang="scss">
@import "./styles/common.scss";
</style>
<template>
<!--
简化版首页:仅产品介绍(精品套餐),无多场景切换。
TabBarShell:横/竖 MainTabShell + 槽,见 TabBarShell.uvue
-->
<view class="hf-home-main-tab">
<view class="hf-home-main-inner">
<BoutiqueHomePanel :logic="logic" />
</view>
</view>
</template>
<script setup lang="uts">
import BoutiqueHomePanel from "@/pages/boutique/components/BoutiqueHomePanel.uvue";
import type { BoutiqueLogic } from "@/pages/boutique/useBoutiqueLogic.uts";
const props = defineProps<{
logic: BoutiqueLogic
}>();
const logic = props.logic;
</script>
<style scoped lang="scss">
.hf-home-main-tab {
flex: 1;
width: 100%;
height: 100%;
min-height: 0;
min-width: 0;
display: flex;
flex-direction: column;
}
.hf-home-main-inner {
flex: 1;
width: 100%;
min-height: 0;
min-width: 0;
display: flex;
flex-direction: column;
}
</style>
<template>
<view class="home-frame-container scene-shell-root"
>
<view class="my-center-wrap">
<MyCenterMain :user-info="resolvedUserInfo" />
</view>
</view>
</template>
<script setup lang="uts">
import { computed } from "vue";
// import { cssClassRef, useResolutionConfig } from "@/services/adapter";
// import { layoutService } from "@/services/LayoutService.uts";
import MyCenterMain from "@/pages/person/MyCenterMain.uvue";
const props = defineProps<{
userInfo?: null | UTSJSONObject
}>();
// useResolutionConfig();
// const adapterClass = computed((): string => {
// const cls = cssClassRef.value;
// return cls != null ? (cls as string) : "";
// });
// const modeClass = computed((): string => {
// const modeRef = layoutService.getCurrentMode();
// const m = modeRef.value;
// return m == "portrait" ? "mode-portrait" : "mode-landscape";
// });
// const resolutionClass = computed((): string => {
// const bucket = layoutService.getResolutionBucket();
// return `res-${bucket}`;
// });
const resolvedUserInfo = computed((): UTSJSONObject => {
const u = props.userInfo;
return u != null ? u : ({} as UTSJSONObject);
});
</script>
<style scoped lang="scss">
@import "../styles/common.scss";
.my-center-wrap {
flex: 1;
width: 100%;
height: 100%;
min-height: 0;
display: flex;
flex-direction: column;
}
</style>
<template>
<view class="hf-reception-stack">
<ReceptionCenter />
</view>
</template>
<script setup lang="uts">
import ReceptionCenter from "@/pages/receptionCenter/center.uvue";
</script>
<style scoped lang="scss">
.hf-reception-stack {
flex: 1;
width: 100%;
height: 100%;
min-height: 0;
display: flex;
flex-direction: column;
}
</style>
# HomeFrame 响应式样式配置
## 🎨 企业级设计系统
HomeFrame 采用现代化的企业级设计语言,融合以下核心设计理念:
### 设计原则
- **视觉层次**:通过阴影、渐变、圆角建立清晰的层级关系
- **微交互**:悬停效果、过渡动画提升用户体验
- **响应式适配**:横竖屏自动切换,多分辨率精确适配
- **一致性**:统一的设计令牌(Design Tokens)确保视觉一致性
### 核心特性
✨ **玻璃态卡片** - `backdrop-filter: blur(10px)` 营造现代感
🌈 **渐变色彩** - 企业级渐变色方案(primary/secondary/success)
💫 **流畅动画** - cubic-bezier 缓动函数实现自然过渡
📐 **精确间距** - 8px 网格系统保证布局规整
🎯 **响应式图标** - Entrance 组件图标尺寸随屏幕自适应
---
## 架构说明
HomeFrame 组件采用 **CSS 变量 + layout-root** 的响应式方案,无需手动处理横竖屏切换。
### 核心原理
1. **配置文件** - `index.vars.uts` 定义所有响应式变量
2. **自动注入** - `layout-root` 组件根据屏幕状态自动应用对应的 CSS 变量
3. **样式引用** - SCSS 中使用 `var(--xxx)` 引用变量,自动响应变化
## 配置文件结构
```typescript
// styles/index.vars.uts
export default {
common: {
// 所有场景通用
'--common-title-height': '48px',
// 设计系统变量
'--l-spacing-sm': '8px',
'--l-radius-lg': '16px',
'--l-shadow-md': '0 4px 16px rgba(0, 0, 0, 0.08)',
'--l-bg-card': 'rgba(255, 255, 255, 0.85)',
'--l-gradient-primary': 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
},
portrait: {
// 竖屏专用
'--module-box-height': 'auto',
'--tool-box-min-height': '280px',
'--entrance-icon-size': '52px',
},
landscape: {
// 横屏专用
'--module-box-height': '320px',
'--tool-box-height': '280px',
'--entrance-icon-size': '56px',
},
resolutions: {
// 精确分辨率适配(优先级最高)
'landscape-1024x768': {
'--module-box-height': '360px',
'--entrance-icon-size': '60px',
},
}
}
```
## 使用方式
### 1. 在组件中导入配置
```typescript
import pageVars from "./styles/index.vars"
```
### 2. 在 SCSS 中使用 CSS 变量
```scss
.module-box {
height: var(--module-box-height);
min-height: var(--tool-box-min-height);
}
```
### 3. 无需任何 JavaScript 逻辑
❌ **不需要**:
- 监听屏幕旋转事件
- 手动计算样式
- 条件判断横竖屏
- 动态绑定 `:style`
✅ **只需要**:
- 定义 CSS 变量
- 在 SCSS 中引用
## 变量命名规范
HomeFrame 布局相关变量简洁命名,间距和字体保留 `l-` 前缀:
### 基础变量
| 变量名 | 说明 | 示例值 |
|--------|------|--------|
| `--module-box-height` | 产品介绍模块高度 | `320px` / `auto` |
| `--tool-box-height` | 展业工具模块高度(横屏) | `280px` |
| `--tool-box-min-height` | 展业工具最小高度(竖屏) | `280px` |
| `--tool-box-margin-bottom` | 展业工具底部间距 | `16px` / `0` |
| `--common-title-height` | 通用标题高度 | `48px` |
| `--tabbar-height` | TabBar 高度 | `60px` / `540px` |
| `--tabbar-icon-size` | TabBar 图标大小 | `24px` / `28px` |
| `--tabbar-width` | TabBar 宽度(横屏) | `120px` |
| `--tabbar-padding` | TabBar 内边距(横屏) | `16px` |
| `--entrance-icon-size` | Entrance 图标尺寸 | `52px` / `56px` |
| `--entrance-item-gap` | Entrance 项目间距 | `20px` / `24px` |
### 设计系统变量
| 变量名 | 说明 | 示例值 |
|--------|------|--------|
| `--l-spacing-*` | 间距变量 (xs/sm/md/lg/xl/2xl/3xl) | `4px` ~ `32px` |
| `--l-font-*` | 字体变量 (xs/sm/md/lg) | `12px` ~ `18px` |
| `--l-radius-*` | 圆角变量 (sm/md/lg/xl) | `8px` ~ `20px` |
| `--l-shadow-*` | 阴影变量 (sm/md/lg) | 多层次阴影 |
| `--l-bg-card` | 卡片背景色 | `rgba(255, 255, 255, 0.85)` |
| `--l-gradient-*` | 渐变色 (primary/secondary/success) | 企业级渐变 |
## 配置层级与优先级
```
resolutions[方向-分辨率] > portrait/landscape > common
(最高) (中) (最低)
```
**合并规则**:后合并的配置覆盖前面的同名属性
## 调试方法
1. 打开控制台,查看 `[useScreenVars]` 日志
2. 确认当前应用的 CSS 变量值
3. 旋转屏幕,观察变量是否自动更新
## 注意事项
⚠️ **重要**:
- 变量名必须与 `index.vars.uts` 中定义的完全一致
- 分辨率 key 格式:`{方向}-{宽}x{高}`,如 `portrait-393x816`
- UTS 对象属性间必须用逗号分隔
- 不要在组件中使用 `:style` 动态绑定,让 CSS 变量自动生效
## 扩展新分辨率
在 `resolutions` 中添加新的配置即可:
```typescript
resolutions: {
// 新增 iPad Pro 横屏
'landscape-1366x1024': {
'--module-box-height': '400px',
'--tool-box-height': '320px',
}
}
```
系统会自动识别并应用,无需修改其他代码。
// ========================================================================
// HomeFrame 公共样式 - 横竖屏通用
// ========================================================================
// ===== HomeFrame 容器基础样式 =====
// .home-frame-container {
// width: 100%;
// height: 100%;
// display: flex;
// flex-direction: column;
// position: relative;
// background-color: var(--bg-page, #F8FAFC);
// }
/* 嵌入 index tab 槽(TabBarShell 右侧):在 flex 列/行里占满剩余空间,避免仅依赖 height:100% 横竖屏一侧失效 */
// .home-frame-container.hf-embed-in-tab-slot {
// flex: 1;
// min-height: 0;
// min-width: 0;
// }
// ===== 内容区域布局 =====
.home-content {
// position: relative;
// flex: 1;
// display: flex;
// flex-direction: row;
// width: 100%;
// height: 100%;
// overflow: hidden;
}
// .right-side {
// height: 100%;
// display: flex;
// flex-direction: column;
// overflow: hidden;
// // padding-bottom: var(--tabbar-height);
// }
/* 横屏:Tabbar 在 DOM 中已先于 right-side,侧栏在物理左侧 */
// ===== 应用内容区 =====
.app-content-box {
/* 横屏:与左侧 Tabbar 用户区视觉对齐;竖屏见下方 .mode-portrait 覆盖 */
// margin-top: 40px;
flex: 1;
height: 100%;
width: 100%;
display: flex;
flex-direction: column;
overflow: hidden;
padding:var(--content-tabbar-gap, 12px);
// padding: 0 var(--content-box-padding-side);
// margin-bottom: var(--content-box-margin-bottom); /* ✅ 竖屏下为底部 tabBar 预留空间 */
// border:1px solid green
}
// .mode-portrait .app-content-box {
// margin-top: 0;
// }
.right-content {
// padding: var(--l-spacing-lg) 8px var(--l-spacing-2xl);
}
// 大屏平板横屏 (1174x768) 特殊优化
// .layout-landscape-1174x768 .right-content {
// padding-top: 4px;
// padding-bottom: 8px;
// }
// .layout-landscape-1174x768 .start {
// // margin-top: 0;
// // height: 72px;
// }
// ===== Start 按钮 =====
.start {
height: 80px;
box-sizing: border-box;
position: relative;
z-index: 100;
display: flex;
flex-direction: row;
justify-content: center;
align-items: center;
overflow: visible;
flex-shrink: 0;
min-width: 100px;
margin-top: 0;
// margin: var(--l-spacing-sm) 0;
padding: 0;
border-radius: var(--l-radius-xl);
background-color: #667eea;
// ✅ 性能优化:移除 box-shadow,低端机渲染压力大
// box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
// ✅ 性能优化:移除 transition,减少重绘开销
}
.start-hover {
// ✅ 性能优化:用 opacity 替代 transform + box-shadow
opacity: 0.85;
}
.start-inner {
position: relative;
z-index: 10;
display: flex;
flex-direction: row;
align-items: center;
justify-content: center;
padding: 0 var(--l-spacing-lg);
background-color: transparent;
}
.start-icon-wrap {
width: 32px;
height: 32px;
border-radius: 16px;
background: rgba(255, 255, 255, 0.95);
display: flex;
flex-direction: row;
align-items: center;
justify-content: center;
margin-right: 10px;
// ✅ 性能优化:移除 box-shadow
// box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}
.start-text {
font-size: var(--l-font-lg);
font-weight: 600;
color: #ffffff;
text-align: center;
letter-spacing: 1px;
}
// ✅ UVUE 不支持 @keyframes,已移除动画定义
// 原 startGlowPulse、startShineSweep、startIconBreath 动画已删除
// ===== 右侧内容盒子 =====
.right-content-box {
flex: 1;
display: flex;
flex-direction: row;
// gap: var(--l-spacing-lg);
// padding: var(--l-spacing-md) 0 var(--l-spacing-3xl);
margin-top: var(--l-spacing-md);
overflow: hidden;
// border:1px solid blue
}
.box-class {
background: var(--l-bg-card);
// ✅ UVUE 不支持 backdrop-filter,低端机性能优化
border-radius: var(--l-radius-lg);
overflow: hidden;
display: flex;
flex-direction: column;
// ✅ 性能优化:移除 box-shadow,低端机渲染压力大
// box-shadow: var(--l-shadow-md);
}
.box-class:hover {
// ✅ 性能优化:hover 在移动端无意义,且增加开销
// box-shadow: var(--l-shadow-lg);
// background: var(--l-bg-card-hover);
}
.content-left {
width: 100%;
flex-shrink: 0;
display: flex;
flex-direction: column;
}
.content-right {
flex: 1;
min-width: 200px;
display: flex;
flex-direction: column;
// border:1px solid yellow
}
// ===== 模块盒子(使用 CSS 变量)=====
.module-box {
height: var(--module-box-height);
margin-bottom: var(--l-spacing-xl);
display: flex; // 启用 flex 布局
flex-direction: column; // 垂直排列
}
.tool-box {
flex: 1;
display: flex;
flex-direction: column;
// border:1px solid red
}
// ===== 通用标题和内容 =====
.common-title {
height: var(--common-title-height);
display: flex;
flex-direction: row;
align-items: center;
padding-left: var(--l-spacing-lg);
border-bottom: 1px solid rgba(0, 0, 0, 0.06);
background-color: var(--bg-card, #FFFFFF);
}
.title-text {
font-size: var(--l-font-md);
font-weight: 600;
color: #1a1a1a;
letter-spacing: 0.5px;
position: relative;
}
// ✅ UVUE 不支持 ::before 伪元素,已移除左侧装饰条
// .title-text::before {
// content: '';
// position: absolute;
// left: -12px;
// top: 50%;
// transform: translateY(-50%);
// width: 3px;
// height: 16px;
// background-color: var(--l-color-primary, #667eea);
// border-radius: 2px;
// }
.content-box {
flex: 1;
padding: 0;
overflow: hidden;
}
// 工具区内容区:确保填充剩余空间并支持垂直居中
.tool-content-box {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.swiper-placeholder {
width: 100%;
height: 100%;
display: flex;
flex-direction: column; // 改为 column 以支持垂直居中
align-items: center;
justify-content: center;
}
.placeholder-text {
font-size: var(--l-font-sm);
color: #999;
}
.message-box {
flex: 1;
min-height: 0;
}
.legacy-home-wrap {
flex: 1;
width: 100%;
height: 100%;
overflow: hidden;
}
.reception-center-wrap {
flex: 1;
width: 100%;
height: 100%;
min-height: 0;
display: flex;
flex-direction: column;
position: relative;
}
.reception-center-inner,
.reception-detail-inner {
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
display: flex;
flex-direction: column;
}
.my-center-wrap {
flex: 1;
width: 100%;
height: 100%;
min-height: 0;
}
.store-addr {
position: absolute;
left: 50%;
bottom: 24rpx;
transform: translateX(-50%);
display: flex;
flex-direction: row;
align-items: center;
}
.icon-addr {
width: 32rpx;
height: 32rpx;
flex-shrink: 0;
background-color: #4673ff;
border-radius: 4rpx;
}
.addr-text {
font-size: 24rpx;
color: #999999;
// ✅ UVUE 不支持 word-wrap,white-space: normal 已可实现换行
white-space: normal;
line-height: 32rpx;
margin-left: 4rpx;
flex-shrink: 0;
}
.addr-line {
width: 600rpx;
height: 2rpx;
margin: 0 40rpx;
flex-shrink: 0;
}
.addr-line-left {
background-color: #eeeeee;
}
.addr-line-right {
background-color: #eeeeee;
}
// ===== HomeFrame Tabbar(横屏左侧 / 竖屏底部)=====
.home-tabbar {
display: flex;
flex-direction: column;
position: relative;
// width: 120px;
flex-shrink: 0;
background-color: var(--bg-card, #FFFFFF);
.home-tabbar-bg-img {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
z-index: 0;
pointer-events: none;
}
.hf-landscape-column,
.user-box,
.landscape-tabbar-wrap,
.home-tabbar-footer {
position: relative;
z-index: 1;
}
}
.home-tabbar-landscape {
min-height: 0;
height: 100%;
align-self: stretch;
}
.home-tabbar-portrait {
width: 100%;
height: var(--tabbar-height, 70px); /* ✅ 使用 CSS 变量控制 tabbar 高度 */
flex-shrink: 0;
flex-direction: column;
align-items: stretch;
padding: 0;
box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.06);
}
.portrait-un-tabbar {
width: 100%;
}
.tabbar-icon-img {
width: 24px;
height: 24px;
}
.tabbar-icon-img-pad {
width: 30px;
height: 30px;
}
.home-tabbar-portrait-pad {
padding-bottom: 6px;
}
.portrait-top-row {
width: 100%;
display: flex;
flex-direction: row;
align-items: center;
.user-box {
padding-top: 0;
padding-right: var(--l-spacing-md);
flex-shrink: 0;
}
}
.portrait-action {
flex-shrink: 0;
}
.user-box {
padding-top: 46px;
}
.user-box-clickable {
// ✅ UVUE 不支持 cursor,移动端无鼠标指针
}
.user-info-row {
flex-direction: row;
align-items: center;
.user-avatar {
margin-right: var(--l-spacing-sm);
}
.user-name-text {
margin-top: 0;
max-width: 80px;
}
}
.user-info {
width: 92px;
display: flex;
flex-direction: column;
align-items: center;
box-sizing: border-box;
position: relative;
}
.user-avatar {
width: 50px;
height: 50px;
border: 1px solid #ffffff;
box-shadow: 0 2px 4px 0 #0000001a;
border-radius: 50%;
}
.user-name-text {
font-size: 14px;
color: #292d33;
margin-top: 8px;
max-width: 56px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
text-align: center;
}
// 横屏:中间区域放 un-tabbar(组件根节点通过 custom-style 纵向排列)
.landscape-tabbar-wrap {
flex: 1;
min-height: 0;
width: 100%;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
.landscape-un-tabbar {
width: 100%;
flex: 1;
min-height: 0;
}
/* 横屏:footer 为侧栏第三段,由父级 flex 贴底;竖屏若复用此类名再按需加 margin */
.home-tabbar-footer {
flex-shrink: 0;
// padding-bottom: 10px;
}
.btn-placeholder {
width: 40px;
height: 40px;
background-color: #e8eaef;
border-radius: 20px;
margin: var(--l-spacing-sm) auto 0;
}
/**
* Tabbar Hooks 统一导出
*
* 集中管理 tabbar 相关的 Composable Hooks
*/
// 通用 tabbar 逻辑
export { useTabbarCommon } from "./useTabbar.uts";
export type { UseTabbarCommonReturn } from "./useTabbar.uts";
// 横屏用户信息逻辑
export { useLandscapeUserInfo } from "./useLandscapeUserInfo.uts";
export type { UseLandscapeUserInfoReturn } from "./useLandscapeUserInfo.uts";
/**
* 横屏 Tabbar 用户信息 Hook
*
* 管理横屏侧栏的用户头像和姓名显示
*/
import { ref, onMounted, type Ref } from "vue";
import { storage } from "@/utils/storage.uts";
import { toStr } from "@/utils/common.uts";
/** Hook 返回值类型 */
type UseLandscapeUserInfoReturn = {
userName: Ref<string>
avatarText: Ref<string>
}
export function useLandscapeUserInfo(): UseLandscapeUserInfoReturn {
const userName = ref<string>("");
/** ✅ 头像文字:从 storage 获取用户信息,取姓名首字 */
const avatarText = ref<string>("我");
onMounted(() => {
const userInfo = storage.getUserInfo();
if (userInfo != null) {
const __userName = toStr(userInfo.get("userName") ?? "");
userName.value = __userName;
avatarText.value = __userName == "" ? "我" : __userName.substring(0, 1);
}
});
return {
userName,
avatarText
};
}
/**
* Tabbar 通用逻辑 Hook
*
* 提取 Portrait 和 Landscape 的公共逻辑,减少代码重复
*/
import { HOME_FRAME_TABS, type TabItem } from "../tabbarShared.uts";
/** Hook 返回值类型 */
type UseTabbarCommonReturn = {
tabs: TabItem[]
getIconSrc: (item: TabItem, active: boolean) => string
}
export function useTabbarCommon(): UseTabbarCommonReturn {
const tabs = HOME_FRAME_TABS;
/**
* 根据激活状态获取图标路径
*/
const getIconSrc = (item: TabItem, active: boolean): string => {
return active ? item.iconSrcActive : item.iconSrcInactive;
};
return {
tabs,
getIconSrc
};
}
/**
* Tabbar 模块导出
*
* 统一导出 tabbar 相关的组件和工具函数
*/
// 场景壳组件导出(唯一入口)
export { default as TabBarShell } from "./TabBarShell.uvue";
// Tabbar 组件导出
export { default as HomeFrameTabbarLandscape } from "./Landscape.uvue";
export { default as HomeFrameTabbarPortrait } from "./Portrait.uvue";
// Composable Hooks
export { useTabbarCommon, useLandscapeUserInfo } from "./hooks";
export type { UseTabbarCommonReturn, UseLandscapeUserInfoReturn } from "./hooks";
// 类型和工具函数导出
export type { HomeFrameTabbarSource } from "./tabbarShared.uts";
export { SCENE_SHELL_USER_INFO_INJECT_KEY, useHomeFrameTabbar, HOME_FRAME_TABS } from "./tabbarShared.uts";
import { computed, ref } from "vue";
import { storage } from "@/utils/storage.uts";
import { notifyUserSceneTypeChanged } from "@/utils/userSceneEvents.uts";
import { hideNativeTabBar } from "@/utils/tabBarShell.uts";
export type HomeFrameTabbarSource = {
getTabIndex: () => number
getUserInfo: () => null | UTSJSONObject
}
/** SceneShell `provide`:`Ref<UTSJSONObject>`;MainTabShell `inject`,与插槽同源 */
export const SCENE_SHELL_USER_INFO_INJECT_KEY = "homeFrame.sceneShellUserInfo"
export type TabItem = {
label: string;
icon: string;
name: string;
/** 模板内仅用路径字段,避免 UTS 在 slot 中调用 import 的函数 */
iconSrcActive: string;
iconSrcInactive: string;
};
export type SceneTypeItem = { describe: string; icon: string; title: string; }
export const HOME_FRAME_TABS: TabItem[] = [
{
label: "首页",
icon: "home",
name: "HomeSlot",
iconSrcActive: "/static/images/tabbar/home-active.png",
iconSrcInactive: "/static/images/tabbar/home.png"
},
{
label: "接待中心",
icon: "record",
name: "ReceptionCenter",
iconSrcActive: "/static/images/tabbar/record-active.png",
iconSrcInactive: "/static/images/tabbar/record.png"
},
{
label: "我的",
icon: "my",
name: "MyCenter",
iconSrcActive: "/static/images/tabbar/study-active.png",
iconSrcInactive: "/static/images/tabbar/study.png"
},
];
export function getSceneTypeItem(sceneId: number): null | SceneTypeItem {
if (sceneId == 1) return { title: "轻改", describe: "太阳膜升级转化", icon: "轻" };
if (sceneId == 0) return { title: "会员权益/升级", describe: "权益延保", icon: "权" };
if (sceneId == 7) return { title: "二手车", describe: "二手车业务", icon: "二" };
return null;
}
export function getTabIconSrc(icon: string, active: boolean): string {
if (icon === "home") {
return active ? "/static/images/tabbar/home-active.png" : "/static/images/tabbar/home.png";
}
if (icon === "record") {
return active ? "/static/images/tabbar/record-active.png" : "/static/images/tabbar/record.png";
}
if (icon === "study") {
return active ? "/static/images/tabbar/study-active.png" : "/static/images/tabbar/study.png";
}
if (icon === "my") {
return active ? "/static/images/tabbar/study-active.png" : "/static/images/tabbar/study.png";
}
return "/static/images/tabbar/home.png";
}
function reLaunchPage(pagesJsonPath: string): void {
const trimmed = pagesJsonPath.startsWith("/") ? pagesJsonPath.substring(1) : pagesJsonPath;
const withSlash = "/" + trimmed;
uni.reLaunch({
url: withSlash,
fail: (_err: any) => {
uni.reLaunch({ url: trimmed });
}
});
}
function switchTabPage(pagesJsonPath: string): void {
const trimmed = pagesJsonPath.startsWith("/") ? pagesJsonPath.substring(1) : pagesJsonPath;
const url = "/" + trimmed;
uni.switchTab({
url,
success: () => {
hideNativeTabBar();
},
fail: (_err: any) => {
reLaunchPage(trimmed);
}
});
}
export function useHomeFrameTabbar(source: HomeFrameTabbarSource) {
const showScenePopup = ref(false);
const showSetting = ref(false);
const currentTabIndex = computed((): number => {
return source.getTabIndex();
});
const sceneTypeList = computed((): UTSJSONObject[] => {
const info = source.getUserInfo();
let openArr: number[] = [1, 0, 7];
if (info != null) {
const arr = (info as UTSJSONObject).openSceneArr as null | number[];
if (arr != null && arr.length > 0) {
openArr = arr;
}
}
const result: UTSJSONObject[] = [];
const valid = [1, 0, 7];
for (const element of openArr) {
const e = element as number;
if (valid.indexOf(e) >= 0) {
const item = getSceneTypeItem(e);
if (item != null) {
result.push({ title: item.title, describe: item.describe, icon: item.icon } as UTSJSONObject);
}
}
}
if (result.length === 0) {
result.push(
{ title: "轻改", describe: "太阳膜升级转化", icon: "轻" } as UTSJSONObject,
{ title: "会员权益/升级", describe: "权益延保", icon: "权" } as UTSJSONObject,
{ title: "二手车", describe: "二手车业务", icon: "二" } as UTSJSONObject
);
}
return result;
});
const sceneTypeIdList = computed((): number[] => {
const info = source.getUserInfo();
let openArr: number[] = [1, 0, 7];
if (info != null) {
const arr = (info as UTSJSONObject).openSceneArr as null | number[];
if (arr != null && arr.length > 0) {
openArr = arr;
}
}
const valid = [1, 0, 7];
const result: number[] = [];
for (const element of openArr) {
const e = element as number;
if (valid.indexOf(e) >= 0) {
result.push(e);
}
}
if (result.length === 0) {
return [1, 0, 7];
}
return result;
});
const userName = computed((): string => {
const info = source.getUserInfo();
if (info == null) {
return "";
}
const obj = info as UTSJSONObject;
const raw = obj.name ?? obj.staffName ?? obj.merchantName;
if (raw == null) {
return "";
}
const s = `${raw}`;
return s !== "" ? s : "";
});
const navigateToTab = (index: number): void => {
const cur = source.getTabIndex();
if (index == cur) {
return;
}
if (index == 0) {
switchTabPage("pages/index/index");
return;
}
if (index == 1) {
switchTabPage("pages/receptionCenter/center");
return;
}
if (index == 2) {
switchTabPage("pages/person/myCenter");
return;
}
};
const onTabChange = (name: string | number): void => {
const idx = name as number;
navigateToTab(idx);
};
const onScenePopupVisible = (v: boolean): void => {
showScenePopup.value = v;
};
const onSettingVisible = (v: boolean): void => {
showSetting.value = v;
};
const onSceneChange = (): void => {
showScenePopup.value = true;
};
const onSetting = (): void => {
showSetting.value = true;
};
const onChooseScene = (index: number): void => {
const ids = sceneTypeIdList.value;
if (index < 0 || index >= ids.length) {
return;
}
const sceneType = ids[index];
const raw = storage.get("userInfo");
if (raw == null) {
return;
}
const info = raw as UTSJSONObject;
const current = info.sceneType as null | number;
if (current != null && current == sceneType) {
return;
}
info.sceneType = sceneType;
uni.showLoading({ title: "切换中", mask: true });
storage.set("userInfo", info, 0);
notifyUserSceneTypeChanged(sceneType);
uni.switchTab({
url: "/pages/index/index",
success: () => {
hideNativeTabBar();
},
complete: () => {
uni.hideLoading();
},
fail: (_err: any) => {
uni.hideLoading();
reLaunchPage("pages/index/index");
}
});
};
const jumpPersonCenter = (): void => {
uni.navigateTo({ url: "/pages/person/attendance" });
};
return {
showScenePopup,
showSetting,
currentTabIndex,
sceneTypeList,
sceneTypeIdList,
userName,
onTabChange,
onScenePopupVisible,
onSettingVisible,
onSceneChange,
onSetting,
onChooseScene,
jumpPersonCenter
};
}
<template>
<un-page class="layout-root layout-column-shell" :class="[resolutionState.cssClass]">
<slot />
</un-page>
</template>
<script setup lang="uts">
import { resolutionState, useResolutionConfig } from "@/services/adapter/index.uts";
// 在这里统一调用初始化,确保任何使用 Layout 的页面都能获得正确的配置
useResolutionConfig();
</script>
<style>
.layout-column-shell {
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
}
</style>
...@@ -56,7 +56,7 @@ import BannerSkeleton from "@/components/Skeleton/BannerSkeleton.uvue"; ...@@ -56,7 +56,7 @@ import BannerSkeleton from "@/components/Skeleton/BannerSkeleton.uvue";
// ✅ 从 uview-unix 模块导入 UnSwiperItem 类型 // ✅ 从 uview-unix 模块导入 UnSwiperItem 类型
import type { UnSwiperItem } from "@/uni_modules/uview-unix"; import type { UnSwiperItem } from "@/uni_modules/uview-unix";
import { useScreenVars } from "@/services/adapter/hooks/index.uts"; import { useScreenVars } from "@/services/adapter/hooks/index.uts";
import homeFramePageVars from "./styles/index.vars.uts"; // ✅ 直接导入 import homeFramePageVars from "@/pages/index/styles/index.vars";
const props = withDefaults(defineProps<{ const props = withDefaults(defineProps<{
loadComplete: boolean loadComplete: boolean
......
...@@ -59,7 +59,11 @@ ...@@ -59,7 +59,11 @@
</template> </template>
<script setup lang="uts"> <script setup lang="uts">
import { useTabbarCommon, useLandscapeUserInfo } from "./hooks"; import { ref, onMounted } from "vue";
import { HOME_FRAME_TABS as tabs } from "./tabbarShared.uts";
import { storage } from "@/utils/storage.uts";
import { toStr } from "@/utils/common.uts";
const props = defineProps<{ const props = defineProps<{
currentTabIndex: number currentTabIndex: number
...@@ -72,8 +76,17 @@ const emit = defineEmits<{ ...@@ -72,8 +76,17 @@ const emit = defineEmits<{
switchStore: [] switchStore: []
}>(); }>();
const { tabs } = useTabbarCommon(); const userName = ref<string>("");
const { userName, avatarText } = useLandscapeUserInfo(); const avatarText = ref<string>("我");
onMounted(() => {
const userInfo = storage.getUserInfo();
if (userInfo != null) {
const __userName = toStr(userInfo.get("userName") ?? "");
userName.value = __userName;
avatarText.value = __userName == "" ? "我" : __userName.substring(0, 1);
}
});
function onTabItemClick(index: number): void { function onTabItemClick(index: number): void {
emit("tabChange", index); emit("tabChange", index);
...@@ -81,7 +94,59 @@ function onTabItemClick(index: number): void { ...@@ -81,7 +94,59 @@ function onTabItemClick(index: number): void {
</script> </script>
<style scoped lang="scss"> <style scoped lang="scss">
@import "../styles/common.scss"; /* ===== 原 common.scss 中横屏 TabBar 相关样式 ===== */
.home-tabbar {
display: flex;
flex-direction: column;
position: relative;
flex-shrink: 0;
background-color: var(--bg-card, #FFFFFF);
.home-tabbar-bg-img {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
z-index: 0;
pointer-events: none;
}
.hf-landscape-column,
.user-box,
.landscape-tabbar-wrap,
.home-tabbar-footer {
position: relative;
z-index: 1;
}
}
.home-tabbar-landscape {
min-height: 0;
height: 100%;
align-self: stretch;
}
.user-box {
padding-top: 46px;
}
.user-box-clickable {
}
.landscape-tabbar-wrap {
flex: 1;
min-height: 0;
width: 100%;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
.home-tabbar-footer {
flex-shrink: 0;
}
/* 顶部用户区:仅内容高度,不把中间 Tab 区挤没 */ /* 顶部用户区:仅内容高度,不把中间 Tab 区挤没 */
.hf-landscape-column { .hf-landscape-column {
......
...@@ -25,7 +25,7 @@ ...@@ -25,7 +25,7 @@
</template> </template>
<script setup lang="uts"> <script setup lang="uts">
import { useTabbarCommon } from "./hooks"; import { HOME_FRAME_TABS as tabs } from "./tabbarShared.uts";
const props = defineProps<{ const props = defineProps<{
currentTabIndex: number currentTabIndex: number
...@@ -34,12 +34,35 @@ const props = defineProps<{ ...@@ -34,12 +34,35 @@ const props = defineProps<{
const emit = defineEmits<{ const emit = defineEmits<{
tabChange: [name: string | number] tabChange: [name: string | number]
}>(); }>();
const { tabs } = useTabbarCommon();
</script> </script>
<style scoped lang="scss"> <style scoped lang="scss">
@import "../styles/common.scss"; /* ===== 原 common.scss 中竖屏 TabBar 相关样式 ===== */
.home-tabbar {
display: flex;
flex-direction: column;
position: relative;
flex-shrink: 0;
background-color: var(--bg-card, #FFFFFF);
}
.home-tabbar-portrait {
width: 100%;
height: var(--tabbar-height, 70px);
flex-shrink: 0;
flex-direction: column;
align-items: stretch;
padding: 0;
box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.06);
}
.home-tabbar-portrait-pad {
padding-bottom: 6px;
}
.portrait-un-tabbar {
width: 100%;
}
/* 与 layout-root 注入的 index.vars.uts 中 --tabbar-icon-size 一致;横屏侧栏见 TabbarLandscape .landscape-vertical-tabs__icon */ /* 与 layout-root 注入的 index.vars.uts 中 --tabbar-icon-size 一致;横屏侧栏见 TabbarLandscape .landscape-vertical-tabs__icon */
.tabbar-icon-img { .tabbar-icon-img {
......
<template> <template>
<!-- TabBar 壳组件:横/竖两套布局 + 默认槽;方向由 useOrientation 驱动 --> <layout-root :page-vars="resolvedPageVars">
<view v-if="shellIsPortrait" class="scene-shell-root-portrait"> <!-- TabBar 壳组件:横/竖两套布局 + 默认槽;方向由 useOrientation 驱动 -->
<view class="scene-shell-slot-portrait"> <view v-if="shellIsPortrait" class="scene-shell-root-portrait">
<slot></slot> <view class="scene-shell-slot-portrait">
</view>
<view class="scene-shell-tabbar-portrait">
<Portrait :current-tab-index="props.activeTabIndex"
@tab-change="onTabChange" />
</view>
</view>
<view v-else class="scene-shell-root-landscape">
<view class="scene-shell-body-landscape">
<Landscape :user-name="userName"
:current-tab-index="props.activeTabIndex"
@tab-change="onTabChange"
@setting="onSetting"
@jump-person-center="jumpPersonCenter"
@switch-store="onSwitchStore" />
<view class="scene-shell-slot-landscape">
<slot></slot> <slot></slot>
</view> </view>
<view class="scene-shell-tabbar-portrait">
<Portrait :current-tab-index="props.activeTabIndex"
@tab-change="(name: string | number) => onTabChange(name)" />
</view>
</view> </view>
</view> <view v-else class="scene-shell-root-landscape">
<!-- ✅ 统一的设置弹窗(横竖屏共用) --> <view class="scene-shell-body-landscape">
<SettingBox :visible="showSetting" <Landscape :user-name="userName"
@update:visible="onSettingVisible" /> :current-tab-index="props.activeTabIndex"
@tab-change="(name: string | number) => onTabChange(name)"
@setting="onSetting"
@jump-person-center="jumpPersonCenter"
@switch-store="onSwitchStore" />
<view class="scene-shell-slot-landscape">
<slot></slot>
</view>
</view>
</view>
<!-- ✅ 统一的设置弹窗(横竖屏共用) -->
<SettingBox :visible="showSetting"
@update:visible="onSettingVisible" />
</layout-root>
</template> </template>
<script setup lang="uts"> <script setup lang="uts">
...@@ -39,13 +41,25 @@ import { hideNativeTabBar } from "@/utils/tabBarShell.uts"; ...@@ -39,13 +41,25 @@ import { hideNativeTabBar } from "@/utils/tabBarShell.uts";
import Landscape from "./Landscape.uvue"; import Landscape from "./Landscape.uvue";
import Portrait from "./Portrait.uvue"; import Portrait from "./Portrait.uvue";
import type { HomeFrameTabbarSource } from "./tabbarShared.uts"; import type { HomeFrameTabbarSource } from "./tabbarShared.uts";
import { useHomeFrameTabbar } from "./tabbarShared.uts"; import { navigateToTab, useHomeFrameTabbar } from "./tabbarShared.uts";
// pageVars 自动匹配
import homePageVars from "@/pages/index/styles/index.vars";
import receptionVars from "@/pages/receptionCenter/styles/index.vars";
import personVars from "@/pages/person/styles/index.vars";
defineSlots(); defineSlots();
const props = defineProps<{ const props = defineProps<{
/** 当前 tab 页下标:0 首页、1 接待中心、2 我的(与 un-tabbar 高亮一致) */ /** 当前 tab 页下标:0 首页、1 接待中心、2 我的(与 un-tabbar 高亮一致) */
activeTabIndex: number activeTabIndex: number
/** 页面 CSS 变量,不传时根据 activeTabIndex 自动匹配 */
pageVars?: UTSJSONObject
}>();
const emit = defineEmits<{
/** tab 切换事件:外部可监听做差异化操作(如数据埋点),页面切换已由 TabBar 内部统一处理 */
tabChange: [name: string | number]
}>(); }>();
// updateOrientation(); // updateOrientation();
...@@ -56,6 +70,16 @@ const shellIsPortrait = computed((): boolean => { ...@@ -56,6 +70,16 @@ const shellIsPortrait = computed((): boolean => {
return ip.value == true; return ip.value == true;
}); });
/** 页面 CSS 变量:优先使用显式传入,否则根据 activeTabIndex 自动匹配 */
const resolvedPageVars = computed((): UTSJSONObject => {
if (props.pageVars != null) {
return props.pageVars;
}
if (props.activeTabIndex == 0) return homePageVars as UTSJSONObject;
if (props.activeTabIndex == 1) return receptionVars as UTSJSONObject;
return personVars as UTSJSONObject;
});
// ✅ Tabbar 逻辑(userInfo 从 storage 直接获取) // ✅ Tabbar 逻辑(userInfo 从 storage 直接获取)
const tabbarSource: HomeFrameTabbarSource = { const tabbarSource: HomeFrameTabbarSource = {
getTabIndex: (): number => props.activeTabIndex, getTabIndex: (): number => props.activeTabIndex,
...@@ -67,12 +91,18 @@ const tabbarSource: HomeFrameTabbarSource = { ...@@ -67,12 +91,18 @@ const tabbarSource: HomeFrameTabbarSource = {
const _tabbar = useHomeFrameTabbar(tabbarSource); const _tabbar = useHomeFrameTabbar(tabbarSource);
const userName = _tabbar.userName; const userName = _tabbar.userName;
const showSetting = _tabbar.showSetting; const showSetting = _tabbar.showSetting;
const onTabChange = _tabbar.onTabChange;
const onSettingVisible = _tabbar.onSettingVisible; const onSettingVisible = _tabbar.onSettingVisible;
const onSetting = _tabbar.onSetting; const onSetting = _tabbar.onSetting;
const jumpPersonCenter = _tabbar.jumpPersonCenter; const jumpPersonCenter = _tabbar.jumpPersonCenter;
const onSwitchStore = _tabbar.onSwitchStore; const onSwitchStore = _tabbar.onSwitchStore;
/** 统一处理 tab 切换:导航页面 + 转发事件给外部 */
function onTabChange(name: string | number): void {
const idx = name as number;
navigateToTab(idx, props.activeTabIndex);
emit("tabChange", name);
}
onMounted((): void => { onMounted((): void => {
requestRecordPermission(); requestRecordPermission();
hideNativeTabBar(); hideNativeTabBar();
......
...@@ -8,9 +8,6 @@ export type HomeFrameTabbarSource = { ...@@ -8,9 +8,6 @@ export type HomeFrameTabbarSource = {
getUserInfo: () => null | UTSJSONObject getUserInfo: () => null | UTSJSONObject
} }
/** TabBarShell `provide`:`Ref<UTSJSONObject>`;MainTabShell `inject`,与插槽同源 */
export const SCENE_SHELL_USER_INFO_INJECT_KEY = "homeFrame.sceneShellUserInfo"
/** /**
* 横屏侧栏头像文案:与 simgle_app `LeftSide` 使用 `userInfo.userName` 一致; * 横屏侧栏头像文案:与 simgle_app `LeftSide` 使用 `userInfo.userName` 一致;
* 数科/ROP 返回里常见 `name`、`staffName`、`nickName`、`merchantName` 等作回退。 * 数科/ROP 返回里常见 `name`、`staffName`、`nickName`、`merchantName` 等作回退。
...@@ -66,22 +63,6 @@ export const HOME_FRAME_TABS: TabItem[] = [ ...@@ -66,22 +63,6 @@ export const HOME_FRAME_TABS: TabItem[] = [
}, },
]; ];
export function getTabIconSrc(icon: string, active: boolean): string {
if (icon === "home") {
return active ? "/static/images/tabbar/home-active.png" : "/static/images/tabbar/home.png";
}
if (icon === "record") {
return active ? "/static/images/tabbar/record-active.png" : "/static/images/tabbar/record.png";
}
if (icon === "study") {
return active ? "/static/images/tabbar/study-active.png" : "/static/images/tabbar/study.png";
}
if (icon === "my") {
return active ? "/static/images/tabbar/study-active.png" : "/static/images/tabbar/study.png";
}
return "/static/images/tabbar/home.png";
}
function reLaunchPage(pagesJsonPath: string): void { function reLaunchPage(pagesJsonPath: string): void {
const trimmed = pagesJsonPath.startsWith("/") ? pagesJsonPath.substring(1) : pagesJsonPath; const trimmed = pagesJsonPath.startsWith("/") ? pagesJsonPath.substring(1) : pagesJsonPath;
const withSlash = "/" + trimmed; const withSlash = "/" + trimmed;
...@@ -107,6 +88,28 @@ function switchTabPage(pagesJsonPath: string): void { ...@@ -107,6 +88,28 @@ function switchTabPage(pagesJsonPath: string): void {
}); });
} }
/**
* 统一 tab 导航函数:可在 TabBar 子组件内部直接调用,
* 外部同时可通过 @tab-change 事件监听做差异化操作。
*/
export function navigateToTab(index: number, currentTabIndex: number): void {
if (index == currentTabIndex) {
return;
}
if (index == 0) {
switchTabPage("pages/index/index");
return;
}
if (index == 1) {
switchTabPage("pages/receptionCenter/center");
return;
}
if (index == 2) {
switchTabPage("pages/person/myCenter");
return;
}
}
export function useHomeFrameTabbar(source: HomeFrameTabbarSource) { export function useHomeFrameTabbar(source: HomeFrameTabbarSource) {
const showSetting = ref(false); const showSetting = ref(false);
...@@ -118,28 +121,13 @@ export function useHomeFrameTabbar(source: HomeFrameTabbarSource) { ...@@ -118,28 +121,13 @@ export function useHomeFrameTabbar(source: HomeFrameTabbarSource) {
return resolveHomeFrameDisplayName(source.getUserInfo()); return resolveHomeFrameDisplayName(source.getUserInfo());
}); });
const navigateToTab = (index: number): void => { const navigateTab = (index: number): void => {
const cur = source.getTabIndex(); navigateToTab(index, source.getTabIndex());
if (index == cur) {
return;
}
if (index == 0) {
switchTabPage("pages/index/index");
return;
}
if (index == 1) {
switchTabPage("pages/receptionCenter/center");
return;
}
if (index == 2) {
switchTabPage("pages/person/myCenter");
return;
}
}; };
const onTabChange = (name: string | number): void => { const onTabChange = (name: string | number): void => {
const idx = name as number; const idx = name as number;
navigateToTab(idx); navigateTab(idx);
}; };
const onSettingVisible = (v: boolean): void => { const onSettingVisible = (v: boolean): void => {
......
...@@ -34,11 +34,11 @@ import NoData from "./NoData.uvue"; ...@@ -34,11 +34,11 @@ import NoData from "./NoData.uvue";
import SingleColumnSkeleton from "./Skeleton/SingleColumnSkeleton.uvue"; import SingleColumnSkeleton from "./Skeleton/SingleColumnSkeleton.uvue";
import { storage } from "@/utils/storage.uts"; import { storage } from "@/utils/storage.uts";
type SceneItem = { class SceneItem {
actived: boolean actived: boolean = false
sceneDesc: string sceneDesc: string = ""
sceneName: string sceneName: string = ""
sceneType: number sceneType: number = 0
} }
const sceneList = ref<SceneItem[]>([ const sceneList = ref<SceneItem[]>([
......
...@@ -10,13 +10,23 @@ import { computed, type ComputedRef } from "vue"; ...@@ -10,13 +10,23 @@ import { computed, type ComputedRef } from "vue";
import { RecordService } from "@/services/recorder/RecordService.uts"; import { RecordService } from "@/services/recorder/RecordService.uts";
/** /**
* 获取录音服务实例 * 录音服务返回值类型
* @returns 录音服务单例
*/ */
export function useRecordService(): { class UseRecordServiceResult {
recordService: RecordService; recordService: RecordService;
isRecording: ComputedRef<boolean>; isRecording: ComputedRef<boolean>;
} {
constructor(recordService: RecordService, isRecording: ComputedRef<boolean>) {
this.recordService = recordService;
this.isRecording = isRecording;
}
}
/**
* 获取录音服务实例
* @returns 录音服务单例
*/
export function useRecordService(): UseRecordServiceResult {
const recordService = RecordService.getInstance(); const recordService = RecordService.getInstance();
// 响应式计算属性:是否正在录音 // 响应式计算属性:是否正在录音
...@@ -24,8 +34,5 @@ export function useRecordService(): { ...@@ -24,8 +34,5 @@ export function useRecordService(): {
return recordService.isReceptioning(); return recordService.isReceptioning();
}); });
return { return new UseRecordServiceResult(recordService, isRecording);
recordService,
isRecording
};
} }
# 图片缓存配置说明
## 📋 配置文件位置
```
config/image-cache.config.uts
```
## ⚙️ 默认配置
```typescript
export const DEFAULT_IMAGE_CACHE_CONFIG: ImageCacheConfig = {
enabled: false, // ⚠️ 默认禁用,提升性能
expiryTime: 7 * 24 * 60 * 60 * 1000, // 7天
maxCacheCount: 100
};
```
## 🎯 为什么默认禁用?
### 1. **性能优化**
- 避免低端机 Storage 阻塞导致 ANR(应用无响应)
- 减少主线程负担,提升页面加载速度
- 降低内存占用
### 2. **用户体验**
- 快速启动,无白屏等待
- 流畅的页面切换
- 减少卡顿和掉帧
### 3. **资源节省**
- 减少 Storage 空间占用
- 降低网络请求(虽然禁用了缓存,但图片本身会从 CDN 加载)
## 🔧 如何启用缓存
### 方法 1:修改配置文件(全局生效)
编辑 `config/image-cache.config.uts`:
```typescript
export const DEFAULT_IMAGE_CACHE_CONFIG: ImageCacheConfig = {
enabled: true, // ✅ 改为 true 启用
expiryTime: 7 * 24 * 60 * 60 * 1000,
maxCacheCount: 100
};
```
### 方法 2:运行时动态修改(推荐)
在设置页面或应用启动时:
```typescript
import imageCache from "@/services/cache/ImageCacheService.uts";
// 启用缓存
imageCache.setEnabled(true);
// 禁用缓存
imageCache.setEnabled(false);
```
### 方法 3:在代码中临时启用
```typescript
import imageCache from "@/services/cache/ImageCacheService.uts";
// 临时启用(仅当前会话)
imageCache.updateConfig({
enabled: true,
expiryTime: 3 * 24 * 60 * 60 * 1000, // 3天
maxCacheCount: 50
});
```
## 📊 配置项说明
| 配置项 | 类型 | 默认值 | 说明 |
|--------|------|--------|------|
| `enabled` | boolean | `false` | 是否启用缓存 |
| `expiryTime` | number | `7天` | 缓存过期时间(毫秒) |
| `maxCacheCount` | number | `100` | 最大缓存数量 |
## 💡 使用建议
### 低端机(内存 < 2GB)
```typescript
// 保持默认禁用
imageCache.setEnabled(false);
```
### 中高端机(内存 >= 4GB)
```typescript
// 可以启用,但限制缓存数量
imageCache.updateConfig({
enabled: true,
maxCacheCount: 50, // 限制数量
expiryTime: 3 * 24 * 60 * 60 * 1000 // 缩短过期时间
});
```
### 离线场景需求强
```typescript
// 完全启用,延长过期时间
imageCache.updateConfig({
enabled: true,
expiryTime: 30 * 24 * 60 * 60 * 1000, // 30天
maxCacheCount: 200
});
```
## 🔍 检查缓存状态
```typescript
import imageCache from "@/services/cache/ImageCacheService.uts";
// 检查是否启用
const enabled = imageCache.isEnabled();
console.log('缓存状态:', enabled ? '已启用' : '已禁用');
// 获取统计信息
const stats = imageCache.getCacheStats();
console.log('缓存统计:', stats);
// {
// totalCount: 50, // 总缓存数
// validCount: 45, // 有效缓存数
// expiredCount: 5 // 过期缓存数
// }
```
## 🗑️ 清理缓存
```typescript
import imageCache from "@/services/cache/ImageCacheService.uts";
// 清空所有缓存
imageCache.clearAllCache();
// 删除单个缓存
imageCache.removeCache('cache_key');
```
## 📝 注意事项
1. **默认禁用是出于性能考虑** - 除非有明确的离线需求,否则建议保持禁用
2. **启用后会增加 Storage 占用** - 注意监控存储空间
3. **缓存会自动清理** - 过期或超出数量限制时自动删除
4. **异步写入不阻塞** - 即使启用也不会影响主线程性能
## 🚀 最佳实践
```typescript
// App.uvue 或 main.uts
import imageCache from "@/services/cache/ImageCacheService.uts";
import { isImageCacheEnabled } from "@/config/image-cache.config.uts";
onLaunch(() => {
// 根据设备性能决定是否启用
const deviceInfo = uni.getDeviceInfo();
if (isImageCacheEnabled()) {
// 配置已启用,可以根据设备调整参数
if (deviceInfo.memorySize < 2 * 1024) {
// 低端机:禁用
imageCache.setEnabled(false);
console.log('[性能优化] 低端机已禁用图片缓存');
} else {
// 中高端机:启用但限制数量
imageCache.updateConfig({
maxCacheCount: 50
});
console.log('[性能优化] 已启用图片缓存(限制50条)');
}
}
});
```
---
**总结**:默认禁用缓存是为了保证最佳性能,如需离线功能可按需启用。
/**
* 图片缓存配置
*
* 说明:
* - 默认禁用图片缓存,以提升低端机性能
* - 可在设置页面中由用户手动启用
* - 启用后支持离线访问,但会增加 Storage 占用
*/
export interface ImageCacheConfig {
/** 是否启用图片缓存(默认禁用) */
enabled: boolean;
/** 缓存过期时间(毫秒),默认 7 天 */
expiryTime: number;
/** 最大缓存数量,默认 100 条 */
maxCacheCount: number;
}
/**
* 默认图片缓存配置
*
* 注意:默认禁用缓存,原因:
* 1. 避免低端机 Storage 阻塞导致 ANR
* 2. 减少内存占用
* 3. 提升页面加载速度
*
* 如需启用,可在设置页面中修改
*/
export const DEFAULT_IMAGE_CACHE_CONFIG: ImageCacheConfig = {
enabled: false, // ⚠️ 默认禁用,提升性能
expiryTime: 7 * 24 * 60 * 60 * 1000, // 7天
maxCacheCount: 100
};
/**
* 获取图片缓存配置
*/
export function getImageCacheConfig(): ImageCacheConfig {
return DEFAULT_IMAGE_CACHE_CONFIG;
}
/**
* 检查图片缓存是否启用
*/
export function isImageCacheEnabled(): boolean {
return DEFAULT_IMAGE_CACHE_CONFIG.enabled;
}
...@@ -94,7 +94,6 @@ ...@@ -94,7 +94,6 @@
"autoscan": true, "autoscan": true,
"custom": { "custom": {
"^uni-(.*)": "@/uni_modules/uni-$1/components/uni-$1/uni-$1.uvue", "^uni-(.*)": "@/uni_modules/uni-$1/components/uni-$1/uni-$1.uvue",
"^home-frame$": "@/components/HomeFrame/index.uvue",
"^layout-root$": "@/components/LayoutRoot/index.uvue", "^layout-root$": "@/components/LayoutRoot/index.uvue",
"^Layout$": "@/components/Layout/index.uvue", "^Layout$": "@/components/Layout/index.uvue",
"^segment-tab$": "@/pages/receptionCenter/SegmentTab.uvue", "^segment-tab$": "@/pages/receptionCenter/SegmentTab.uvue",
......
<template> <template>
<view class="page-container boutique-home-panel"> <view class="content-left">
<HomeFrame ref="homeRef" <view class="module-box box-class">
class="boutique-home-frame-root" <!-- ✅ 性能优化:骨架屏 + 异步加载 -->
:embed-in-tab-slot="true" <ProductIntroSkeleton v-if="!logic.loadComplete.value" />
:show-footer="true" <view v-else class="content-box">
:swiper-custom="true" <ProductIntroSwiper
:intro-load-complete="logic.loadComplete.value" :load-complete="logic.loadComplete.value"
:intro-swiper-list="boutiqueIntroSwiperList" :swiper-list="boutiqueIntroSwiperList"
:intro-modules="introModulesForHomeFrame" :modules="introModulesForHomeFrame"
:intro-eyebrow="boutiqueIntroEyebrowText" :eyebrow="boutiqueIntroEyebrowText"
intro-empty-title="暂无数据" empty-title="暂无数据"
:intro-empty-text="boutiqueIntroEmptyText" :empty-text="boutiqueIntroEmptyText"
:intro-show-switch-product="true" :show-switch-product="true"
@intro-slide-tap="onIntroSlideTap" @slide-tap="onIntroSlideTap"
@introSwitchProduct="onIntroSwitchProduct" @switch-product="onIntroSwitchProduct" />
@start="handleStart"> </view>
</HomeFrame> </view>
<view class="tool-box box-class">
<view class="common-title">
<text class="title-text">{{ toolBoxTitle }}</text>
</view>
<view class="content-box tool-content-box">
<ToolSkeleton v-if="!toolBoxLoaded" :count="4" />
<view v-else class="swiper-placeholder">
<un-empty mode="data" text="敬请期待"></un-empty>
</view>
</view>
</view>
<CenterPopup :list="padBusinessTypePopupItems" <CenterPopup :list="padBusinessTypePopupItems"
title="请选择接待类型" title="请选择接待类型"
...@@ -54,10 +65,11 @@ import type { BoutiqueLogic } from "@/pages/boutique/useBoutiqueLogic.uts"; ...@@ -54,10 +65,11 @@ import type { BoutiqueLogic } from "@/pages/boutique/useBoutiqueLogic.uts";
import { ComponentPublicInstance, computed, nextTick, ref } from "vue"; import { ComponentPublicInstance, computed, nextTick, ref } from "vue";
import CenterPopup from "@/components/CenterPopup.uvue"; import CenterPopup from "@/components/CenterPopup.uvue";
import HomeFrame from "@/components/HomeFrame/index.uvue";
import PackageDetailPopup from "@/pages/boutique/components/PackageDetailPopup.uvue"; import PackageDetailPopup from "@/pages/boutique/components/PackageDetailPopup.uvue";
import { recordService } from "@/services/recorder/index.uts"; import ProductIntroSwiper from "@/components/ProductIntroSwiper.uvue";
import { storage } from "@/utils/storage.uts"; import ProductIntroSkeleton from "@/components/Skeleton/ProductIntroSkeleton.uvue";
import ToolSkeleton from "@/components/Skeleton/ToolSkeleton.uvue";
import { delay } from "@/utils/delay.uts";
// ✅ 从 uview-unix 模块导入 UnSwiperItem 类型 // ✅ 从 uview-unix 模块导入 UnSwiperItem 类型
import type { UnSwiperItem } from "@/uni_modules/uview-unix"; import type { UnSwiperItem } from "@/uni_modules/uview-unix";
...@@ -117,59 +129,17 @@ const padBusinessTypePopupItems = computed((): any[] => { ...@@ -117,59 +129,17 @@ const padBusinessTypePopupItems = computed((): any[] => {
return list != null ? list : ([] as any[]); return list != null ? list : ([] as any[]);
}); });
const homeRef = ref(null);
const packageRef = ref(null); const packageRef = ref(null);
/** 切换产品:受控弹层(与 CenterPopup `visible` + `update:visible` 用法一致) */ /** 切换产品:受控弹层(与 CenterPopup `visible` + `update:visible` 用法一致) */
const showPadBusinessTypePopup = ref<boolean>(false); const showPadBusinessTypePopup = ref<boolean>(false);
const toolBoxTitle = ref<string>("展业工具");
const toolBoxLoaded = ref<boolean>(false);
function callExposedMethod(comp: any, methodName: string): void { function callExposedMethod(comp: any, methodName: string): void {
if (comp == null) return; if (comp == null) return;
(comp as ComponentPublicInstance).$callMethod(methodName); (comp as ComponentPublicInstance).$callMethod(methodName);
} }
async function handleStart(): Promise<void> {
const permitted = await recordService.isPermission();
if (permitted != true) {
return;
}
let typeCode = logic.padSelectedTypeCode.value;
if (typeCode === "") {
const tiRaw = storage.get("typeItem");
if (tiRaw != null) {
// iOS 兼容:storage.get 可能返回字符串,需要解析
let ti: UTSJSONObject | null = null;
if (typeof tiRaw === "string") {
const strVal = tiRaw as string;
// 检查是否为空字符串
if (strVal.length > 0) {
try {
ti = JSON.parse(strVal) as UTSJSONObject;
} catch (e) {
console.error('[BoutiqueHomePanel] 解析 typeItem 失败');
}
}
} else if (tiRaw instanceof UTSJSONObject) {
ti = tiRaw as UTSJSONObject;
}
if (ti != null) {
const v = ti["typeCode"] as string | null;
typeCode = v != null ? v : "";
}
}
}
if (typeCode === "") {
uni.showToast({ title: "请先加载或选择产品类型", icon: "none" });
return;
}
const q = `typeCode=${encodeURIComponent(typeCode)}&type=edit`;
uni.navigateTo({ url: `/pages/equity/detail/index?${q}` });
}
function onChooseCustomerType(index: number): void {
logic.chooseCustomerType(homeRef.value as any, index);
}
function toDetail(index: number): void { function toDetail(index: number): void {
const list = logic.introCarouselItems.value; const list = logic.introCarouselItems.value;
const item = index >= 0 && index < list.length ? list[index] : null; const item = index >= 0 && index < list.length ? list[index] : null;
...@@ -205,33 +175,20 @@ function closePackageDetail(): void { ...@@ -205,33 +175,20 @@ function closePackageDetail(): void {
logic.chooseItem.value = {}; logic.chooseItem.value = {};
} }
function updateHome(): void { // 延迟加载展业工具骨架屏
logic.jumpPage(homeRef.value as any, ""); delay(() => {
} toolBoxLoaded.value = true;
}, 4);
defineExpose({
updateHome
});
</script> </script>
<style scoped lang="scss"> <style scoped lang="scss">
/* 套在 TabBarShell flex 链内时,仅用 height:100% 竖屏常算不出高度;与权益页同级结构一致用 flex 占满 */ .content-left {
.page-container.boutique-home-panel {
flex: 1;
width: 100%; width: 100%;
min-height: 0; height: 100%;
min-width: 0;
display: flex; display: flex;
flex-direction: column; flex-direction: column;
position: relative;
box-sizing: border-box;
}
.boutique-home-frame-root {
flex: 1;
min-height: 0; min-height: 0;
min-width: 0;
width: 100%;
} }
.package-detail-box { .package-detail-box {
......
<template> <template>
<view class="page-container equity-page hf-equity-tab-root fade-in"> <view class="content-left">
<HomeFrame ref="homeRef" <view class="module-box box-class">
:embed-in-tab-slot="true" <ProductIntroSkeleton v-if="!loadComplete" />
:show-footer="true" <view v-else class="content-box">
:swiper-custom="true" <ProductIntroSwiper
:intro-load-complete="loadComplete" :load-complete="loadComplete"
:intro-swiper-list="equitySwiperList" :swiper-list="equitySwiperList"
:intro-modules="moduleList" :modules="moduleList"
intro-eyebrow="权益中心" eyebrow="权益中心"
intro-empty-title="权益配置中" empty-title="权益配置中"
@intro-slide-tap="onIntroSlideTap" empty-text="敬请期待"
@start="handleStart"> @slide-tap="onIntroSlideTap" />
</HomeFrame> </view>
</view>
<view class="tool-box box-class">
<view class="common-title">
<text class="title-text">{{ toolBoxTitle }}</text>
</view>
<view class="content-box tool-content-box">
<ToolSkeleton v-if="!toolBoxLoaded" :count="4" />
<view v-else class="swiper-placeholder">
<un-empty mode="data" text="敬请期待"></un-empty>
</view>
</view>
</view>
</view> </view>
</template> </template>
<script setup lang="uts"> <script setup lang="uts">
import { ComponentPublicInstance, computed, ref } from "vue"; import { computed, onMounted, ref } from "vue";
// ✅ UVUE 类型导入:uview-unix 模块为二进制文件,使用本地定义的类型 // ✅ UVUE 类型导入:uview-unix 模块为二进制文件,使用本地定义的类型
import { UnSwiperItem } from "@/types/uview-unix-types.uts"; import { UnSwiperItem } from "@/types/uview-unix-types.uts";
import { getCarBrandsListApi, getEmployeeListApi, getMerchantCarBrandList, getPadBusinessTypeListApi } from "@/api/common-api.uts"; import { getCarBrandsListApi, getEmployeeListApi, getMerchantCarBrandList } from "@/api/common-api.uts";
import { getMockData, getSoureData } from "@/api/system-api.uts"; import { getMockData, getSoureData } from "@/api/system-api.uts";
import HomeFrame from "@/components/HomeFrame/index.uvue";
import imageCache from "@/services/cache/ImageCacheService.uts";
import { recordService } from "@/services/recorder/index.uts";
import { dispatch, state } from "@/store/index.uts"; import { dispatch, state } from "@/store/index.uts";
import { storage } from "@/utils/storage.uts"; import { storage } from "@/utils/storage.uts";
import { delay } from "@/utils/delay.uts";
import ProductIntroSwiper from "@/components/ProductIntroSwiper.uvue";
import ProductIntroSkeleton from "@/components/Skeleton/ProductIntroSkeleton.uvue";
import ToolSkeleton from "@/components/Skeleton/ToolSkeleton.uvue";
const homeRef = ref(null);
const loadComplete = ref<boolean>(false); const loadComplete = ref<boolean>(false);
const moduleList = ref<Array<any>>([]); const moduleList = ref<Array<any>>([]);
const toolList = ref<Array<any>>([]); const toolList = ref<Array<any>>([]);
const mediaId = ref<number | string>(""); const mediaId = ref<number | string>("");
const toolBoxTitle = ref<string>("展业工具");
const toolBoxLoaded = ref<boolean>(false);
const EQUITY_SWIPER_PLACEHOLDER = "/static/images/login/nothing.webp"; const EQUITY_SWIPER_PLACEHOLDER = "/static/images/login/nothing.webp";
...@@ -129,105 +143,6 @@ function setViewInfo(data: any): void { ...@@ -129,105 +143,6 @@ function setViewInfo(data: any): void {
} }
} }
/** 与 `useBoutiqueLogic.normalizePadBizTypeRows` 一致:biz-types/list 响应容错 */
function normalizePadBizTypeRows(bizRes: any | null): any[] {
if (bizRes == null) {
return [] as any[];
}
if (Array.isArray(bizRes)) {
return bizRes as any[];
}
const root = bizRes as UTSJSONObject;
const d = root["data"];
if (d != null && Array.isArray(d)) {
return d as any[];
}
if (d != null) {
const obj = d as UTSJSONObject;
const list = obj["list"];
if (list != null && Array.isArray(list)) {
return list as any[];
}
const records = obj["records"];
if (records != null && Array.isArray(records)) {
return records as any[];
}
}
return [] as any[];
}
const rowPadTypeCode = (row: UTSJSONObject): string => {
const a = row["typeCode"] as string | null;
if (a != null && a !== "") {
return a;
}
const b = row["type_code"] as string | null;
return b != null ? b : "";
};
const rowPadTypeName = (row: UTSJSONObject): string => {
const a = row["typeName"] as string | null;
if (a != null && a !== "") {
return a;
}
const b = row["type_name"] as string | null;
return b != null ? b : "";
};
/** 无 `typeItem` 时拉 biz-types 首条写入 storage,与 simgle_app 权益首页 onLoad 一致 */
async function ensurePadTypeItemForReception(): Promise<void> {
const existing = storage.get("typeItem") as UTSJSONObject | null;
if (existing != null) {
const tc = existing["typeCode"] as string | null;
if (tc != null && tc !== "") {
return;
}
}
try {
const bizRes = await getPadBusinessTypeListApi();
const rows = normalizePadBizTypeRows(bizRes);
if (rows.length == 0) {
return;
}
const first = rows[0] as UTSJSONObject;
const typeCode = rowPadTypeCode(first);
const typeName = rowPadTypeName(first);
if (typeCode === "") {
return;
}
storage.set(
"typeItem",
{
typeCode: typeCode,
typeName: typeName
} as UTSJSONObject,
0
);
} catch (_e) {
// 忽略:handleStart 会提示无 typeCode
}
}
async function handleStart(): Promise<void> {
const permitted = await recordService.isPermission();
if (permitted != true) {
return;
}
await ensurePadTypeItemForReception();
const typeItem = storage.get("typeItem") as UTSJSONObject | null;
let typeCode = "";
if (typeItem != null) {
const tc = typeItem["typeCode"] as string | null;
typeCode = tc != null ? tc : "";
}
if (typeCode === "") {
uni.showToast({ title: "未获取到展业类型,请稍后重试", icon: "none" });
return;
}
const q = `typeCode=${encodeURIComponent(typeCode)}&type=edit`;
uni.navigateTo({ url: `/pages/equity/detail/index?${q}` });
}
function getReceptionCover(obj: UTSJSONObject): string { function getReceptionCover(obj: UTSJSONObject): string {
const source = obj.receptionSourceDetailList; const source = obj.receptionSourceDetailList;
if (source == null) { if (source == null) {
...@@ -329,9 +244,8 @@ async function getSoure(brandIdList: number[], subBrandIdList: number[]): Promis ...@@ -329,9 +244,8 @@ async function getSoure(brandIdList: number[], subBrandIdList: number[]): Promis
const storageKey = `source_${sceneType}_${shopMerchantId}`; const storageKey = `source_${sceneType}_${shopMerchantId}`;
// ✅ 简化调用:imageCache 内部自动判断是否启用
let data: null | UTSJSONObject = null; let data: null | UTSJSONObject = null;
const cachedData = imageCache.getCache(storageKey); const cachedData = storage.get(storageKey) as UTSJSONObject | null;
if (cachedData != null) { if (cachedData != null) {
data = cachedData as UTSJSONObject; data = cachedData as UTSJSONObject;
...@@ -352,8 +266,7 @@ async function getSoure(brandIdList: number[], subBrandIdList: number[]): Promis ...@@ -352,8 +266,7 @@ async function getSoure(brandIdList: number[], subBrandIdList: number[]): Promis
if (requestData != null) { if (requestData != null) {
setViewInfo(requestData as UTSJSONObject); setViewInfo(requestData as UTSJSONObject);
// ✅ 简化调用:imageCache 内部自动判断是否写入 storage.set(storageKey, requestData, 0);
imageCache.setCache(storageKey, requestData);
} else { } else {
loadComplete.value = true; loadComplete.value = true;
} }
...@@ -433,7 +346,7 @@ function get_Vehicle_Sales_Data(): void { ...@@ -433,7 +346,7 @@ function get_Vehicle_Sales_Data(): void {
}); });
} }
onLoad((_options) => { function initEquityData(): void {
getMockData(true).then(mockdata => { getMockData(true).then(mockdata => {
console.log(mockdata, "==="); console.log(mockdata, "===");
const userInfo = storage.get("userInfo") as UTSJSONObject; const userInfo = storage.get("userInfo") as UTSJSONObject;
...@@ -447,6 +360,15 @@ onLoad((_options) => { ...@@ -447,6 +360,15 @@ onLoad((_options) => {
} }
}); });
get_Vehicle_Sales_Data(); get_Vehicle_Sales_Data();
}
onLoad((_options) => {
initEquityData();
});
// 作为子组件嵌入 TabBarShell 槽时 onLoad 不触发,补 onMounted
onMounted(() => {
initEquityData();
}); });
onShow(() => { onShow(() => {
...@@ -469,6 +391,12 @@ onShow(() => { ...@@ -469,6 +391,12 @@ onShow(() => {
return; return;
} }
}); });
// 延迟加载展业工具骨架屏
delay(() => {
toolBoxLoaded.value = true;
}, 4);
</script> </script>
<style scoped lang="scss"> <style scoped lang="scss">
...@@ -476,13 +404,11 @@ onShow(() => { ...@@ -476,13 +404,11 @@ onShow(() => {
@import "../styles/landscape.scss"; @import "../styles/landscape.scss";
@import "../styles/portrait.scss"; @import "../styles/portrait.scss";
/* 与 BoutiqueHomePanel 一致:嵌在 TabBarShell 槽内时参与 flex,避免竖屏高度链断掉 */ .content-left {
.hf-equity-tab-root { width: 100%;
flex: 1; height: 100%;
min-height: 0;
min-width: 0;
display: flex; display: flex;
flex-direction: column; flex-direction: column;
box-sizing: border-box; min-height: 0;
} }
</style> </style>
<template>
<view v-if="showStartReception"
class="start"
hover-class="start-hover"
@click="onStartClick">
<view class="start-inner">
<view class="start-icon-wrap">
<un-icon name="play-right-fill" size="14" color="#1677ff"></un-icon>
</view>
<text class="start-text">开始接待</text>
</view>
</view>
</template>
<script setup lang="uts">
import { recordService } from "@/services/recorder/index.uts";
import { storage } from "@/utils/storage.uts";
const props = withDefaults(defineProps<{
/** 是否显示「开始接待」按钮 */
showStartReception?: boolean
/**
* 业务类型编码,不传时自动从 storage 读取。
* 消费方按场景传入(如精品场景从 logic.padSelectedTypeCode 获取),
* 无个性化需求可不传。
*/
typeCode?: string
}>(), {
showStartReception: true,
typeCode: "",
});
const emit = defineEmits<{
/** 开始接待事件:外部可监听做差异化操作,页面跳转已由 RecordStart 内部统一处理 */
start: []
}>();
async function onStartClick(): Promise<void> {
// 1. 统一检查录音权限
const permitted = await recordService.isPermission();
if (permitted != true) {
return;
}
// 2. 获取 typeCode:优先使用传入值,否则从 storage 读取
let typeCode = props.typeCode;
if (typeCode === "") {
const typeItem = storage.get("typeItem") as UTSJSONObject | null;
if (typeItem != null) {
const tc = typeItem["typeCode"] as string | null;
typeCode = tc != null ? tc : "";
}
}
// 3. 校验 typeCode
if (typeCode === "") {
uni.showToast({ title: "请先加载或选择产品类型", icon: "none" });
return;
}
// 4. 统一跳转接待详情页
const q = `typeCode=${encodeURIComponent(typeCode)}&type=edit`;
uni.navigateTo({ url: `/pages/equity/detail/index?${q}` });
// 5. 通知外部
emit("start");
}
</script>
<style scoped lang="scss">
.start {
height: 80px;
box-sizing: border-box;
position: relative;
z-index: 100;
display: flex;
flex-direction: row;
justify-content: center;
align-items: center;
overflow: visible;
flex-shrink: 0;
min-width: 100px;
margin-top: 0;
padding: 0;
border-radius: var(--l-radius-xl);
background-color: #667eea;
}
.start-hover {
opacity: 0.85;
}
.start-inner {
position: relative;
z-index: 10;
display: flex;
flex-direction: row;
align-items: center;
justify-content: center;
padding: 0 var(--l-spacing-lg);
background-color: transparent;
}
.start-icon-wrap {
width: 32px;
height: 32px;
border-radius: 16px;
background: rgba(255, 255, 255, 0.95);
display: flex;
flex-direction: row;
align-items: center;
justify-content: center;
margin-right: 10px;
}
.start-text {
font-size: var(--l-font-lg);
font-weight: 600;
color: #ffffff;
text-align: center;
letter-spacing: 1px;
}
</style>
<template> <template>
<!-- 物理「首页」tab:TabBarShell + 产品介绍(精品) --> <!--
<layout-root :page-vars="pageVars"> 首页主壳:TabBarShell(横/竖)+ 动态场景内容 + 常驻录音按钮。
场景通过外部按钮弹窗选择切换,录音按钮始终不销毁。
-->
<TabBarShell ref="shellRef"
:active-tab-index="0">
<view class="index-shell-page"> <view class="index-shell-page">
<view class="index-shell-scene-stretch"> <view class="index-shell-scene-stretch">
<TabBarShell ref="shellRef" <view class="tab-panel">
:active-tab-index="0"> <RecordStart />
<template #default>
<view class="tab-panel"> <view class="app-content-box">
<HomeMainTab :logic="logic" /> <view class="right-content-box flex-row">
<BoutiqueHomePanel v-if="currentScene === 'boutique'" ref="boutiquePanelRef" :logic="boutiqueLogic" />
<EquityHomePanel v-else-if="currentScene === 'equity'" ref="equityPanelRef" />
<UsedCarHomePanel v-else-if="currentScene === 'usedcar'" />
<!-- 轻改 / 洗美 占位 -->
<view v-else class="scene-placeholder">
<un-empty mode="data" :text="placeholderText" />
</view>
</view> </view>
</template> </view>
</TabBarShell> </view>
</view> </view>
</view> </view>
</layout-root> </TabBarShell>
</template> </template>
<script setup lang="uts"> <script setup lang="uts">
import { ComponentPublicInstance, ref } from "vue"; import { ref } from "vue";
import TabBarShell from "@/components/HomeFrame/tabbar/TabBarShell.uvue"; import TabBarShell from "@/components/TabBar/TabBarShell.uvue";
import HomeMainTab from "@/components/HomeFrame/presets/HomeMainTab.uvue"; import RecordStart from "./RecordStart.uvue";
import BoutiqueHomePanel from "@/pages/boutique/components/BoutiqueHomePanel.uvue";
import EquityHomePanel from "@/pages/equity/components/EquityHomePanel.uvue";
import UsedCarHomePanel from "@/pages/usedCar/components/UsedCarHomePanel.uvue";
import { useBoutiqueLogic } from "@/pages/boutique/useBoutiqueLogic.uts"; import { useBoutiqueLogic } from "@/pages/boutique/useBoutiqueLogic.uts";
import pageVars from "@/components/HomeFrame/styles/index.vars" import type { BoutiqueLogic } from "@/pages/boutique/useBoutiqueLogic.uts";
import { storage } from "@/utils/storage.uts";
const shellRef = ref(null); const shellRef = ref(null);
const logic = useBoutiqueLogic(); const boutiquePanelRef = ref(null);
const equityPanelRef = ref(null);
// ===== 场景选择 =====
type SceneId = string
class SceneItem {
id: SceneId = ""
label: string = ""
constructor(id: SceneId = "", label: string = "") {
this.id = id;
this.label = label;
}
}
const sceneList: SceneItem[] = [
{ id: "boutique", label: "精品" },
{ id: "equity", label: "权益" },
{ id: "usedcar", label: "二手车" },
{ id: "refit", label: "轻改" },
{ id: "wash", label: "洗美" },
];
const currentScene = ref<SceneId>("boutique");
const placeholderText = ref<string>("场景开发中,敬请期待");
function onSceneChange(id: SceneId): void {
if (id === currentScene.value) {
return;
}
currentScene.value = id;
}
// ===== 精品场景 logic =====
const boutiqueLogic: BoutiqueLogic = useBoutiqueLogic();
onShow(async () => { onShow(async () => {
await logic.initIfNeeded(); // 用户/门店校验
await logic.getBoutiquePackageList(); const userInfo = storage.get("userInfo");
if (userInfo == null) {
storage.remove("userInfo");
storage.remove("sessionId");
uni.reLaunch({ url: "/pages/common/login/index" });
return;
}
const userInfoObj = userInfo as UTSJSONObject;
const shopMerchantId = (userInfoObj.shopMerchantId as string) ?? "";
if (shopMerchantId == null || shopMerchantId === "") {
storage.remove("userInfo");
storage.remove("sessionId");
uni.reLaunch({ url: "/pages/common/login/index" });
return;
}
// 精品场景初始化
if (currentScene.value === "boutique") {
await boutiqueLogic.initIfNeeded();
await boutiqueLogic.getBoutiquePackageList();
}
}); });
</script> </script>
<style scoped lang="scss"> <style scoped lang="scss">
// ===== 应用内容区 (原 common.scss) =====
.app-content-box {
flex: 1;
height: 100%;
width: 100%;
display: flex;
flex-direction: column;
overflow: hidden;
padding: var(--content-tabbar-gap, 12px);
}
.right-content-box {
flex: 1;
display: flex;
flex-direction: row;
margin-top: var(--l-spacing-md);
overflow: hidden;
}
.index-shell-page { .index-shell-page {
width: 100%; width: 100%;
height: 100%; height: 100%;
...@@ -40,7 +131,6 @@ onShow(async () => { ...@@ -40,7 +131,6 @@ onShow(async () => {
flex-direction: column; flex-direction: column;
} }
/* 吃掉 index 页剩余主轴尺寸;横竖屏都要有明确高宽,内层 height:100% / flex 链才能算对 */
.index-shell-scene-stretch { .index-shell-scene-stretch {
flex: 1; flex: 1;
min-height: 0; min-height: 0;
...@@ -74,5 +164,15 @@ onShow(async () => { ...@@ -74,5 +164,15 @@ onShow(async () => {
min-width: 0; min-width: 0;
display: flex; display: flex;
flex-direction: column; flex-direction: column;
position: relative;
}
/* ===== 场景占位 ===== */
.scene-placeholder {
flex: 1;
display: flex;
align-items: center;
justify-content: center;
background-color: #f8fafc;
} }
</style> </style>
...@@ -49,7 +49,7 @@ import SettingBox from "./SettingBox.uvue"; ...@@ -49,7 +49,7 @@ import SettingBox from "./SettingBox.uvue";
import ProfileCard from "./components/ProfileCard.uvue"; import ProfileCard from "./components/ProfileCard.uvue";
import AccountInfo from "./components/AccountInfo.uvue"; import AccountInfo from "./components/AccountInfo.uvue";
import CommonFunctions from "./components/CommonFunctions.uvue"; import CommonFunctions from "./components/CommonFunctions.uvue";
import { resolveHomeFrameDisplayName } from "@/components/HomeFrame/tabbar/tabbarShared.uts"; import { resolveHomeFrameDisplayName } from "@/components/TabBar/tabbarShared.uts";
import { toObj,toStr, type ObjOrNull } from "@/utils/common.uts"; import { toObj,toStr, type ObjOrNull } from "@/utils/common.uts";
import { storage } from "@/utils/storage.uts"; import { storage } from "@/utils/storage.uts";
......
<template> <template>
<layout-root :page-vars="pageVars"> <TabBarShell ref="shellRef"
<TabBarShell ref="shellRef" :active-tab-index="2">
:active-tab-index="2"> <!-- ✅ 修复空指针:骨架屏和真实内容同时渲染 -->
<!-- ✅ 修复空指针:骨架屏和真实内容同时渲染 --> <PersonSkeleton v-if="!userInfoLoaded" />
<PersonSkeleton v-if="!userInfoLoaded" /> <MyCenterMain @loaded="onMyCenterLoaded" />
<MyCenterMain @loaded="onMyCenterLoaded" /> </TabBarShell>
</TabBarShell>
</layout-root>
</template> </template>
<script setup lang="uts"> <script setup lang="uts">
import { ref } from "vue"; import { ref } from "vue";
import TabBarShell from "@/components/HomeFrame/tabbar/TabBarShell.uvue"; import TabBarShell from "@/components/TabBar/TabBarShell.uvue";
import pageVars from "./styles/index.vars";
import MyCenterMain from "./MyCenterMain.uvue"; import MyCenterMain from "./MyCenterMain.uvue";
import PersonSkeleton from "./skeleton/PersonSkeleton.uvue"; import PersonSkeleton from "./skeleton/PersonSkeleton.uvue";
......
<template> <template>
<!-- 接待中心 Tab 聚合页:与 pages/index、pages/person/myCenter 一致,TabBarShell 负责 hideNativeTabBar + un-tabbar --> <!-- 接待中心 Tab 聚合页:与 pages/index、pages/person/myCenter 一致 -->
<layout-root :page-vars="pageVars"> <TabBarShell :active-tab-index="1">
<view class="reception-shell-page" :style="receptionContentDisplayVars"> <view class="reception-shell-page" :style="receptionContentDisplayVars">
<TabBarShell :active-tab-index="1"> <view class="reception-center-page">
<template #default> <!-- Tab 切换(竖屏显示) -->
<view class="reception-center-page"> <view class="reception-tabs-container">
<!-- Tab 切换(竖屏显示) --> <un-tabs :active-style="mainTabActiveStyle"
<view class="reception-tabs-container"> class="reception-main-tabs"
<un-tabs :active-style="mainTabActiveStyle" :inactive-style="mainTabInactiveStyle"
class="reception-main-tabs" :item-style="mainTabItemStyle"
:inactive-style="mainTabInactiveStyle" :list="mainTabs"
:item-style="mainTabItemStyle" :value="mainTabIndex"
:list="mainTabs" @change="onMainTabChange">
:value="mainTabIndex" </un-tabs>
@change="onMainTabChange"> </view>
</un-tabs> <!-- Tab 内容区域 -->
</view> <view class="reception-content-container">
<!-- Tab 内容区域 --> <!-- ✅ 性能优化:统一渲染组件,通过 CSS 控制显示/隐藏,避免重复实例化 -->
<view class="reception-content-container">
<!-- ✅ 性能优化:统一渲染组件,通过 CSS 控制显示/隐藏,避免重复实例化 --> <!-- 业绩看板(竖屏滚动 / 横屏左栏) -->
<scroll-view class="reception-dashboard-scroll"
<!-- 业绩看板(竖屏滚动 / 横屏左栏) --> :class="{'reception-portrait-only': true}"
<scroll-view class="reception-dashboard-scroll" scroll-y="true"
:class="{'reception-portrait-only': true}" show-scrollbar="false">
scroll-y="true" <!-- ✅ 性能优化:骨架屏 + 异步加载 -->
show-scrollbar="false"> <ReceptionDashboardTab v-if="dashboardLoaded"
<!-- ✅ 性能优化:骨架屏 + 异步加载 --> :performance-data="performanceData"
<ReceptionDashboardTab v-if="dashboardLoaded" :all-reception-records="dashboardReceptionRecordsAll" />
:performance-data="performanceData" <!-- 骨架屏:业绩看板加载中 -->
:all-reception-records="dashboardReceptionRecordsAll" /> <DashboardSkeleton v-else />
<!-- 骨架屏:业绩看板加载中 --> </scroll-view>
<DashboardSkeleton v-else />
</scroll-view> <!-- 接待列表(竖屏 Tab2 / 横屏右栏) -->
<view class="reception-list-wrapper" v-if="isPortrait != true || mainTabIndex == 1">
<!-- 接待列表(竖屏 Tab2 / 横屏右栏) --> <!-- ✅ 性能优化:始终渲染组件,内部通过 showListSkeleton 控制骨架屏 -->
<view class="reception-list-wrapper" v-if="isPortrait != true || mainTabIndex == 1"> <ReceptionCustomerListTab
<!-- ✅ 性能优化:始终渲染组件,内部通过 showListSkeleton 控制骨架屏 --> :sticky-header="true"
<ReceptionCustomerListTab :reception-record-list="receptionRecordList"
:sticky-header="true" :show-list-skeleton="showListSkeleton"
:reception-record-list="receptionRecordList" :reception-list-loading-more="receptionListLoadingMore"
:show-list-skeleton="showListSkeleton" :reception-list-has-more="receptionListHasMore"
:reception-list-loading-more="receptionListLoadingMore" :filter-tab-index="filterTabIndex"
:reception-list-has-more="receptionListHasMore" :submitted-result-tab-index="submittedResultTabIndex"
:filter-tab-index="filterTabIndex" :unsubmitted-pending-tab-index="unsubmittedPendingTabIndex"
:submitted-result-tab-index="submittedResultTabIndex" @scroll-lower="onListScrollToLower"
:unsubmitted-pending-tab-index="unsubmittedPendingTabIndex" @filter-tab-change="onFilterTabChange"
@scroll-lower="onListScrollToLower" @submitted-result-change="onSubmittedResultChange"
@filter-tab-change="onFilterTabChange" @unsubmitted-pending-change="onUnsubmittedPendingChange" />
@submitted-result-change="onSubmittedResultChange"
@unsubmitted-pending-change="onUnsubmittedPendingChange" />
</view>
</view>
<!-- 全局弹窗(已移至子组件,使用 navigateTo 跳转) -->
</view> </view>
</template> </view>
</TabBarShell>
<!-- 全局弹窗(已移至子组件,使用 navigateTo 跳转) -->
</view>
</view> </view>
</layout-root> </TabBarShell>
</template> </template>
<script setup lang="uts"> <script setup lang="uts">
...@@ -66,7 +62,7 @@ import { type ComponentPublicInstance, type Ref, computed, nextTick, onMounted, ...@@ -66,7 +62,7 @@ import { type ComponentPublicInstance, type Ref, computed, nextTick, onMounted,
import { type UnTabItem } from "@/uni_modules/uview-unix"; import { type UnTabItem } from "@/uni_modules/uview-unix";
import { get } from "@/utils/common.uts"; // ✅ 导入 get 函数用于安全访问 JSONObject import { get } from "@/utils/common.uts"; // ✅ 导入 get 函数用于安全访问 JSONObject
import { getMerchantPerformance, getList} from "@/api/receiption.uts"; import { getMerchantPerformance, getList} from "@/api/receiption.uts";
import TabBarShell from "@/components/HomeFrame/tabbar/TabBarShell.uvue"; import TabBarShell from "@/components/TabBar/TabBarShell.uvue";
import { updateOrientation, useOrientation, useScreenVars } from "@/services/adapter/hooks/index.uts"; import { updateOrientation, useOrientation, useScreenVars } from "@/services/adapter/hooks/index.uts";
// ✅ 数据库相关导入(用于本地未提交记录) // ✅ 数据库相关导入(用于本地未提交记录)
import { DBRecord, recordService, type RecordData, type RecordFile } from "@/services/recorder/index.uts"; import { DBRecord, recordService, type RecordData, type RecordFile } from "@/services/recorder/index.uts";
......
<template> <template>
<view class="page-container used-car-home-in-tab"> <view class="home-content">
<HomeFrame ref="homeRef" <view class="header">
:embed-in-tab-slot="true" <text class="title">二手车场景</text>
:show-footer="true"> <text class="subtitle">Used Car</text>
<template #home> </view>
<view class="home-content">
<view class="header"> <view class="action-area">
<text class="title">二手车场景</text> <text class="status-text">二手车场景不支持开始接待跳转</text>
<text class="subtitle">Used Car</text> </view>
</view>
<view class="info-panel">
<view class="action-area"> <text class="info-label">接待状态:</text>
<text class="status-text">二手车场景不支持开始接待跳转</text> <text class="info-value">{{ receptionStatusText }}</text>
</view> </view>
<view class="info-panel">
<text class="info-label">接待状态:</text>
<text class="info-value">{{ receptionStatusText }}</text>
</view>
</view>
</template>
</HomeFrame>
</view> </view>
</template> </template>
<script setup lang="uts"> <script setup lang="uts">
import { ComponentPublicInstance, computed, ref } from "vue"; import { computed, onMounted, ref } from "vue";
import HomeFrame from "@/components/HomeFrame/index.uvue";
import { useReception } from "@/composables/useReception"; import { useReception } from "@/composables/useReception";
import { storage } from "@/utils/storage.uts"; import { storage } from "@/utils/storage.uts";
...@@ -52,6 +43,11 @@ onLoad((_options: OnLoadOptions) => { ...@@ -52,6 +43,11 @@ onLoad((_options: OnLoadOptions) => {
uni.hideLoading(); uni.hideLoading();
}); });
// 作为子组件嵌入 TabBarShell 槽时 onLoad 不触发,补 onMounted
onMounted(() => {
uni.hideLoading();
});
onShow(() => { onShow(() => {
const userInfo = storage.get("userInfo"); const userInfo = storage.get("userInfo");
if (userInfo == null) { if (userInfo == null) {
......
/**
* 图片缓存服务使用示例
*
* 演示如何使用 ImageCacheService
*/
import imageCache from "@/services/cache/ImageCacheService.uts";
// ==================== 基本用法 ====================
/**
* 1. 检查缓存是否启用
*/
export function checkCacheEnabled(): boolean {
const enabled = imageCache.isEnabled();
console.log('[ImageCache] 缓存状态:', enabled ? '已启用' : '已禁用');
return enabled;
}
/**
* 2. 启用/禁用缓存
*/
export function toggleCache(enabled: boolean): void {
imageCache.setEnabled(enabled);
console.log('[ImageCache] 缓存已', enabled ? '启用' : '禁用');
}
/**
* 3. 写入缓存(自动判断是否启用)
*/
export function saveToCache(key: string, data: any): void {
// ✅ 简化调用:无需检查 isEnabled()
imageCache.setCache(key, data);
console.log('[ImageCache] 数据已写入缓存:', key);
}
/**
* 4. 读取缓存(自动判断是否启用)
*/
export function loadFromCache(key: string): any | null {
// ✅ 简化调用:无需检查 isEnabled()
const data = imageCache.getCache(key);
if (data != null) {
console.log('[ImageCache] 从缓存读取成功:', key);
} else {
console.log('[ImageCache] 缓存未命中:', key);
}
return data;
}
/**
* 5. 删除缓存
*/
export function removeFromCache(key: string): void {
imageCache.removeCache(key);
console.log('[ImageCache] 缓存已删除:', key);
}
/**
* 6. 清空所有缓存
*/
export function clearAllCache(): void {
imageCache.clearAllCache();
console.log('[ImageCache] 所有缓存已清空');
}
/**
* 7. 获取缓存统计
*/
export function getCacheInfo(): void {
const stats = imageCache.getCacheStats();
console.log('[ImageCache] 缓存统计:', {
总数: stats.totalCount,
有效: stats.validCount,
过期: stats.expiredCount
});
}
/**
* 8. 更新缓存配置
*/
export function updateCacheConfig(): void {
imageCache.updateConfig({
enabled: true,
expiryTime: 7 * 24 * 60 * 60 * 1000, // 7天
maxCacheCount: 100
});
console.log('[ImageCache] 配置已更新');
}
// ==================== 在组件中使用 ====================
/**
* 示例:在页面加载时使用缓存
*/
export async function loadDataWithCache(dataKey: string, fetchData: () => Promise<any>): Promise<any> {
// 1. 尝试从缓存读取
const cached = imageCache.getCache(dataKey);
if (cached != null) {
console.log('[ImageCache] 使用缓存数据');
return cached;
}
// 2. 缓存未命中,从网络获取
console.log('[ImageCache] 缓存未命中,从网络获取');
try {
const data = await fetchData();
// 3. 写入缓存(如果启用)
if (imageCache.isEnabled()) {
imageCache.setCache(dataKey, data);
}
return data;
} catch (error) {
console.error('[ImageCache] 数据获取失败:', error);
throw error;
}
}
// ==================== 导出默认对象 ====================
export default {
checkCacheEnabled,
toggleCache,
saveToCache,
loadFromCache,
removeFromCache,
clearAllCache,
getCacheInfo,
updateCacheConfig,
loadDataWithCache
};
/**
* 图片缓存服务 - 模块化图片缓存管理
*
* 功能:
* 1. 支持开关控制是否启用缓存
* 2. 自动清理过期缓存
* 3. 提供统一的缓存读写接口
* 4. 异步写入,不阻塞主线程
*
* 使用场景:
* - 权益素材图片缓存
* - 产品介绍图片缓存
* - 其他需要离线访问的图片资源
*/
import { storage } from "@/utils/storage.uts";
import { DEFAULT_IMAGE_CACHE_CONFIG, type ImageCacheConfig } from "@/config/image-cache.config.uts";
// ==================== 常量定义 ====================
/** 缓存配置键名 */
const CACHE_CONFIG_KEY = "image_cache_config";
/** 默认缓存过期时间(7天) */
const DEFAULT_CACHE_EXPIRY = 7 * 24 * 60 * 60 * 1000;
/** 缓存前缀 */
const CACHE_PREFIX = "img_cache_";
// ==================== 类型定义 ====================
/** 缓存配置 */
export interface ImageCacheConfig {
/** 是否启用缓存 */
enabled: boolean;
/** 缓存过期时间(毫秒) */
expiryTime: number;
/** 最大缓存数量 */
maxCacheCount: number;
}
/** 缓存项 */
export interface CacheItem {
/** 缓存数据 */
data: any;
/** 缓存时间戳 */
timestamp: number;
/** 过期时间戳 */
expireAt: number;
}
// ==================== 默认配置 ====================
// ✅ 使用配置文件中的默认值
const DEFAULT_CONFIG: ImageCacheConfig = {
enabled: DEFAULT_IMAGE_CACHE_CONFIG.enabled,
expiryTime: DEFAULT_IMAGE_CACHE_CONFIG.expiryTime,
maxCacheCount: DEFAULT_IMAGE_CACHE_CONFIG.maxCacheCount
};
// ==================== 核心功能 ====================
/**
* 获取缓存配置
*/
function getConfig(): ImageCacheConfig {
const config = storage.get(CACHE_CONFIG_KEY) as ImageCacheConfig | null;
if (config != null) {
return config;
}
// 首次使用,保存默认配置
storage.set(CACHE_CONFIG_KEY, DEFAULT_CONFIG, 0);
return DEFAULT_CONFIG;
}
/**
* 更新缓存配置
* @param config 新配置(部分更新)
*/
export function updateConfig(config: Partial<ImageCacheConfig>): void {
const current = getConfig();
const updated: ImageCacheConfig = {
enabled: config.enabled ?? current.enabled,
expiryTime: config.expiryTime ?? current.expiryTime,
maxCacheCount: config.maxCacheCount ?? current.maxCacheCount
};
storage.set(CACHE_CONFIG_KEY, updated, 0);
}
/**
* 检查缓存是否启用
*/
export function isEnabled(): boolean {
const config = getConfig();
return config.enabled;
}
/**
* 启用/禁用缓存
* @param enabled 是否启用
*/
export function setEnabled(enabled: boolean): void {
updateConfig({ enabled });
}
/**
* 生成缓存键名
* @param key 原始键名
*/
function generateCacheKey(key: string): string {
return `${CACHE_PREFIX}${key}`;
}
/**
* 写入缓存(自动判断是否启用)
* @param key 缓存键名
* @param data 缓存数据
* @param expiryTime 过期时间(可选,使用默认值)
*/
export function setCache(key: string, data: any, expiryTime?: number): void {
const config = getConfig();
// 如果缓存未启用,直接返回,不执行任何操作
if (!config.enabled) {
return;
}
const cacheKey = generateCacheKey(key);
const now = Date.now();
const expire = expiryTime ?? config.expiryTime;
const cacheItem: CacheItem = {
data: data,
timestamp: now,
expireAt: now + expire
};
// ✅ 使用异步存储 API,避免阻塞主线程
storage.setAsync(cacheKey, cacheItem, 0);
// 检查并清理过期缓存(异步执行)
setTimeout(() => {
cleanupExpiredCache();
}, 100);
}
/**
* 读取缓存(自动判断是否启用)
* @param key 缓存键名
* @returns 缓存数据,如果不存在、已过期或缓存禁用则返回 null
*/
export function getCache(key: string): any | null {
const config = getConfig();
// 如果缓存未启用,直接返回 null
if (!config.enabled) {
return null;
}
const cacheKey = generateCacheKey(key);
const cacheItem = storage.get(cacheKey) as CacheItem | null;
if (cacheItem == null) {
return null;
}
// 检查是否过期
const now = Date.now();
if (now > cacheItem.expireAt) {
// 已过期,删除缓存
removeCache(key);
return null;
}
return cacheItem.data;
}
/**
* 删除缓存
* @param key 缓存键名
*/
export function removeCache(key: string): void {
const cacheKey = generateCacheKey(key);
storage.remove(cacheKey);
}
/**
* 清理所有缓存
*/
export function clearAllCache(): void {
const keys = storage.keys();
keys.forEach((key: string) => {
if (key.startsWith(CACHE_PREFIX)) {
storage.remove(key);
}
});
}
/**
* 清理过期缓存
*/
function cleanupExpiredCache(): void {
const config = getConfig();
const keys = storage.keys();
const now = Date.now();
let removedCount = 0;
// 收集所有缓存项及其时间戳
const cacheItems: Array<{ key: string; item: CacheItem }> = [];
keys.forEach((key: string) => {
if (key.startsWith(CACHE_PREFIX)) {
const item = storage.get(key) as CacheItem | null;
if (item != null) {
cacheItems.push({ key, item });
}
}
});
// 按时间戳排序(旧的在前)
cacheItems.sort((a, b) => a.item.timestamp - b.item.timestamp);
// 删除过期的和超出数量的
cacheItems.forEach(({ key, item }) => {
if (now > item.expireAt || removedCount >= cacheItems.length - config.maxCacheCount) {
storage.remove(key);
removedCount++;
}
});
}
/**
* 获取缓存统计信息
*/
export function getCacheStats(): {
totalCount: number;
validCount: number;
expiredCount: number;
totalSize: number;
} {
const keys = storage.keys();
const now = Date.now();
let validCount = 0;
let expiredCount = 0;
keys.forEach((key: string) => {
if (key.startsWith(CACHE_PREFIX)) {
const item = storage.get(key) as CacheItem | null;
if (item != null) {
if (now > item.expireAt) {
expiredCount++;
} else {
validCount++;
}
}
}
});
return {
totalCount: validCount + expiredCount,
validCount,
expiredCount,
totalSize: 0 // Storage API 不支持直接获取大小
};
}
// ==================== 导出默认对象 ====================
export default {
isEnabled,
setEnabled,
updateConfig,
setCache,
getCache,
removeCache,
clearAllCache,
getCacheStats
};
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!