Commit cd6af975 by cen Committed by chenwq1

fix:竖屏

1 parent 28206b44
Showing 38 changed files with 2164 additions and 974 deletions
......@@ -3,6 +3,8 @@ import { updateResolutionConfig } from "@/config/resolution-adapt/index.uts";
// #ifdef APP
import { layoutService } from "@/services/LayoutService.uts";
import { recordService } from "@/services/recorder";
import { lockOrientation } from "@/utils/plus-screen.uts";
// #endif
let firstBackTime = 0;
......@@ -13,6 +15,19 @@ export default {
layoutService.init();
const sys = uni.getSystemInfoSync();
console.log(`[App] 当前分辨率:${ sys.screenWidth } x ${ sys.screenHeight}`);
// pad/大屏锁定横屏,手机锁定竖屏
if (layoutService.isMode("pad") || layoutService.isMode("desktop")) {
lockOrientation("landscape-primary");
// 锁定后延迟刷新屏幕尺寸,此时已旋转为横屏,getSystemInfoSync() 会返回 1174x768
setTimeout(() => {
layoutService.refreshScreenInfo();
}, 400);
// 启动阶段多次重试锁定,避免首屏/框架稍后把方向改回竖屏(不做按页面锁定)
setTimeout(() => { lockOrientation("landscape-primary"); }, 600);
setTimeout(() => { lockOrientation("landscape-primary"); }, 1200);
} else {
lockOrientation("portrait-primary");
}
// #endif
console.log("App Launch");
......
......@@ -7,6 +7,6 @@
/* 精品首页竖屏下“开始接待”区域适配,降低高度避免图片拉伸感 */
.start {
height: 96px;
padding-top: 24px;
// padding-top: 24px;
}
}
......@@ -163,4 +163,4 @@ export const signSecretKey: SignSecretKeyItem = signSecretKeyMap[currentTarget]
export const pathEnum: UTSJSONObject = PATH_ENUM;
export const pathEnumExport: UTSJSONObject = PATH_ENUM;
// env 仅用于区分当前环境标签,这里直接按 TARGET_INDEX 映射为字符串
export const env: string = TARGET_INDEX == 3 ? "production" : TARGET_INDEX == 1 ? "develop" : "test";
export const env: string = TARGET_INDEX == 3 ? "production" : (TARGET_INDEX == 1 ? "develop" : "test");
import { env } from "@/api/env.uts";
/**
* 系统/配置 API(从 gl_tape/api/module/systemApi.js 迁移)
* 可先返回 mock 对象,后续接入真实配置中心
*/
import http from '@/api/request/http.uts'
import { env } from '@/api/env.uts'
import { storage } from '@/utils/storage.uts'
import http from "@/api/request/http.uts";
import { storage } from "@/utils/storage.uts";
const ENV_STR = env == 'production' ? 'prod' : env == 'develop' ? 'develop' : 'test'
const CONFIG_MODULE = 'app-tape'
const BOUTIQUE_CONFIG_MODULE = 'boutique-pad-config'
const CONFIG_BASE = 'https://config-center-backend.glsx.com.cn/glsxAdmin/config'
const CONFIG_URL = `${CONFIG_BASE}?moduleUrl=${CONFIG_MODULE}&env=${ENV_STR}`
const BOUTIQUE_CONFIG_URL = `${CONFIG_BASE}?moduleUrl=${BOUTIQUE_CONFIG_MODULE}&env=${ENV_STR}`
const ENV_STR = env == "production" ? "prod" : (env == "develop" ? "develop" : "test");
const CONFIG_MODULE = "app-tape";
const BOUTIQUE_CONFIG_MODULE = "boutique-pad-config";
const CONFIG_BASE = "https://config-center-backend.glsx.com.cn/glsxAdmin/config";
const CONFIG_URL = `${CONFIG_BASE}?moduleUrl=${CONFIG_MODULE}&env=${ENV_STR}`;
const BOUTIQUE_CONFIG_URL = `${CONFIG_BASE}?moduleUrl=${BOUTIQUE_CONFIG_MODULE}&env=${ENV_STR}`;
const _emptyList: any[] = [] as any[]
const _emptyList: any[] = [] as any[];
const defaultBoutiqueMock: UTSJSONObject = {
'createTime': 0,
'moduleList': _emptyList,
'toolList': _emptyList,
'defaultCarId': ''
}
"createTime": 0,
"moduleList": _emptyList,
"toolList": _emptyList,
"defaultCarId": ""
};
function parseStorageJson(key: string): UTSJSONObject | null {
const raw = storage.get(key)
if (raw == null) return null
if (typeof raw == 'string') {
const s = (raw as string).trim()
if (s == '' || s.length == 0) return null
function parseStorageJson(key: string): null | UTSJSONObject {
const raw = storage.get(key);
if (raw == null) return null;
if (typeof raw === "string") {
const s = (raw as string).trim();
if (s == "" || s.length === 0) return null;
try {
return JSON.parse(s) as UTSJSONObject
} catch (_) {
return null
return JSON.parse(s) as UTSJSONObject;
} catch {
return null;
}
}
return raw as UTSJSONObject
return raw as UTSJSONObject;
}
/** 获取 APP 配置 */
export function getMockData(immediate: boolean = false): Promise<UTSJSONObject> {
const cached = parseStorageJson('mock_data')
const cached = parseStorageJson("mock_data");
if (!immediate && cached != null) {
const createTime = (cached['createTime'] as number) ?? 0
const createTime = (cached.createTime as number) ?? 0;
if (Date.now() - createTime < 5 * 60 * 1000) {
return Promise.resolve(cached)
return Promise.resolve(cached);
}
}
return http.uni_request({ 'url': CONFIG_URL }).then((data: any): UTSJSONObject => {
const result = (data != null ? data : {}) as UTSJSONObject
result['createTime'] = Date.now()
storage.set('mock_data', result, 0)
return result
return http.uni_request({ "url": CONFIG_URL }).then((data: any): UTSJSONObject => {
const result = (data != null ? data : {}) as UTSJSONObject;
result.createTime = Date.now();
storage.set("mock_data", result, 0);
return result;
}).catch((): UTSJSONObject => {
const fallback: UTSJSONObject = { 'createTime': Date.now() }
return fallback
})
const fallback: UTSJSONObject = { "createTime": Date.now() };
return fallback;
});
}
/** 获取轻改配置(moduleList, toolList, defaultCarId) */
export function getBoutiqueMockData(immediate: boolean = false): Promise<UTSJSONObject> {
const cached = parseStorageJson('boutique_mock_data')
const cached = parseStorageJson("boutique_mock_data");
if (!immediate && cached != null) {
const createTime = (cached['createTime'] as number) ?? 0
const createTime = (cached.createTime as number) ?? 0;
if (Date.now() - createTime < 5 * 60 * 1000) {
return Promise.resolve(cached)
return Promise.resolve(cached);
}
}
return http.uni_request({ 'url': BOUTIQUE_CONFIG_URL }).then((data: any): UTSJSONObject => {
const result = (data != null ? data : {}) as UTSJSONObject
result['createTime'] = Date.now()
result['moduleList'] = result['moduleList'] != null ? result['moduleList'] : _emptyList
result['toolList'] = result['toolList'] != null ? result['toolList'] : _emptyList
result['defaultCarId'] = result['defaultCarId'] != null ? result['defaultCarId'] : ''
storage.set('boutique_mock_data', result, 0)
return result
return http.uni_request({ "url": BOUTIQUE_CONFIG_URL }).then((data: any): UTSJSONObject => {
const result = (data != null ? data : {}) as UTSJSONObject;
result.createTime = Date.now();
result.moduleList = result.moduleList != null ? result.moduleList : _emptyList;
result.toolList = result.toolList != null ? result.toolList : _emptyList;
result.defaultCarId = result.defaultCarId != null ? result.defaultCarId : "";
storage.set("boutique_mock_data", result, 0);
return result;
}).catch((): UTSJSONObject => {
const fallback = { ...defaultBoutiqueMock, 'createTime': Date.now() } as UTSJSONObject
return fallback
})
const fallback = { ...defaultBoutiqueMock, "createTime": Date.now() } as UTSJSONObject;
return fallback;
});
}
/**
* 获取后台延保素材ID
*/
export function getEquityMaterialId(data: UTSJSONObject): Promise<any> {
return http.post({
method: 'dj.api.smartcarlife.reception.home.page.material.view',
projectName: 'boutique',
...data
} as UTSJSONObject)
return http.post({
method: "dj.api.smartcarlife.reception.home.page.material.view",
projectName: "boutique",
...data
} as UTSJSONObject);
}
/**
* 获取后台延保素材配置
*/
export function getEquityMaterialConfig(data: UTSJSONObject): Promise<any> {
return http.post({
method: 'dj.api.car.boutique.reception.home.page.entrance.material.detail',
projectName: 'boutique',
...data
} as UTSJSONObject)
return http.post({
method: "dj.api.car.boutique.reception.home.page.entrance.material.detail",
projectName: "boutique",
...data
} as UTSJSONObject);
}
/**
* 权益配置
*/
export function findReceptionpriproConfigList(data: UTSJSONObject): Promise<any> {
return http.post({
method: 'dj.api.smartcarlife.recepiton.customer.findReceptionpriproConfigList',
projectName: 'boutique',
...data
} as UTSJSONObject)
return http.post({
method: "dj.api.smartcarlife.recepiton.customer.findReceptionpriproConfigList",
projectName: "boutique",
...data
} as UTSJSONObject);
}
/**获取素材配置 */
/** 获取素材配置 */
export async function getSoureData(
shopMerchantId: string | number,
sceneType: string | number,
params: UTSJSONObject = {}
shopMerchantId: number | string,
sceneType: number | string,
params: UTSJSONObject = {}
): Promise<any> {
try {
const res = await getEquityMaterialId({
merchantId: shopMerchantId,
...params
})
try {
const res = await getEquityMaterialId({
merchantId: shopMerchantId,
...params
});
if (res != null && (res as UTSJSONObject).id != null) {
console.log((res as UTSJSONObject).id, 'res.idres.idres.idres.id')
if (res != null && (res as UTSJSONObject).id != null) {
console.log((res as UTSJSONObject).id, "res.idres.idres.idres.id");
let data = await getEquityMaterialConfig({
id: (res as UTSJSONObject).id
})
const data = await getEquityMaterialConfig({
id: (res as UTSJSONObject).id
});
if (data != null) {
const dataObj = data as UTSJSONObject
const storageName = `source_${sceneType}_${shopMerchantId}`
let toolList: Array<any> = []
if (dataObj.toolList != null) {
toolList = dataObj.toolList as Array<any>
}
let materialInfoList: Array<any> = []
if (dataObj.materialInfoList != null) {
materialInfoList = dataObj.materialInfoList as Array<any>
}
if (data != null) {
const dataObj = data as UTSJSONObject;
const storageName = `source_${sceneType}_${shopMerchantId}`;
let toolList: Array<any> = [];
if (dataObj.toolList != null) {
toolList = dataObj.toolList as Array<any>;
}
let materialInfoList: Array<any> = [];
if (dataObj.materialInfoList != null) {
materialInfoList = dataObj.materialInfoList as Array<any>;
}
const insurance = (materialInfoList as Array<any>).find((e: any) => (e as UTSJSONObject).componentName == 'insurance')
const hasEquity = (toolList as Array<any>).find((e: any) => (e as UTSJSONObject).id == (insurance as UTSJSONObject).id)
const insurance = (materialInfoList as Array<any>).find((e: any) => (e as UTSJSONObject).componentName == "insurance");
const hasEquity = (toolList as Array<any>).find((e: any) => (e as UTSJSONObject).id == (insurance as UTSJSONObject).id);
if (insurance != null && hasEquity != null) {
let configList: Array<any> = []
if (insurance != null && hasEquity != null) {
let configList: Array<any> = [];
try {
configList = await findReceptionpriproConfigList({}) as Array<any>
storage.set('findReceptionpriproConfigList', configList, 0)
} catch (error) {
configList = storage.get('findReceptionpriproConfigList') as Array<any>
}
try {
configList = await findReceptionpriproConfigList({}) as Array<any>;
storage.set("findReceptionpriproConfigList", configList, 0);
} catch {
configList = storage.get("findReceptionpriproConfigList") as Array<any>;
}
const toolOtherList = (configList as Array<any>).map((i: any) => {
return {
id: ((hasEquity as UTSJSONObject).id as number) + 100 + ((i as UTSJSONObject).id as number),
shortTitle: (i as UTSJSONObject).productName,
shortTitleUrl: (i as UTSJSONObject).procuctLog
} as UTSJSONObject
})
const toolOtherList = (configList as Array<any>).map((i: any) => {
return {
id: ((hasEquity as UTSJSONObject).id as number) + 100 + ((i as UTSJSONObject).id as number),
shortTitle: (i as UTSJSONObject).productName,
shortTitleUrl: (i as UTSJSONObject).procuctLog
} as UTSJSONObject;
});
toolList = toolList.concat(toolOtherList)
toolList = toolList.concat(toolOtherList);
const moduleOtherList = (configList as Array<any>).map((i: any) => {
return {
id: ((hasEquity as UTSJSONObject).id as number) + 100 + ((i as UTSJSONObject).id as number),
title: (i as UTSJSONObject).productName,
shortTitleUrl: (i as UTSJSONObject).procuctLog,
productPoster: (i as UTSJSONObject).productPoster,
showAlt: false,
componentName: 'CaseCenter',
receptionpriproCusCaseList: (i as UTSJSONObject).receptionpriproCusCaseList,
hide: true,
detailTitle: (i as UTSJSONObject).productName,
thumbnail: 'https://img02.glsx.com.cn/weapp/resource/app-tape/common/qsyw.webp'
} as UTSJSONObject
})
const moduleOtherList = (configList as Array<any>).map((i: any) => {
return {
id: ((hasEquity as UTSJSONObject).id as number) + 100 + ((i as UTSJSONObject).id as number),
title: (i as UTSJSONObject).productName,
shortTitleUrl: (i as UTSJSONObject).procuctLog,
productPoster: (i as UTSJSONObject).productPoster,
showAlt: false,
componentName: "CaseCenter",
receptionpriproCusCaseList: (i as UTSJSONObject).receptionpriproCusCaseList,
hide: true,
detailTitle: (i as UTSJSONObject).productName,
thumbnail: "https://img02.glsx.com.cn/weapp/resource/app-tape/common/qsyw.webp"
} as UTSJSONObject;
});
materialInfoList = materialInfoList.concat(moduleOtherList)
}
materialInfoList = materialInfoList.concat(moduleOtherList);
}
dataObj.toolList = await imgTransformBase64(toolList, ['shortTitleUrl'])
dataObj.moduleList = await imgTransformBase64(materialInfoList, ['thumbnail', 'receptionSourceDetailList', 'screenList'])
dataObj.toolList = await imgTransformBase64(toolList, ["shortTitleUrl"]);
dataObj.moduleList = await imgTransformBase64(materialInfoList, ["thumbnail", "receptionSourceDetailList", "screenList"]);
uni.setStorageSync(storageName, {
moduleList: dataObj.moduleList,
toolList: dataObj.toolList,
id: (res as UTSJSONObject).id
})
uni.setStorageSync(storageName, {
moduleList: dataObj.moduleList,
toolList: dataObj.toolList,
id: (res as UTSJSONObject).id
});
return Promise.resolve(dataObj)
} else {
throw new Error('获取数据失败')
}
} else {
throw new Error('未找到素材 ID')
}
} catch (error) {
uni.hideLoading()
if (error != null) {
uni.showToast({
title: `${error}`,
icon: 'none',
duration: 2000
})
}
return Promise.reject(error)
}
return dataObj;
} else {
throw new Error("获取数据失败");
}
} else {
throw new Error("未找到素材 ID");
}
} catch (error) {
uni.hideLoading();
if (error != null) {
uni.showToast({
title: `${error}`,
icon: "none",
duration: 2000
});
}
return Promise.reject(error);
}
}
/**批量图片转 base64 */
/** 批量图片转 base64 */
async function imgTransformBase64(imgList: Array<any>= [], keyList: string[]): Promise<Array<any>> {
const result: Array<any> = []
for (let idx = 0; idx < imgList.length; idx++) {
const e = imgList[idx]
const eObj = e as UTSJSONObject
for (const key in eObj) {
if (keyList.includes(key)) {
const isArray = Array.isArray(eObj[key])
const result: Array<any> = [];
for (const e of imgList) {
const eObj = e as UTSJSONObject;
for (const key in eObj) {
if (keyList.includes(key)) {
const isArray = Array.isArray(eObj[key]);
if (isArray) {
const arr = eObj[key] as Array<any>
for (let i = 0; i < arr.length; i++) {
const item = arr[i]
const itemObj = item as UTSJSONObject
for (const k in itemObj) {
if (k == 'detailUrl' && itemObj[k] != null) {
itemObj[k] = await getBase64(itemObj[k] as string)
}
}
}
} else {
if (typeof eObj[key] === 'string' && eObj[key] != null) {
eObj[key] = await getBase64(eObj[key] as string)
}
if (eObj[key] != null && typeof eObj[key] === 'object') {
const nestedObj = eObj[key] as UTSJSONObject
for (const k in nestedObj) {
if (nestedObj[k] != null) {
nestedObj[k] = await getBase64(nestedObj[k] as string)
}
}
}
}
}
}
result.push(e)
}
return result
if (isArray) {
const arr = eObj[key] as Array<any>;
for (const item of arr) {
const itemObj = item as UTSJSONObject;
for (const k in itemObj) {
if (k == "detailUrl" && itemObj[k] != null) {
itemObj[k] = await getBase64(itemObj[k] as string);
}
}
}
} else {
if (typeof eObj[key] === "string" && eObj[key] != null) {
eObj[key] = await getBase64(eObj[key] as string);
}
if (eObj[key] != null && typeof eObj[key] === "object") {
const nestedObj = eObj[key] as UTSJSONObject;
for (const k in nestedObj) {
if (nestedObj[k] != null) {
nestedObj[k] = await getBase64(nestedObj[k] as string);
}
}
}
}
}
}
result.push(e);
}
return result;
}
/**转 base64 */
/** 转 base64 */
async function getBase64(url: string): Promise<string> {
return new Promise((resolve, reject) => {
uni.request({
url,
method: 'GET',
responseType: 'arraybuffer',
success: res => {
const base64 = `data:image/png;base64,${uni.arrayBufferToBase64(res.data as ArrayBuffer)}`
resolve(base64)
},
fail: err => {
resolve(url)
}
})
})
return new Promise((resolve, reject) => {
uni.request({
url,
method: "GET",
responseType: "arraybuffer",
success: res => {
const base64 = `data:image/png;base64,${uni.arrayBufferToBase64(res.data as ArrayBuffer)}`;
resolve(base64);
},
fail: err => {
resolve(url);
}
});
});
}
<template>
<view class="entrance-box">
<view class="entrance-list">
<view
v-for="(item, index) in entranceList"
:key="index"
class="entrance-item"
@click="handleClick(item)"
>
<view class="entrance-icon" :style="{ backgroundColor: item.color }"></view>
<text class="entrance-name">{{ item.label }}</text>
</view>
<view class="entrance-box">
<view class="entrance-list">
<view v-for="(item, index) in entranceList"
:key="index"
class="entrance-item"
@click="handleClick(item)">
<!-- App 端需用相对路径,便于打包时基于当前文件解析并打入包内 -->
<image v-if="item.icon === 'daily-report'"
class="entrance-icon"
mode="aspectFit"
src="../static/images/boutique/tools/daily-report.png" />
<image v-else-if="item.icon === 'create-order'"
class="entrance-icon"
mode="aspectFit"
src="../static/images/boutique/tools/create-order.png" />
<image v-else-if="item.icon === 'equity-order'"
class="entrance-icon"
mode="aspectFit"
src="../static/images/boutique/tools/equity-order.png" />
<image v-else-if="item.icon === 'defeat-order'"
class="entrance-icon"
mode="aspectFit"
src="../static/images/boutique/tools/defeat-order.png" />
<image v-else-if="item.icon === 'order-management'"
class="entrance-icon"
mode="aspectFit"
src="../static/images/boutique/tools/order-management.png" />
<image v-else-if="item.icon === 'wage-appeal'"
class="entrance-icon"
mode="aspectFit"
src="../static/images/boutique/tools/wage-appeal.png" />
<image v-else
class="entrance-icon"
mode="aspectFit"
src="../static/images/boutique/tools/daily-report.png" />
<text class="entrance-name">{{ item.label }}</text>
</view>
</view>
</view>
</view>
</template>
<script setup lang="uts">
import { computed } from 'vue'
import { computed } from "vue";
type EntranceItem = {
label: string
color: string
icon: string
label: string
}
const props = defineProps<{
sceneType?: number
}>()
}>();
defineEmits(['entranceClick'])
defineEmits(["entranceClick"]);
const entranceList = computed((): EntranceItem[] => {
const sceneType = props.sceneType ?? 1
if (sceneType == 1) {
return [
{ label: '驻店日报', color: '#7c4dff' },
{ label: '新建工单', color: '#4673ff' },
{ label: '战败下单', color: '#ff4747' },
{ label: '工单列表', color: '#ff8c00' },
{ label: '工资申诉', color: '#ffc107' }
]
}
if (sceneType == 0) {
return [
{ label: '驻店日报', color: '#7c4dff' },
{ label: '新建工单', color: '#4673ff' },
{ label: '权益提单', color: '#4caf50' },
{ label: '战败下单', color: '#ff4747' },
{ label: '工单列表', color: '#ff8c00' },
{ label: '工资申诉', color: '#ffc107' }
]
}
return [
{ label: '驻店日报', color: '#7c4dff' },
{ label: '新建工单', color: '#4673ff' },
{ label: '战败下单', color: '#ff4747' },
{ label: '工单列表', color: '#ff8c00' },
{ label: '工资申诉', color: '#ffc107' }
]
})
const sceneType = props.sceneType ?? 1;
if (sceneType === 1) {
// 轻改场景:对应老项目 icon-daily-report / icon-create-order / icon-defeat-order / icon-order-management / icon-wage-appeal
return [
{ label: "驻店日报", icon: "daily-report", color: "#7c4dff" },
{ label: "新建工单", icon: "create-order", color: "#4673ff" },
{ label: "战败下单", icon: "defeat-order", color: "#ff4747" },
{ label: "工单列表", icon: "order-management", color: "#ff8c00" },
{ label: "工资申诉", icon: "wage-appeal", color: "#ffc107" }
];
}
if (sceneType === 0) {
// 权益场景:在轻改基础上增加“权益提单” icon-equity-order
return [
{ label: "驻店日报", icon: "daily-report", color: "#7c4dff" },
{ label: "新建工单", icon: "create-order", color: "#4673ff" },
{ label: "权益提单", icon: "equity-order", color: "#4caf50" },
{ label: "战败下单", icon: "defeat-order", color: "#ff4747" },
{ label: "工单列表", icon: "order-management", color: "#ff8c00" },
{ label: "工资申诉", icon: "wage-appeal", color: "#ffc107" }
];
}
// 其它场景兜底:先复用轻改配置
return [
{ label: "驻店日报", icon: "daily-report", color: "#7c4dff" },
{ label: "新建工单", icon: "create-order", color: "#4673ff" },
{ label: "战败下单", icon: "defeat-order", color: "#ff4747" },
{ label: "工单列表", icon: "order-management", color: "#ff8c00" },
{ label: "工资申诉", icon: "wage-appeal", color: "#ffc107" }
];
});
function handleClick(item: EntranceItem): void {
uni.showToast({ title: '敬请期待', icon: 'none' })
function handleClick(_item: EntranceItem): void {
uni.showToast({ title: "敬请期待", icon: "none" });
}
</script>
......@@ -77,7 +107,7 @@ function handleClick(item: EntranceItem): void {
}
.entrance-item {
width: 80px;
width: 100px;
display: flex;
flex-direction: column;
align-items: center;
......@@ -92,8 +122,8 @@ function handleClick(item: EntranceItem): void {
}
.entrance-name {
font-size: var(--l-font-sm);
font-size: 12px;
color: #333;
margin-top: var(--l-spacing-xs);
margin-top: 6px;
}
</style>
......@@ -15,10 +15,10 @@
<view v-for="(item, index) in tabs"
:key="index"
class="tab-item"
:class="[tabIndex == index ? 'tabActive' : '']"
:class="[currentTabIndex === index ? 'tabActive' : '']"
@click="onChangeTab(index)">
<view class="icon-box">
<view class="icon-placeholder" :class="[tabIndex == index ? 'icon-active' : '']"></view>
<view class="icon-placeholder" :class="[currentTabIndex === index ? 'icon-active' : '']"></view>
</view>
<text class="tab-label">{{ item.label }}</text>
</view>
......@@ -45,8 +45,13 @@
<view v-for="(item, index) in tabs"
:key="index"
class="tab-item tab-item-inline"
:class="[tabIndex == index ? 'tabActive' : '']"
:class="[currentTabIndex === index ? 'tabActive' : '']"
@click="onChangeTab(index)">
<view class="tab-icon-wrap">
<image class="tab-icon"
mode="aspectFit"
:src="getTabIconSrc(item.icon, currentTabIndex === index)" />
</view>
<text class="tab-label">{{ item.label }}</text>
</view>
</view>
......@@ -77,6 +82,11 @@ const isPortraitMode = computed((): boolean => {
return props.isPortrait === true;
});
const currentTabIndex = computed((): number => {
const idx = props.tabIndex as null | number;
return idx != null ? idx : 0;
});
type SceneTypeItem = { describe: string; icon: string; title: string; }
function getSceneTypeItem(sceneId: number): null | SceneTypeItem {
......@@ -139,14 +149,33 @@ const sceneTypeIdList = computed((): number[] => {
return result;
});
const tabs = [
type TabItem = {
label: string;
icon: string;
name: string;
};
const tabs: TabItem[] = [
{ label: "首页", icon: "home", name: "HomeSlot" },
{ label: "接待中心", icon: "record", name: "ReceptionCenter" },
{ label: "学习中心", icon: "study", name: "StudyCenter" },
{ label: "场景集市", icon: "scene", name: "SceneMarket" },
{ label: "活动中心", icon: "activity", name: "ActivityCenter" }
// { label: "场景集市", icon: "scene", name: "SceneMarket" },
// { label: "活动中心", icon: "activity", name: "ActivityCenter" }
];
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";
}
return "/static/images/tabbar/home.png";
}
const userName = computed((): string => {
const info = props.userInfo;
if (info == null) {
......@@ -284,6 +313,19 @@ function jumpPersonCenter(): void {
color: #3773f8;
}
.tab-icon-wrap {
width: 24px;
height: 24px;
display: flex;
justify-content: center;
align-items: center;
}
.tab-icon {
width: 24px;
height: 24px;
}
.portrait-action {
flex-shrink: 0;
}
......@@ -317,7 +359,6 @@ function jumpPersonCenter(): void {
align-items: center;
box-sizing: border-box;
position: relative;
text-align: center;
}
.user-avatar {
......@@ -354,12 +395,11 @@ function jumpPersonCenter(): void {
}
.tab-item {
width: 52px; /* toRpx(104) / 2 */
width: 80px; /* toRpx(104) / 2 */
display: flex;
flex-direction: column;
align-items: center;
margin-bottom: 12.5px; /* toRpx(25) / 2 */
text-align: center;
}
.icon-box {
......@@ -386,6 +426,7 @@ function jumpPersonCenter(): void {
font-size: 13px; /* toRpx(26) / 2 */
color: #8a98b5;
margin-top: 6px; /* toRpx(12) / 2 */
text-align: center;
}
.tabActive .tab-label {
......@@ -406,6 +447,9 @@ function jumpPersonCenter(): void {
}
.tab-item-inline {
flex-direction: row;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
</style>
......@@ -11,9 +11,6 @@
<!-- 横屏三卡片布局:轻改等使用 swiperCustom -->
<view v-if="useCardLayout && tabIndex == 0" class="app-content-box right-content show-content-box">
<view class="start" @click="onStartClick">
<image class="start-bg-img"
:mode="isPortraitMode ? 'aspectFill' : 'scaleToFill'"
src="/static/images/home/start-btn.png" />
<view class="start-inner">
<text class="start-text">开始接待</text>
</view>
......@@ -60,9 +57,6 @@
<!-- 横屏三卡片布局:轻改等使用 swiperCustom -->
<view v-if="useCardLayout && tabIndex == 0" class="app-content-box right-content show-content-box">
<view class="start" @click="onStartClick">
<image class="start-bg-img"
mode="scaleToFill"
src="/static/images/home/start-btn.png" />
<view class="start-inner">
<text class="start-text">开始接待</text>
</view>
......@@ -259,7 +253,7 @@ defineExpose({
}
.app-content-box {
margin-top: 50px;
margin-top: 40px;
flex: 1;
display: flex;
flex-direction: column;
......@@ -274,26 +268,16 @@ defineExpose({
.start {
height: 86px;
box-sizing: border-box;
margin-right: 32px;
position: relative;
display: flex;
justify-content: center;
align-items: flex-start;
padding-top: 30px;
padding-top: 36px;
overflow: hidden;
flex-shrink: 0;
min-width: 140px;
}
.start-bg-img {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
z-index: 0;
pointer-events: none;
/* 与旧项目 background-size: 100% 100% 一致,铺满容器 */
border-radius: 18px;
background: #5b8cff;
}
.start-inner {
......@@ -309,7 +293,7 @@ defineExpose({
}
.start-text {
font-size: 20px;
font-size: 16px;
font-weight: 600;
color: #ffffff;
text-align: center;
......@@ -332,7 +316,7 @@ defineExpose({
}
.content-left {
width: var(--l-content-left-width);
width: 100%;
flex-shrink: 0;
display: flex;
flex-direction: column;
......@@ -364,8 +348,8 @@ defineExpose({
}
.title-text {
font-size: var(--l-font-lg);
font-weight: 600;
font-size: 16px;
font-weight: 500;
color: #333;
}
......
......@@ -28,15 +28,13 @@
{
"path": "pages/boutique/index",
"style": {
"navigationStyle": "custom",
"pageOrientation": "landscape"
"navigationStyle": "custom"
}
},
{
"path": "pages/boutique/portrait",
"style": {
"navigationStyle": "custom",
"pageOrientation": "portrait"
"navigationStyle": "custom"
}
},
{
......@@ -59,7 +57,7 @@
}
},
{
"path":"pages/equity/detail/index",
"path": "pages/equity/detail/index",
"style": {
"navigationStyle": "custom"
}
......@@ -75,7 +73,7 @@
"^no-data$": "@/pages/common/components/NoData.uvue",
"^home-frame$": "@/components/HomeFrame/index.uvue",
"^layout-root$": "@/components/LayoutRoot/index.uvue",
"^Layout$": "@/components/Layout/index.uvue"
"^Layout$": "@/components/Layout/index.uvue"
}
},
"globalStyle": {
......
<template>
<view class="page-container container">
<!-- 与旧项目一致:页面背景图 home-bg-1.webp -->
<view class="page-bg"></view>
<HomeFrame ref="homeRef"
:show-footer="true"
:swiper-custom="true"
@change-tab="onChangeTab"
@start="handleStart">
<template #swiperCustom>
<view v-if="loadComplete" class="swiper-custom-wrap">
<view v-if="packageList.length > 0" class="swiper-custom-content">
<swiper class="package-swiper"
:current="currentSwiperIndex"
@change="onSwiperChange">
<swiper-item v-for="(item, idx) in packageList"
:key="idx"
@tap="toDetail(idx)">
<image v-if="getPkg(item, 'bannerImg')"
class="swiper-bg"
mode="aspectFill"
:src="getPkg(item, 'bannerImg')" />
<view class="swiper-name">
{{ getPkg(item, 'name') }}
</view>
<view class="swiper-content-box">
<view class="price price-1">
<text class="price-label">市场价</text>
<view class="num">
<text class="unit">¥</text>
<text>{{ getPkg(item, 'marketPrice') }}</text>
</view>
</view>
<view class="price price-2">
{{ getPkg(item, 'discountPrice') }}
</view>
<view class="price price-3">
<text class="price-label">套餐价</text>
<view class="num">
<text class="unit">¥</text>
<text>{{ getPkg(item, 'packagePrice') }}</text>
</view>
</view>
<view class="briefIntroduction">
{{ getPkg(item, 'briefIntroduction') }}
</view>
</view>
<view class="swiper-btn">
查看详情
</view>
</swiper-item>
</swiper>
<view class="swiper-dots">
<view v-for="(_, i) in packageList"
:key="i"
class="dot"
:class="[{ active: i == currentSwiperIndex }]" />
</view>
</view>
<view v-else class="swiper-empty">
<text class="empty-text">{{ swiperNoDataObject.text }}</text>
</view>
</view>
<view v-else class="swiper-loading">
<text>加载中...</text>
</view>
</template>
<template #detail>
<view class="detail-content">
<text class="detail-title">详情页</text>
</view>
</template>
</HomeFrame>
<CenterPopup ref="customerTypeRef"
:list="typeList"
title="请选择当前洽谈的客户类型"
@choose="chooseCustomerType" />
<PackageDetailPopup ref="packageRef" @close="closePackageDetail">
<view class="package-detail-box">
<view class="package-box">
<view class="package-name">
套餐内容
</view>
<view class="package-content">
<rich-text :nodes="chooseItem.content ?? ''"></rich-text>
</view>
</view>
<view class="package-box package-detail">
<view class="package-name">
套餐介绍
</view>
<view class="package-content">
<rich-text :nodes="chooseItem.scriptIntroduction ?? ''"></rich-text>
</view>
</view>
</view>
</PackageDetailPopup>
</view>
</template>
<script setup lang="uts">
import { ref, type Ref } from "vue";
import CenterPopup from "@/components/CenterPopup.uvue";
import HomeFrame from "@/components/HomeFrame/index.uvue";
import PackageDetailPopup from "@/pages/boutique/components/PackageDetailPopup.uvue";
import type { BoutiqueLogic } from "@/pages/boutique/useBoutiqueLogic.uts";
const props = defineProps<{ logic: BoutiqueLogic }>();
const homeRef = ref(null);
const customerTypeRef = ref(null);
const packageRef = ref(null);
const loadComplete = props.logic.loadComplete;
const packageList = props.logic.packageList;
const currentSwiperIndex = props.logic.currentSwiperIndex;
const swiperNoDataObject = props.logic.swiperNoDataObject;
const typeList = props.logic.typeList;
const chooseItem = props.logic.chooseItem;
function getPkg(item: any, key: string): any {
return props.logic.getPkg(item, key);
}
function onSwiperChange(e: any): void {
props.logic.onSwiperChange(e);
}
function onChangeTab(index: number): void {
props.logic.onChangeTab(index);
}
function handleStart(): void {
const comp = customerTypeRef.value;
if (comp != null) {
const obj = comp as UTSJSONObject;
const openFn = obj["open"];
if (openFn != null && typeof openFn === "function") {
(openFn as () => void)();
}
}
}
function chooseCustomerType(index: number): void {
// UTS: ref(null) 的 value 可能被推断为 Nothing?,这里显式断言为 any
props.logic.chooseCustomerType(homeRef.value as any, index);
}
function toDetail(index: number): void {
const item = packageList.value[index];
if (item != null) {
chooseItem.value = item as UTSJSONObject;
const p = packageRef.value as null | UTSJSONObject;
const openFn = p != null ? p["open"] : null;
if (openFn != null && typeof openFn === "function") {
(openFn as () => void)();
}
}
}
function closePackageDetail(): void {
chooseItem.value = {};
}
function updateHome(): void {
const h = homeRef.value as null | UTSJSONObject;
if (h == null) return;
const fn = h["updateApp"];
if (fn != null && typeof fn === "function") {
(fn as () => void)();
}
}
defineExpose({
updateHome
});
</script>
<style scoped lang="scss">
.page-container {
width: 100%;
height: 100%;
position: relative;
}
.container {
position: relative;
}
.page-bg {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
z-index: -1;
background-image: url('@/assets/images/common/home-bg-1.webp');
background-size: cover;
background-repeat: no-repeat;
}
.swiper-custom-wrap {
width: 100%;
height: 100%;
position: relative;
}
.swiper-custom-content {
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
}
.package-swiper {
flex: 1;
width: 100%;
}
.swiper-bg {
position: absolute;
width: 100%;
height: 100%;
top: 0;
left: 0;
z-index: -1;
}
.swiper-name {
padding-top: var(--l-spacing-lg);
text-indent: 67px;
color: #333;
font-size: var(--l-font-base);
font-weight: 500;
}
.swiper-content-box {
margin: var(--l-spacing-md) var(--l-spacing-xl) 0;
height: 132px;
position: relative;
}
.swiper-content-box .price,
.swiper-content-box .briefIntroduction {
position: absolute;
}
.price-1 {
color: #999;
font-size: 10px;
left: var(--l-spacing-xl);
top: 32px;
width: 97px;
text-align: center;
}
.price-1 .num {
color: #333;
font-size: var(--l-font-base);
font-weight: 700;
display: flex;
justify-content: center;
}
.price-1 .unit {
margin-right: 4px;
}
.price-2 {
left: 129px;
top: 48px;
width: 94px;
color: #ff4747;
font-size: var(--l-font-lg);
font-weight: 700;
display: flex;
justify-content: center;
}
.price-3 {
top: 27px;
left: 228px;
color: #999;
font-size: 14px;
width: 148px;
text-align: center;
}
.price-3 .num {
color: #ff4747;
font-size: 22px;
font-weight: 700;
display: flex;
justify-content: center;
}
.price-3 .unit {
margin-right: 8px;
}
.briefIntroduction {
left: 0;
top: 106px;
color: #666;
font-size: 12px;
width: 100%;
text-align: center;
}
.swiper-btn {
color: #4673ff;
font-size: 13px;
text-align: center;
margin-top: var(--l-spacing-md);
}
.swiper-dots {
display: flex;
flex-direction: row;
justify-content: center;
padding: var(--l-spacing-sm) 0;
}
.dot {
width: 8px;
height: 8px;
border-radius: 4px;
background: #ccc;
margin: 0 4px;
}
.dot.active {
background: #4673ff;
}
.swiper-empty,
.swiper-loading {
width: 100%;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
}
.empty-text {
font-size: var(--l-font-sm);
color: #999;
}
.detail-content {
width: 100%;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
}
.detail-title {
font-size: var(--l-font-2xl);
color: #333;
}
.package-detail-box {
padding-bottom: 50px;
margin: 0 var(--l-spacing-xl);
}
.package-box {
border-radius: var(--l-radius-xl);
background: #ffffff;
box-shadow: 0 6px 24px rgba(44, 102, 247, 0.15);
margin-bottom: var(--l-spacing-xl);
box-sizing: border-box;
padding: var(--l-spacing-xl);
}
.package-name {
color: #333;
font-size: var(--l-font-xl);
font-weight: 500;
line-height: 28px;
margin-bottom: var(--l-spacing-md);
}
.package-content {
line-height: 22px;
color: #333;
font-size: 14px;
}
.package-detail {
border: 2px solid rgba(70, 115, 255, 0.5);
background: rgba(70, 115, 255, 0.1);
box-shadow: 0 6px 24px rgba(44, 102, 247, 0.15);
}
.package-detail .package-name {
color: #4673ff;
}
</style>
<template>
<view class="page-container">
<HomeFrame ref="homeRef"
:show-footer="true"
:swiper-custom="true"
@start="handleStart">
<template #swiperCustom>
<view v-if="loadComplete" class="swiper-custom-wrap">
<swiper v-if="packageList.length > 0"
class="package-swiper"
:current="currentSwiperIndex"
@change="onSwiperChange">
<swiper-item v-for="(item, idx) in packageList"
:key="idx"
@tap="toDetail(idx)">
<view class="swiper-custom-content">
<image class="bg"
mode="aspectFill"
:src="getBanner(item)" />
</view>
</swiper-item>
</swiper>
<view v-if="packageList.length > 0" class="swiper-dots">
<view v-for="(_, i) in packageList"
:key="i"
class="dot"
:class="[{ active: i === currentSwiperIndex }]" />
</view>
<view v-else class="swiper-empty">
<text class="empty-text">敬请期待</text>
</view>
</view>
<view v-else class="swiper-loading">
<text>加载中...</text>
</view>
</template>
<template #detail>
<view class="detail-content">
<text class="detail-title">详情页</text>
</view>
</template>
</HomeFrame>
</view>
</template>
<script setup lang="uts">
import { ref } from "vue";
import HomeFrame from "@/components/HomeFrame/index.uvue";
import type { BoutiqueLogic } from "@/pages/boutique/useBoutiqueLogic.uts";
type NavigateToFailLike = {
errCode: number;
errMsg: string;
errSubject: string;
message: null | string;
};
const props = defineProps<{ logic: BoutiqueLogic }>();
const homeRef = ref(null);
const loadComplete = props.logic.loadComplete;
const packageList = props.logic.packageList;
const currentSwiperIndex = props.logic.currentSwiperIndex;
function getBanner(item: any): string {
return props.logic.getPkg(item, "bannerImg") as string;
}
function onSwiperChange(e: any): void {
props.logic.onSwiperChange(e);
}
function toDetail(_index: number): void {
uni.showToast({ title: "套餐详情", icon: "none" });
}
function handleStart(): void {
uni.navigateTo({
url: "/pages/reception/record",
fail: (e: any) => {
const err = e as NavigateToFailLike;
const msg = err.message !== null && err.message !== "" ? err.message : "";
console.error("[navigateTo] /pages/reception/record fail:", msg, JSON.stringify(e));
uni.showToast({ title: "跳转失败", icon: "none" });
}
});
}
function updateHome(): void {
const h = homeRef.value as null | UTSJSONObject;
if (h == null) return;
const fn = h["updateApp"];
if (fn != null && typeof fn === "function") {
(fn as () => void)();
}
}
defineExpose({
updateHome
});
</script>
<style scoped lang="scss">
.page-container {
width: 100%;
height: 100%;
}
.swiper-custom-wrap {
width: 100%;
height: 100%;
}
.package-swiper {
width: 100%;
height: 100%;
}
.swiper-custom-content {
width: 100%;
height: 100%;
position: relative;
}
.bg {
position: absolute;
width: 100%;
height: 100%;
top: 0;
left: 0;
z-index: -1;
}
.swiper-dots {
display: flex;
flex-direction: row;
justify-content: center;
padding: 12px 0;
}
.dot {
width: 8px;
height: 8px;
border-radius: 4px;
background: #ccc;
margin: 0 4px;
}
.dot.active {
background: #4673ff;
}
.swiper-empty,
.swiper-loading {
width: 100%;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
}
.empty-text {
font-size: 14px;
color: #999;
}
.detail-content {
width: 100%;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
}
.detail-title {
font-size: 24px;
color: #333;
}
</style>
<template>
<!-- #ifdef APP -->
<layout-root>
<!-- #endif -->
<view class="page-container container">
......@@ -100,11 +99,10 @@
</view>
<!-- #ifdef APP -->
</layout-root>
<!-- #endif -->
</template>
<script setup lang="uts">
import { ref } from "vue";
import { computed, ref } from "vue";
import { getBoutiquePackageList as apiGetBoutiquePackageList, getBoutiqueMaterialConfig } from "@/api/boutique-api.uts";
import { getEmployeeListApi } from "@/api/common-api.uts";
......@@ -159,11 +157,8 @@ const typeList = [
{ title: "现场客户", describe: "客户未领取精品券\n首次到店", icon: "icon-customer-2" }
];
function clearHistory(): void {
dispatch("clearCustomerInfo");
dispatch("clearHistory");
dispatch("clearReceptionTrack");
}
const landscapeRef = ref(null);
const portraitRef = ref(null);
function jumpPage(pid: string): void {
const list = carBannerList.value;
......@@ -196,15 +191,12 @@ function handleStart(): void {
}
}
function chooseCustomerType(index: number): void {
customerType.value = index;
if (index == 0) {
const ml = moduleList.value;
if (ml.length >= 3) {
const mid = (ml[2] as UTSJSONObject).id;
jumpPage(mid != null ? (mid as any).toString() : "");
} else {
jumpPage("");
function updateCurrentHome(): void {
if (isPortrait.value) {
const p = portraitRef.value as null | UTSJSONObject;
const fn = p !== null ? p.updateHome : null;
if (fn !== null && typeof fn === "function") {
(fn as () => void)();
}
} else {
jumpPage("");
......@@ -350,11 +342,6 @@ async function getBoutiquePackageList(): Promise<void> {
list.push(e);
}
}
packageList.value = list;
} catch {
packageList.value = [];
} finally {
loadComplete.value = true;
}
}
......@@ -389,10 +376,7 @@ onShow(async () => {
}
getBoutiquePackageList();
setTimeout((): void => {
const home = homeRef.value;
if (home != null) {
callExposedMethod(home, "updateApp");
}
updateCurrentHome();
}, 0);
});
</script>
......
<template>
<!-- #ifdef APP -->
<layout-root>
<!-- #endif -->
<view class="page-container">
<home-frame
ref="homeRef"
:showFooter="true"
:swiperCustom="true"
@start="handleStart"
>
<template #swiperCustom>
<view class="swiper-custom-placeholder">
<text class="package-title">套餐火爆热卖</text>
<text class="coming-soon">敬请期待</text>
</view>
</template>
<template #detail>
<view class="detail-content">
<text class="detail-title">详情页</text>
</view>
</template>
</home-frame>
</view>
<!-- #ifdef APP -->
</layout-root>
<!-- #endif -->
<!-- 兼容旧路由:统一跳转到单入口 /pages/boutique/index,由入口页内部决定横竖屏 -->
<view class="redirect-placeholder"></view>
</template>
<script setup lang="uts">
import { ref, ComponentPublicInstance } from 'vue'
// import { onLoad, onShow } from '@dcloudio/uni-app'
import { storage } from '@/utils/storage.uts'
import HomeFrame from '@/components/HomeFrame/index.uvue'
import { ComponentPublicInstance, ref } from "vue";
import { storage } from "@/utils/storage.uts";
import { onLoad, onShow } from "@dcloudio/uni-app";
const homeRef = ref(null)
const homeRef = ref(null);
function handleStart(): void {
uni.showToast({
title: '开始接待',
icon: 'success'
})
function redirect(): void {
uni.reLaunch({ url: "/pages/boutique/index" });
}
onLoad((options: OnLoadOptions) => {
uni.hideLoading()
})
onLoad((_options: OnLoadOptions) => {
uni.hideLoading();
redirect();
});
onShow(() => {
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 | null
const shopMerchantName = userInfoObj['shopMerchantName'] as string | null
if (shopMerchantId == null || shopMerchantId == '' || shopMerchantName == null || shopMerchantName == '') {
storage.remove('userInfo')
storage.remove('sessionId')
uni.reLaunch({ url: '/pages/common/login/index' })
return
}
if (homeRef.value != null) {
(homeRef.value as ComponentPublicInstance).$callMethod('updateApp')
}
})
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 null | string;
const shopMerchantName = userInfoObj.shopMerchantName as null | string;
if (shopMerchantId == null || shopMerchantId == "" || shopMerchantName == null || shopMerchantName == "") {
storage.remove("userInfo");
storage.remove("sessionId");
uni.reLaunch({ url: "/pages/common/login/index" });
return;
}
if (homeRef.value != null) {
(homeRef.value as ComponentPublicInstance).$callMethod("updateApp");
}
});
</script>
<style scoped lang="scss">
.page-container {
width: 100%;
height: 100%;
}
.swiper-custom-placeholder {
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.package-title {
font-size: var(--l-font-lg);
font-weight: 500;
color: #333;
margin-bottom: var(--l-spacing-md);
}
.coming-soon {
font-size: var(--l-font-sm);
color: #999;
}
.detail-content {
width: 100%;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
}
.detail-title {
font-size: 24px;
color: #333;
.redirect-placeholder {
width: 100%;
height: 100%;
}
</style>
import { ref, type Ref } from "vue";
import { getBoutiquePackageList as apiGetBoutiquePackageList, getBoutiqueMaterialConfig } from "@/api/boutique-api.uts";
import { getEmployeeList } from "@/api/common-api.uts";
import { getBoutiqueMockData, getMockData } from "@/api/system-api.uts";
import { dispatch, store } from "@/store/index.uts";
import { storage } from "@/utils/storage.uts";
const _emptyArr: any[] = [] as any[];
export type BoutiqueLogic = {
loadComplete: Ref<boolean>;
requested: Ref<boolean>;
packageList: Ref<any[]>;
moduleList: Ref<any[]>;
toolList: Ref<any[]>;
chooseItem: Ref<UTSJSONObject>;
customerType: Ref<number>;
tabId: Ref<number>;
carBannerList: Ref<any[]>;
currentCarId: Ref<string>;
currentSwiperIndex: Ref<number>;
defaultCarId: Ref<string>;
swiperNoDataObject: UTSJSONObject;
typeList: any[];
getPkg: (item: any, key: string) => any;
clearHistory: () => void;
jumpPage: (homeFrameRef: any, pid: string) => void;
chooseCustomerType: (homeFrameRef: any, index: number) => void;
onSwiperChange: (e: any) => void;
onChangeTab: (index: number) => void;
initIfNeeded: () => Promise<void>;
getBoutiquePackageList: () => Promise<void>;
ensureLoginOrRelauch: () => boolean;
};
export function useBoutiqueLogic(): BoutiqueLogic {
/** 产品介绍轮播图默认图:与旧项目一致,按套餐 type 取图 */
const packageTypeBanner: UTSJSONObject = {
"1": "/static/images/boutique/package-1.webp",
"2": "/static/images/boutique/package-2.webp"
};
const loadComplete = ref<boolean>(false);
const requested = ref<boolean>(false);
const packageList = ref<any[]>([]);
const moduleList = ref<any[]>([]);
const toolList = ref<any[]>([]);
const chooseItem = ref<UTSJSONObject>({});
const customerType = ref<number>(-1);
const tabId = ref<number>(1);
const carBannerList = ref<any[]>([]);
const currentCarId = ref<string>("");
const currentSwiperIndex = ref<number>(0);
const defaultCarId = ref<string>("");
const swiperNoDataObject: UTSJSONObject = { icon: "", text: "敬请期待" };
// 显式声明为 any[],避免被推断为 UTSArray<UTSJSONObject> 导致泛型不匹配(error17)
const typeList: any[] = [
{ title: "回店客户", describe: "客户已领精品券且已上牌完成\n交付安排客户当日回店提车", icon: "icon-customer-1" },
{ title: "现场客户", describe: "客户未领取精品券\n首次到店", icon: "icon-customer-2" }
] as any[];
// 注意:UTS 中 function 声明不能稳定作为“值”返回给对象属性(会触发 error17),这里统一用 const 箭头函数
const ensureLoginOrRelauch = (): boolean => {
const userInfo = storage.get("userInfo");
if (userInfo == null) {
storage.remove("userInfo");
storage.remove("sessionId");
uni.reLaunch({ url: "/pages/common/login" });
return false;
}
const userInfoObj = userInfo as UTSJSONObject;
const shopMerchantId = userInfoObj.shopMerchantId as null | string;
const shopMerchantName = userInfoObj.shopMerchantName as null | string;
if (shopMerchantId == null || shopMerchantId == "" || shopMerchantName == null || shopMerchantName == "") {
storage.remove("userInfo");
storage.remove("sessionId");
uni.reLaunch({ url: "/pages/common/login" });
return false;
}
return true;
};
const getPkg = (item: any, key: string): any => {
if (item == null) return "";
const obj = item as UTSJSONObject;
const v = obj[key];
return v != null ? v : "";
};
const clearHistory = (): void => {
dispatch("clearCustomerInfo");
dispatch("clearHistory");
dispatch("clearReceptionTrack");
};
const callExposedMethod = (comp: any, methodName: string): void => {
if (comp == null) return;
const obj = comp as UTSJSONObject;
const fn = obj[methodName];
if (fn != null && typeof fn === "function") {
(fn as () => void)();
}
};
const jumpPage = (homeFrameRef: any, pid: string): void => {
const list = carBannerList.value;
let carIndex = list.findIndex((e: any) => (e as UTSJSONObject).carModelId == defaultCarId.value);
if (list.length == 1 || carIndex < 0) carIndex = 0;
const mod0 = moduleList.value.length > 0 ? (moduleList.value[0] as UTSJSONObject) : null;
const mod0Id = mod0 != null ? mod0.id : null;
const idStr = pid != "" ? pid : (mod0Id != null ? (mod0Id as any).toString() : "");
tabId.value = 1;
const carItem = list.length > 0 ? list[carIndex] : null;
currentCarId.value = carItem != null ? ((carItem as UTSJSONObject).carModelId ?? "") as string : "";
// 通知 HomeFrame 进入详情(具体 id/type 等仍在横屏组件内维护)
if (homeFrameRef != null) {
const h = homeFrameRef as UTSJSONObject;
h["__boutique_pid"] = idStr;
callExposedMethod(h, "showDetailPage");
}
};
const chooseCustomerType = (homeFrameRef: any, index: number): void => {
customerType.value = index;
if (index == 0) {
const ml = moduleList.value;
if (ml.length >= 3) {
const mid = (ml[2] as UTSJSONObject).id;
jumpPage(homeFrameRef, mid != null ? (mid as any).toString() : "");
} else {
jumpPage(homeFrameRef, "");
}
} else {
jumpPage(homeFrameRef, "");
}
};
const onSwiperChange = (e: any): void => {
const detail = (e as UTSJSONObject).detail as null | UTSJSONObject;
if (detail != null) {
const cur = detail.current as null | number;
if (cur != null) currentSwiperIndex.value = cur;
}
};
const initIfNeeded = async (): Promise<void> => {
if (!ensureLoginOrRelauch()) return;
if (requested.value) return;
await getMockData(true);
const userInfo = storage.get("userInfo") as null | UTSJSONObject;
if (userInfo == null) return;
const shopMerchantId = userInfo.shopMerchantId as null | string;
if (shopMerchantId == null || shopMerchantId == "") return;
customerType.value = -1;
getEmployeeList({ merchantId: shopMerchantId, sceneList: [1], appQGFlag: 1 })
.then((res: any) => {
dispatch("setEmployeeList", res);
})
.catch(() => {});
uni.showLoading({ title: "加载中", mask: true });
getBoutiqueMaterialConfig({ merchantId: shopMerchantId } as UTSJSONObject)
.then((res: any) => {
uni.hideLoading();
const resp = res as null | UTSJSONObject;
const materials = (resp != null && resp.materials != null ? resp.materials : _emptyArr) as any[];
const hidePackage = (resp != null ? resp.hidePackage : false) ?? false;
const boutiqueMediaConfig = {} as UTSJSONObject;
const carBannerListTemp: any[] = _emptyArr.slice();
const boutiqueCarListTemp: any[] = _emptyArr.slice();
for (const material of materials) {
const m = material as UTSJSONObject;
const mCarModelName = m.carModelName;
const mCarModelId = m.carModelId;
if (m != null && mCarModelName != null && mCarModelId != null) {
const configItems = [
{ key: "films", configIndex: 1 },
{ key: "products", configIndex: 2 }
];
if (hidePackage == false) configItems.unshift({ key: "packages", configIndex: 0 });
const retrofitting: any[] = _emptyArr.slice();
carBannerListTemp.push({
title: (m.seriesName ?? m.brandName ?? "") as string,
url: (m.modelDisplayPicurl ?? "") as string,
name: mCarModelName,
carModelId: mCarModelId,
seriesId: m.seriesId
});
boutiqueMediaConfig[mCarModelId as string] = {} as UTSJSONObject;
boutiqueCarListTemp.push({
carModelName: mCarModelName,
carModelId: mCarModelId,
brandId: m.brandId,
brandName: m.brandName,
name: m.seriesName,
id: m.seriesId
});
for (const it of configItems) {
const listVal = m[it.key as string];
retrofitting.push({
list: listVal != null ? listVal : _emptyArr,
tabId: (it.configIndex as number) + 1
});
}
const cfg = boutiqueMediaConfig[mCarModelId as string] as UTSJSONObject;
cfg.retrofitting = retrofitting;
cfg.optionals = m.optionals != null ? m.optionals : _emptyArr;
}
}
const withConfig = carBannerListTemp.map((c: any) => {
const cid = (c as UTSJSONObject).carModelId;
const cfg = boutiqueMediaConfig[cid as string] as UTSJSONObject;
(c as UTSJSONObject).configList = cfg != null && cfg.retrofitting != null ? cfg.retrofitting : _emptyArr;
return c;
});
carBannerList.value = withConfig;
const userState = (store.state as UTSJSONObject).user as UTSJSONObject;
userState.boutiqueMediaConfig = boutiqueMediaConfig;
userState.boutiqueCarList = boutiqueCarListTemp;
})
.catch((error) => {
uni.hideLoading();
uni.showToast({ title: error != null ? (error as any).toString() : "加载失败", icon: "none" });
});
const baseConfigData = await getBoutiqueMockData(true);
const ml = baseConfigData.moduleList != null ? baseConfigData.moduleList : _emptyArr;
const tl = baseConfigData.toolList != null ? baseConfigData.toolList : _emptyArr;
const dc = baseConfigData.defaultCarId ?? "";
dispatch("setBoutiqueBaseConfig", baseConfigData);
moduleList.value = ml as any[];
toolList.value = tl as any[];
defaultCarId.value = dc as string;
requested.value = true;
};
const getBoutiquePackageList = async (): Promise<void> => {
loadComplete.value = false;
packageList.value = [];
if (!ensureLoginOrRelauch()) {
loadComplete.value = true;
return;
}
const userInfo = storage.get("userInfo") as null | UTSJSONObject;
const merchantId = userInfo != null ? (userInfo.shopMerchantId as null | string) : null;
if (merchantId == null || merchantId == "") {
loadComplete.value = true;
return;
}
try {
const raw = await apiGetBoutiquePackageList({ merchantId } as UTSJSONObject);
let arr: any[] = _emptyArr.slice();
if (raw != null) {
if (Array.isArray(raw)) {
arr = raw as any[];
} else {
const obj = raw as UTSJSONObject;
const listVal = obj["list"] ?? obj["data"];
arr = (listVal != null && Array.isArray(listVal) ? listVal : _emptyArr) as any[];
}
}
const list: any[] = _emptyArr.slice();
for (const element of arr) {
const e = element as UTSJSONObject;
if (e != null) {
// eslint-disable-next-line unicorn/prefer-string-replace-all
e.scriptIntroduction = ((e.scriptIntroduction ?? "") as string).replace(/<\/?br\s*\/?>|\\n|\n/g, "<br>");
// eslint-disable-next-line unicorn/prefer-string-replace-all
e.content = ((e.content ?? "") as string).replace(/<\/?br\s*\/?>|\\n|\n/g, "<br>");
const pkgType = (e.type != null ? (e.type as any).toString() : "2") as string;
const defaultBanner = (packageTypeBanner[pkgType] ?? packageTypeBanner["2"]) as string | null;
if ((e.bannerImg == null || (e.bannerImg as string) == "") && defaultBanner != null) {
e.bannerImg = defaultBanner;
}
if (e.marketPrice != null) e.marketPrice = Number.parseFloat((e.marketPrice as any).toString()).toString();
if (e.packagePrice != null) e.packagePrice = Number.parseFloat((e.packagePrice as any).toString()).toString();
list.push(e);
}
}
packageList.value = list;
} catch (_err) {
packageList.value = [];
} finally {
loadComplete.value = true;
}
};
const onChangeTab = (index: number): void => {
if (index == 0) {
getBoutiquePackageList();
}
};
// UTS 对对象字面量“简写属性”(foo,) 的类型推断不稳定,可能触发 error17;这里全部显式写 key:value
return {
loadComplete: loadComplete,
requested: requested,
packageList: packageList,
moduleList: moduleList,
toolList: toolList,
chooseItem: chooseItem,
customerType: customerType,
tabId: tabId,
carBannerList: carBannerList,
currentCarId: currentCarId,
currentSwiperIndex: currentSwiperIndex,
defaultCarId: defaultCarId,
swiperNoDataObject: swiperNoDataObject,
typeList: typeList,
getPkg: getPkg,
clearHistory: clearHistory,
jumpPage: jumpPage,
chooseCustomerType: chooseCustomerType,
onSwiperChange: onSwiperChange,
onChangeTab: onChangeTab,
initIfNeeded: initIfNeeded,
getBoutiquePackageList: getBoutiquePackageList,
ensureLoginOrRelauch: ensureLoginOrRelauch
};
}
<template>
<layout-root>
<!-- #endif -->
<view class="page-container account-page">
<view class="bg">
<image class="bg-image"
......@@ -79,7 +79,6 @@
</view>
</view>
</view>
<!-- #ifdef APP -->
</layout-root>
</template>
......
......@@ -20,7 +20,6 @@
import { defineExpose, ref } from "vue";
import { apiGetMerchantBrand, apiSelectMerchantScene } from "@/api/user-api.uts";
import { layoutService } from "@/services/LayoutService";
import { storage } from "@/utils/storage.uts";
type SceneItem = {
......@@ -51,15 +50,15 @@ function jump(info: UTSJSONObject, data: any | null): void {
uni.hideLoading();
if (data != null) {
if (data !== null) {
const loginRole = (data as UTSJSONObject).loginRoleOnSelectMerchant;
if (loginRole != null) {
if (loginRole !== null) {
info.loginRoleOnSelectMerchant = loginRole;
}
}
const shopMerchantId = info.shopMerchantId as null | string;
if (shopMerchantId == null || shopMerchantId == "") {
if (shopMerchantId === null || shopMerchantId === "") {
uni.showToast({ title: "参数异常", icon: "none" });
return;
}
......@@ -72,7 +71,7 @@ function jump(info: UTSJSONObject, data: any | null): void {
uni.hideLoading();
const code = (res as UTSJSONObject).code as null | string;
if (code == "0") {
if (code === "0") {
const dataObj = (res as UTSJSONObject).data as null | UTSJSONObject;
const channelType = dataObj != null ? (dataObj.channelType as null | number) : null;
info.channelType = channelType ?? 1;
......@@ -86,12 +85,20 @@ function jump(info: UTSJSONObject, data: any | null): void {
storage.remove("boutique_YQorderSetting");
let url = "/pages/index/index";
if (sceneType == 1) {
url = layoutService.isMode("portrait") ? "/pages/boutique/portrait" : "/pages/boutique/index";
} else if (sceneType == 0) {
url = "/pages/equity/index";
} else if (sceneType == 7) {
url = "/pages/usedCar/index";
switch (sceneType) {
case 0: {
url = "/pages/equity/index";
break;
}
case 1: {
// 精品页统一入口:由入口页内部决定横竖屏组件
url = "/pages/boutique/index";
break;
}
case 7: {
url = "/pages/usedCar/index";
break;
}
}
console.log(`准备跳转: ${ url}`);
......@@ -104,12 +111,20 @@ function jump(info: UTSJSONObject, data: any | null): void {
const sceneType = info.sceneType as null | number;
let url = "/pages/index/index";
if (sceneType == 1) {
url = layoutService.isMode("portrait") ? "/pages/boutique/portrait" : "/pages/boutique/index";
} else if (sceneType == 0) {
url = "/pages/equity/index";
} else if (sceneType == 7) {
url = "/pages/usedCar/index";
switch (sceneType) {
case 0: {
url = "/pages/equity/index";
break;
}
case 1: {
// 精品页统一入口:由入口页内部决定横竖屏组件
url = "/pages/boutique/index";
break;
}
case 7: {
url = "/pages/usedCar/index";
break;
}
}
console.log(`准备跳转(catch): ${ url}`);
uni.reLaunch({ url });
......
<template>
<!-- #ifdef APP -->
<layout-root>
<!-- #endif -->
<view class="page-container">
<home-frame ref="homeRef" :showFooter="true">
<template #home>
<view class="home-content">
<view class="header">
<text class="title">
会员权益场景
</text>
<text class="subtitle">
Member Equity
</text>
</view>
<view class="action-area">
<view class="start-btn" @click="handleStart">
<text class="btn-text">
开始接待
</text>
</view>
</view>
</view>
</template>
<template #detail>
<view class="detail-content">
</view>
</template>
</home-frame>
</view>
<!-- #ifdef APP -->
</layout-root>
<!-- #endif -->
<layout-root>
<!-- #endif -->
<view class="page-container">
<HomeFrame ref="homeRef" :show-footer="true">
<template #home>
<view class="home-content">
<view class="header">
<text class="title">
会员权益场景
</text>
<text class="subtitle">
Member Equity
</text>
</view>
<view class="action-area">
<view class="start-btn" @click="handleStart">
<text class="btn-text">
开始接待
</text>
</view>
</view>
</view>
</template>
<template #detail>
<view class="detail-content">
</view>
</template>
</HomeFrame>
</view>
<!-- #ifdef APP -->
</layout-root>
<!-- #endif -->
</template>
<script setup lang="uts">
import { ref, ComponentPublicInstance } from 'vue'
// import { onLoad, onShow } from '@dcloudio/uni-app'
import { storage } from '@/utils/storage.uts'
import { state , dispatch } from "@/store/index.uts";
import HomeFrame from '@/components/HomeFrame/index.uvue'
import { getMerchantCarBrandList, getEmployeeListApi , getCarBrandsListApi } from '@/api/common-api.uts'
import { getMockData, getSoureData } from '@/api/system-api.uts'
const homeRef = ref(null)
const detailRef = ref(null)
const loadComplete = ref<boolean>(false)
const moduleList = ref<Array<any>>([])
const toolList = ref<Array<any>>([])
const mediaId = ref<string | number>('')
function setViewInfo(data: any): void {
const dataObj = data as UTSJSONObject
moduleList.value = dataObj.moduleList as Array<any>
toolList.value = dataObj.toolList as Array<any>
mediaId.value = dataObj.id as string
loadComplete.value = true
// 将 state.user 转换为 UTSJSONObject 后合并
const userState = state.user as UTSJSONObject
for (const key in dataObj) {
if (key !== 'moduleList' && key !== 'toolList' && key !== 'id') {
userState[key] = dataObj[key]
}
}
// state.user = userState as UserStateType
}
function handleStart(): void {
const currentModuleList = moduleList.value
if (currentModuleList.length == 0) {
return uni.showToast({
title: '该场景尚未配置素材,请联系总部人员',
icon: 'none'
})
}
const firstItem = currentModuleList[0] as UTSJSONObject
const firstId = firstItem.id as string
uni.navigateTo({ url: `/pages/equity/detail/index?id=${firstId}&type=edit` })
}
async function getSoure(brandIdList: string[], subBrandIdList: string[]): Promise<void> {
const userInfo = storage.get('userInfo') as UTSJSONObject
const shopMerchantId: string = (userInfo.shopMerchantId as string) ?? ''
const sceneType: number = (userInfo.sceneType as number) ?? 0
const storageKey = `source_${sceneType}_${shopMerchantId}`
const data = uni.getStorageSync(storageKey) as UTSJSONObject
if (data != null) {
setViewInfo(data)
}
try {
const requestData = await getSoureData(shopMerchantId, sceneType, {
brandIdList: brandIdList,
subBrandIdList: subBrandIdList
})
if (requestData != null) {
setViewInfo(requestData as UTSJSONObject)
} else {
loadComplete.value = true
}
} catch (error) {
console.error('获取数据失败:', error)
loadComplete.value = true
}
}
/**按序加载车型 */
async function getCarBrandsList(carBrandList: Array<any>, index: number) {
const item = carBrandList[index] as UTSJSONObject
if (item == null) return
const storageKey = `${(item.id as string) ?? ''}_${(item.brandId as string) ?? ''}_carlist`
const carList = uni.getStorageSync(storageKey)
if (index < carBrandList.length - 1) {
const nextIndex = index + 1
if (carList == null) {
const list = await getCarBrandsListApi({
brandId: (item.brandId as string) ?? '',
childBrandId: (item.id as string) ?? ''
})
if (list != null) {
uni.setStorageSync(storageKey, list)
}
getCarBrandsList(carBrandList, nextIndex)
} else {
getCarBrandsList(carBrandList, nextIndex)
}
}
}
function get_Vehicle_Sales_Data(): void {
const userInfo = storage.get('userInfo') as UTSJSONObject,
storageCarBrandList = storage.get('carBrandList'),
storageEmployeeList = storage.get('employeeList'),
shopMerchantId = userInfo.shopMerchantId
getMerchantCarBrandList([shopMerchantId ?? '']).then((res: any) => {
const resObj = res as UTSJSONObject
const data = resObj.data as UTSJSONObject
const dataArray = data as Array<any>
const firstItem = dataArray[0] as UTSJSONObject
let list = firstItem.carBrandList as Array<any>,
carBrandList = [] as any[]
const brandIdList: string[] = []
const subBrandIdList: string[] = []
list?.forEach((e: any) => {
const eObj = e as UTSJSONObject
const childs = eObj.childs as Array<any>
import { ComponentPublicInstance, ref } from "vue";
import { getCarBrandsListApi, getEmployeeListApi, getMerchantCarBrandList } from "@/api/common-api.uts";
import { getMockData, getSoureData } from "@/api/system-api.uts";
import HomeFrame from "@/components/HomeFrame/index.uvue";
import { dispatch, state } from "@/store/index.uts";
// import { onLoad, onShow } from '@dcloudio/uni-app'
import { storage } from "@/utils/storage.uts";
const homeRef = ref(null);
const detailRef = ref(null);
const loadComplete = ref<boolean>(false);
const moduleList = ref<Array<any>>([]);
const toolList = ref<Array<any>>([]);
const mediaId = ref<number | string>("");
function setViewInfo(data: any): void {
const dataObj = data as UTSJSONObject;
moduleList.value = dataObj.moduleList as Array<any>;
toolList.value = dataObj.toolList as Array<any>;
mediaId.value = dataObj.id as string;
loadComplete.value = true;
// 将 state.user 转换为 UTSJSONObject 后合并
const userState = state.user as UTSJSONObject;
for (const key in dataObj) {
if (key !== "moduleList" && key !== "toolList" && key !== "id") {
userState[key] = dataObj[key];
}
}
// state.user = userState as UserStateType
}
function handleStart(): void {
const currentModuleList = moduleList.value;
if (currentModuleList.length === 0) {
return uni.showToast({
title: "该场景尚未配置素材,请联系总部人员",
icon: "none"
});
}
const firstItem = currentModuleList[0] as UTSJSONObject;
const firstId = firstItem.id as string;
uni.navigateTo({ url: `/pages/equity/detail/index?id=${firstId}&type=edit` });
}
async function getSoure(brandIdList: string[], subBrandIdList: string[]): Promise<void> {
const userInfo = storage.get("userInfo") as UTSJSONObject;
const shopMerchantId: string = (userInfo.shopMerchantId as string) ?? "";
const sceneType: number = (userInfo.sceneType as number) ?? 0;
const storageKey = `source_${sceneType}_${shopMerchantId}`;
const data = uni.getStorageSync(storageKey) as UTSJSONObject;
if (data != null) {
setViewInfo(data);
}
try {
const requestData = await getSoureData(shopMerchantId, sceneType, {
brandIdList,
subBrandIdList
});
if (requestData != null) {
setViewInfo(requestData as UTSJSONObject);
} else {
loadComplete.value = true;
}
} catch (error) {
console.error("获取数据失败:", error);
loadComplete.value = true;
}
}
/** 按序加载车型 */
async function getCarBrandsList(carBrandList: Array<any>, index: number) {
const item = carBrandList[index] as UTSJSONObject;
if (item == null) return;
const storageKey = `${(item.id as string) ?? ""}_${(item.brandId as string) ?? ""}_carlist`;
const carList = uni.getStorageSync(storageKey);
if (index < carBrandList.length - 1) {
const nextIndex = index + 1;
if (carList == null) {
const list = await getCarBrandsListApi({
brandId: (item.brandId as string) ?? "",
childBrandId: (item.id as string) ?? ""
});
if (list != null) {
uni.setStorageSync(storageKey, list);
}
getCarBrandsList(carBrandList, nextIndex);
} else {
getCarBrandsList(carBrandList, nextIndex);
}
}
}
function get_Vehicle_Sales_Data(): void {
const userInfo = storage.get("userInfo") as UTSJSONObject;
const storageCarBrandList = storage.get("carBrandList");
const storageEmployeeList = storage.get("employeeList");
const shopMerchantId = userInfo.shopMerchantId;
getMerchantCarBrandList([shopMerchantId ?? ""]).then((res: any) => {
const resObj = res as UTSJSONObject;
const data = resObj.data as UTSJSONObject;
const dataArray = data as Array<any>;
const firstItem = dataArray[0] as UTSJSONObject;
const carBrandList = [] as any[];
const list = firstItem.carBrandList as Array<any>;
const brandIdList: string[] = [];
const subBrandIdList: string[] = [];
list?.forEach((e: any) => {
const eObj = e as UTSJSONObject;
const childs = eObj.childs as Array<any>;
childs.forEach((i: any) => {
const iObj = i as UTSJSONObject
iObj.brandName = (eObj.name as string) ?? ''
iObj.brandId = (eObj.id as string) ?? ''
carBrandList.push(iObj)
const idStr: string = (iObj.id as string) ?? ''
subBrandIdList.push(idStr)
})
childs.forEach((i: any) => {
const iObj = i as UTSJSONObject;
iObj.brandName = (eObj.name as string) ?? "";
iObj.brandId = (eObj.id as string) ?? "";
carBrandList.push(iObj);
const idStr: string = (iObj.id as string) ?? "";
subBrandIdList.push(idStr);
});
const idStr: string = (eObj.id as string) ?? ''
brandIdList.push(idStr)
})
getSoure(brandIdList, subBrandIdList)
dispatch('setCarBrandsList', carBrandList)
storage.set('carBrandList', carBrandList, 0)
if (carBrandList.length > 0) {
let index = 0
getCarBrandsList(carBrandList, index)
}
})
/**获取销售人员 */
getEmployeeListApi({
merchantId: shopMerchantId
}).then(res => {
dispatch('setEmployeeList', res)
storage.set('employeeList', res, 0)
})
}
const idStr: string = (eObj.id as string) ?? "";
brandIdList.push(idStr);
});
getSoure(brandIdList, subBrandIdList);
dispatch("setCarBrandsList", carBrandList);
storage.set("carBrandList", carBrandList, 0);
if (carBrandList.length > 0) {
const index = 0;
getCarBrandsList(carBrandList, index);
}
});
/** 获取销售人员 */
getEmployeeListApi({
merchantId: shopMerchantId
}).then(res => {
dispatch("setEmployeeList", res);
storage.set("employeeList", res, 0);
});
}
onLoad((options) => {
getMockData(true).then(mockdata =>{
console.log(mockdata,'===')
const userInfo = storage.get('userInfo') as UTSJSONObject
const mockDataObj = mockdata as UTSJSONObject
const channelType = userInfo.channelType as string
if (channelType == '1' && mockDataObj.boutiqueDefaultCarBrandId != null) {
state.user.boutiqueDefaultCarBrandId = (mockDataObj.boutiqueDefaultCarBrandId as string) ?? '' //默认车辆品牌
if (mockDataObj.defaultCarId != null) {
state.user.defaultCarId = (mockDataObj.defaultCarId as string) ?? ''//默认车系
}
}
})
get_Vehicle_Sales_Data()
uni.hideLoading()
})
onShow(() => {
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) ?? ''
const sceneType = (userInfoObj.sceneType as number) ?? 0
if (shopMerchantId == null) {
storage.remove('userInfo')
storage.remove('sessionId')
uni.reLaunch({ url: '/pages/common/login/index' })
return
}
if (homeRef.value != null) {
(homeRef.value as ComponentPublicInstance).$callMethod('updateApp')
}
})
onLoad((options) => {
getMockData(true).then(mockdata =>{
console.log(mockdata, "===");
const userInfo = storage.get("userInfo") as UTSJSONObject;
const mockDataObj = mockdata as UTSJSONObject;
const channelType = userInfo.channelType as string;
if (channelType == "1" && mockDataObj.boutiqueDefaultCarBrandId != null) {
state.user.boutiqueDefaultCarBrandId = (mockDataObj.boutiqueDefaultCarBrandId as string) ?? ""; // 默认车辆品牌
if (mockDataObj.defaultCarId != null) {
state.user.defaultCarId = (mockDataObj.defaultCarId as string) ?? "";// 默认车系
}
}
});
get_Vehicle_Sales_Data();
uni.hideLoading();
});
onShow(() => {
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) ?? "";
const sceneType = (userInfoObj.sceneType as number) ?? 0;
if (shopMerchantId == null) {
storage.remove("userInfo");
storage.remove("sessionId");
uni.reLaunch({ url: "/pages/common/login/index" });
return;
}
if (homeRef.value != null) {
(homeRef.value as ComponentPublicInstance).$callMethod("updateApp");
}
});
......
<template>
<view class="page">
<!-- #ifdef APP -->
<scroll-view class="scroll-container" scroll-y="true">
<!-- #endif -->
<view class="content">
<view class="header">
<view class="back-btn" @click="goBack">
<text class="back-text">← 返回</text>
</view>
<text class="title">个人考勤</text>
</view>
<view class="placeholder-box">
<text class="placeholder-text">敬请期待</text>
</view>
<view class="page">
<scroll-view class="scroll-container" scroll-y="true">
<view class="content">
<view class="header">
<view class="back-btn" @click="goBack">
<text class="back-text">← 返回</text>
</view>
<text class="title">个人考勤</text>
</view>
<view class="placeholder-box">
<text class="placeholder-text">敬请期待</text>
</view>
</view>
</scroll-view>
</view>
<!-- #ifdef APP -->
</scroll-view>
<!-- #endif -->
</view>
</template>
<script setup lang="uts">
function goBack(): void {
uni.navigateBack()
uni.navigateBack();
}
</script>
......
<template>
<view class="page">
<view class="header">
<view class="back-btn" @click="goBack">
<text class="back-text">← 返回</text>
</view>
<text class="title">接待录音</text>
</view>
<view class="content flex-col">
<view class="status-row">
<text class="status-label">状态:</text>
<text class="status-text">{{ statusText }}</text>
</view>
<view class="btn-row">
<view class="btn start-btn"
:class="{ disabled: isRecording }"
@click="onStartRecord">
<text class="btn-text">开始录音</text>
</view>
<view class="btn stop-btn"
:class="{ disabled: !isRecording }"
@click="onStopRecord">
<text class="btn-text">停住录音</text>
</view>
</view>
<view class="btn-row">
<view class="btn play-btn"
:class="{ disabled: recordFilePath == null }"
@click="onPlayRecord">
<text class="btn-text">播放刚刚的录音</text>
</view>
</view>
</view>
</view>
</template>
<script setup lang="uts">
import type { StartRecordOptions, StartRecordSuccess, StopRecordOptions, StopRecordSuccess } from "@/uni_modules/uts-recorder";
import { computed, ref } from "vue";
import { startRecord, stopRecord } from "@/uni_modules/uts-recorder";
const isRecording = ref(false);
const recordFilePath = ref<null | string>(null);
const statusText = computed((): string => {
if (isRecording.value) return "录音中…";
if (recordFilePath.value !== null) return "已停止,可播放";
return "暂无录音";
});
function goBack(): void {
uni.navigateBack();
}
function onStartRecord(): void {
if (isRecording.value) return;
isRecording.value = true;
recordFilePath.value = null;
const options: StartRecordOptions = {
sampleRate: 16_000,
numberOfChannels: 1,
success: (_res: StartRecordSuccess) => {
// 录音已开始,文件路径在 stop 时才有
},
fail: (_err: UniError) => {
isRecording.value = false;
uni.showToast({ title: "开始录音失败", icon: "none" });
}
};
startRecord(options);
uni.showToast({ title: "开始录音", icon: "none" });
}
function onStopRecord(): void {
if (!isRecording.value) return;
const options: StopRecordOptions = {
success: (res: StopRecordSuccess) => {
isRecording.value = false;
const filePath = res.filePath !== null && res.filePath !== "" ? res.filePath : res.tempFilePath;
recordFilePath.value = filePath !== null && filePath !== "" ? filePath : null;
uni.showToast({ title: "已停止录音", icon: "success" });
},
fail: (_err: UniError) => {
isRecording.value = false;
uni.showToast({ title: "停止录音失败", icon: "none" });
}
};
stopRecord(options);
}
function onPlayRecord(): void {
const path = recordFilePath.value;
if (path === null || path === "") {
uni.showToast({ title: "没有可播放的录音", icon: "none" });
return;
}
const audio = uni.createInnerAudioContext();
audio.src = path;
audio.play();
audio.onPlay(() => {
uni.showToast({ title: "开始播放", icon: "none" });
});
audio.onError((err) => {
const msg = err.errMsg !== "" ? err.errMsg : "播放失败";
uni.showToast({ title: msg, icon: "none" });
});
}
</script>
<style scoped lang="scss">
.page {
width: 100%;
min-height: 100%;
display: flex;
flex-direction: column;
background: #f5f7fa;
}
.header {
display: flex;
flex-direction: row;
align-items: center;
padding: 24px 16px;
background: #fff;
border-bottom: 1px solid #eee;
}
.back-btn {
padding: 8px 12px;
}
.back-text {
font-size: 16px;
color: #3773f8;
}
.title {
font-size: 18px;
font-weight: 500;
color: #1a1a1a;
margin-left: 12px;
}
.content {
padding: 24px 16px;
}
.status-row {
margin-bottom: 24px;
}
.status-label {
font-size: 14px;
color: #666;
}
.status-text {
font-size: 14px;
color: #1a1a1a;
margin-left: 8px;
}
.btn-row {
display: flex;
flex-direction: row;
flex-wrap: wrap;
margin-bottom: 16px;
}
.btn {
padding: 12px 24px;
border-radius: 8px;
margin-right: 12px;
margin-bottom: 8px;
}
.btn.disabled {
opacity: 0.5;
}
.start-btn {
background: #3773f8;
}
.stop-btn {
background: #e74c3c;
}
.play-btn {
background: #27ae60;
}
.btn-text {
font-size: 15px;
color: #fff;
}
</style>
<template>
<!-- #ifdef APP -->
<layout-root>
<!-- #endif -->
<view class="page-container">
<home-frame ref="homeRef" :showFooter="true">
<template #home>
<view class="home-content">
<view class="header">
<text class="title">二手车场景</text>
<text class="subtitle">Used Car</text>
</view>
<layout-root>
<view class="page-container">
<HomeFrame ref="homeRef" :show-footer="true">
<template #home>
<view class="home-content">
<view class="header">
<text class="title">二手车场景</text>
<text class="subtitle">Used Car</text>
</view>
<view class="action-area">
<view class="start-btn" @click="handleStart">
<text class="btn-text">开始接待</text>
</view>
<view class="action-area">
<view class="start-btn" @click="handleStart">
<text class="btn-text">开始接待</text>
</view>
<view class="status-info" v-if="isRecording">
<text class="status-text">录音中...</text>
</view>
</view>
<view v-if="isRecording" class="status-info">
<text class="status-text">录音中...</text>
</view>
</view>
<view class="info-panel">
<text class="info-label">接待状态:</text>
<text class="info-value">{{ receptionStatusText }}</text>
</view>
</view>
</template>
<view class="info-panel">
<text class="info-label">接待状态:</text>
<text class="info-value">{{ receptionStatusText }}</text>
</view>
</view>
</template>
<template #detail>
<view class="detail-content">
<text class="detail-title">详情页</text>
<template #detail>
<view class="detail-content">
<text class="detail-title">详情页</text>
</view>
</template>
</HomeFrame>
</view>
</template>
</home-frame>
</view>
<!-- #ifdef APP -->
</layout-root>
<!-- #endif -->
</layout-root>
</template>
<script setup lang="uts">
import { ref, computed, type Ref, ComponentPublicInstance } from 'vue'
import type { Ref } from "vue";
import { ComponentPublicInstance, computed, ref } from "vue";
import HomeFrame from "@/components/HomeFrame/index.uvue";
import { usePermission } from "@/composables/usePermission";
import { useReception } from "@/composables/useReception";
import { useRecorder } from "@/composables/useRecorder";
import { useUploader } from "@/composables/useUploader";
// import { onLoad, onShow } from '@dcloudio/uni-app'
import { storage } from '@/utils/storage.uts'
import HomeFrame from '@/components/HomeFrame/index.uvue'
import { useRecorder } from '@/composables/useRecorder'
import { useUploader } from '@/composables/useUploader'
import { usePermission } from '@/composables/usePermission'
import { useReception } from '@/composables/useReception'
const homeRef = ref(null)
const loadComplete = ref<boolean>(true)
const recorder = useRecorder()
const isRecording = (recorder as UTSJSONObject)['isRecording'] as Ref<boolean>
const uploader = useUploader()
const permission = usePermission()
const reception = useReception()
import { storage } from "@/utils/storage.uts";
const homeRef = ref(null);
const loadComplete = ref<boolean>(true);
const recorder = useRecorder();
const isRecording = (recorder as UTSJSONObject).isRecording as Ref<boolean>;
const uploader = useUploader();
const permission = usePermission();
const reception = useReception();
type RefWithValue = { value: number }
const receptionStatusText = computed((): string => {
const status = (reception as UTSJSONObject)['receptionStatus'] as RefWithValue | null
if (status != null && status.value == 0) {
return '未开始'
} else if (status != null && status.value == 1) {
return '接待中'
} else {
return '已完成'
}
})
const status = (reception as UTSJSONObject).receptionStatus as null | RefWithValue;
if (status != null && status.value == 0) {
return "未开始";
} else if (status != null && status.value == 1) {
return "接待中";
} else {
return "已完成";
}
});
async function handleStart(): Promise<void> {
const checkMic = (permission as UTSJSONObject)['checkMicrophonePermission'] as () => Promise<boolean>
const hasPermission = await checkMic()
if (hasPermission == false) {
uni.showToast({
title: '需要麦克风权限',
icon: 'none'
})
return
}
const clearHist = (reception as UTSJSONObject)['clearHistory'] as () => void
clearHist()
const startAud = (recorder as UTSJSONObject)['startAudio'] as () => void
startAud()
const startRec = (reception as UTSJSONObject)['startReception'] as () => void
startRec()
uni.showToast({
title: '开始接待',
icon: 'success'
})
const checkMic = (permission as UTSJSONObject).checkMicrophonePermission as () => Promise<boolean>;
const hasPermission = await checkMic();
if (hasPermission == false) {
uni.showToast({
title: "需要麦克风权限",
icon: "none"
});
return;
}
const clearHist = (reception as UTSJSONObject).clearHistory as () => void;
clearHist();
const startAud = (recorder as UTSJSONObject).startAudio as () => void;
startAud();
const startRec = (reception as UTSJSONObject).startReception as () => void;
startRec();
uni.showToast({
title: "开始接待",
icon: "success"
});
}
function handleFinish(): void {
const stopAud = (recorder as UTSJSONObject)['stopAudio'] as () => void
stopAud()
const finishRec = (reception as UTSJSONObject)['finishReception'] as () => void
finishRec()
const stopAud = (recorder as UTSJSONObject).stopAudio as () => void;
stopAud();
const finishRec = (reception as UTSJSONObject).finishReception as () => void;
finishRec();
uni.showToast({
title: '完成接待',
icon: 'success'
})
uni.showToast({
title: "完成接待",
icon: "success"
});
}
onLoad((options: OnLoadOptions) => {
uni.hideLoading()
})
uni.hideLoading();
});
onShow(() => {
const userInfo = storage.get('userInfo')
if (userInfo == null) {
storage.remove('userInfo')
storage.remove('sessionId')
uni.reLaunch({ url: '/pages/common/login/index' })
return
}
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 | null
const shopMerchantName = userInfoObj['shopMerchantName'] as string | null
const userInfoObj = userInfo as UTSJSONObject;
const shopMerchantId = userInfoObj.shopMerchantId as null | string;
const shopMerchantName = userInfoObj.shopMerchantName as null | string;
if (shopMerchantId == null || shopMerchantId == '' || shopMerchantName == null || shopMerchantName == '') {
storage.remove('userInfo')
storage.remove('sessionId')
uni.reLaunch({ url: '/pages/common/login/index' })
return
}
if (shopMerchantId == null || shopMerchantId == "" || shopMerchantName == null || shopMerchantName == "") {
storage.remove("userInfo");
storage.remove("sessionId");
uni.reLaunch({ url: "/pages/common/login/index" });
return;
}
if (homeRef.value != null) {
(homeRef.value as ComponentPublicInstance).$callMethod('updateApp')
}
})
if (homeRef.value != null) {
(homeRef.value as ComponentPublicInstance).$callMethod("updateApp");
}
});
</script>
<style scoped lang="scss">
......
......@@ -5,207 +5,221 @@
* - 计算一次,缓存结果,供全局使用
*/
import { ref } from 'vue'
import { LAYOUT_MODES, type LayoutMode, type LayoutModeConfig } from '@/config/layout.config.uts'
import { LAYOUT_VARS } from '@/config/layout-vars.uts'
import type { LayoutMode, LayoutModeConfig } from "@/config/layout.config.uts";
import { ref } from "vue";
import { LAYOUT_VARS } from "@/config/layout-vars.uts";
import { LAYOUT_MODES } from "@/config/layout.config.uts";
class LayoutService {
private currentMode = ref<LayoutMode>('pad')
private screenWidth = ref<number>(1024)
private screenHeight = ref<number>(768)
private scaleRatio = ref<number>(1)
private cssVariables = ref<UTSJSONObject>({})
private initialized = ref<boolean>(false)
/**
* 初始化(App 启动时调用一次)
private cssVariables = ref<UTSJSONObject>({});
private currentMode = ref<LayoutMode>("pad");
private initialized = ref<boolean>(false);
private scaleRatio = ref<number>(1);
private screenHeight = ref<number>(768);
private screenWidth = ref<number>(1024);
/**
* 获取 CSS 变量对象(用于根元素 :style)
*/
init(): void {
this.updateScreenInfo()
this.initialized.value = true
const w = this.screenWidth.value
const h = this.screenHeight.value
const minDim = w < h ? w : h
console.log('[LayoutService] init | 短边minDim=' + minDim + ' | mode=' + this.currentMode.value + ' | ratio=' + this.scaleRatio.value.toFixed(3) + ' | w=' + w + ' h=' + h)
}
/**
* 更新屏幕信息并重新计算
getCSSVariables(): UTSJSONObject {
if (!this.initialized.value) {
this.init();
}
return this.cssVariables.value;
}
/**
* 获取当前模式
*/
private updateScreenInfo(): void {
const systemInfo = uni.getSystemInfoSync()
this.screenWidth.value = systemInfo.screenWidth
this.screenHeight.value = systemInfo.screenHeight
getCurrentMode() {
return this.currentMode;
}
this.currentMode.value = this.detectMode()
const baseWidth = this.getBaseWidth()
this.scaleRatio.value = this.screenWidth.value / baseWidth
/**
* 获取当前分辨率档位(例如 1080 / 1920)
* - 仅用于选择 I18n 适配配置,不追求特别细的区分
*/
getResolutionBucket(): string {
if (!this.initialized.value) {
this.init();
}
const sw = this.screenWidth.value;
const sh = this.screenHeight.value;
const isPortraitMode = this.currentMode.value == "portrait";
const w = isPortraitMode ? (Math.min(sw, sh)) : sw;
// 简单两档划分:大于等于 1440 归为 1920,否则归为 1080
return w >= 1440 ? "1920" : "1080";
}
/**
* 获取缩放比例
*/
getScaleRatio() {
return this.scaleRatio;
}
this.updateCSSVariables()
}
/**
* 获取屏幕信息
*/
getScreenInfo() {
return {
width: this.screenWidth,
height: this.screenHeight
};
}
/**
* 初始化(App 启动时调用一次)
*/
init(): void {
this.updateScreenInfo();
this.initialized.value = true;
const w = this.screenWidth.value;
const h = this.screenHeight.value;
const minDim = Math.min(w, h);
console.log(`[LayoutService] init | 短边minDim=${ minDim } | mode=${ this.currentMode.value } | ratio=${ this.scaleRatio.value.toFixed(3) } | w=${ w } h=${ h}`);
}
/**
* 是否指定模式
*/
isMode(mode: LayoutMode): boolean {
return this.currentMode.value == mode;
}
/**
/**
* 刷新屏幕信息并重新计算(如锁定横屏后需延迟调用以拿到旋转后的尺寸)
*/
refreshScreenInfo(): void {
this.updateScreenInfo();
const w = this.screenWidth.value;
const h = this.screenHeight.value;
console.log(`[LayoutService] refreshScreenInfo | w=${ w } h=${ h } | mode=${ this.currentMode.value } | ratio=${ this.scaleRatio.value.toFixed(3)}`);
}
/**
* 按设计稿尺寸缩放
*/
scaleSize(designSize: number): number {
if (!this.initialized.value) {
this.init();
}
return Math.round(designSize * this.scaleRatio.value);
}
/**
* 检测布局模式(按设备物理尺寸区分)
* - 平板:物理短边 >= 768,用 pad 布局
* - 手机:物理短边 < 768,用 portrait 布局(手机默认竖屏)
* - 大屏:物理长边 >= 1440,用 desktop
* - 平板:物理长边 >= 1024,用 pad 布局(横屏);用长边判断避免 pad 竖屏时被误判为手机
* - 手机:物理长边 < 1024,用 portrait 布局(竖屏)
*/
private detectMode(): LayoutMode {
const w = this.screenWidth.value
const h = this.screenHeight.value
const minDim = w < h ? w : h // 物理短边
const maxDim = w > h ? w : h // 物理长边
let mode: LayoutMode = 'pad'
if (maxDim >= 1440) {
mode = 'desktop'
} else if (minDim >= 768) {
mode = 'pad' // 平板
} else {
mode = 'portrait' // 手机:始终用竖屏布局
}
console.log('[LayoutService] detectMode: 短边=' + minDim + ', w=' + w + ', h=' + h + ', mode=' + mode)
return mode
}
/**
private detectMode(): LayoutMode {
const w = this.screenWidth.value;
const h = this.screenHeight.value;
const minDim = Math.min(w, h); // 物理短边
const maxDim = Math.max(w, h); // 物理长边
let mode: LayoutMode = "pad";
if (maxDim >= 1440) {
mode = "desktop";
} else if (maxDim >= 1024) {
mode = "pad"; // 平板:长边>=1024 即视为 pad,保证 pad 端为横屏布局
} else {
mode = "portrait"; // 手机:长边<1024,用竖屏布局
}
console.log(`[LayoutService] detectMode: 长边=${ maxDim }, 短边=${ minDim }, w=${ w }, h=${ h }, mode=${ mode}`);
return mode;
}
/**
* 获取当前模式的基准宽度
*/
private getBaseWidth(): number {
const config = LAYOUT_MODES[this.currentMode.value] as LayoutModeConfig | null
if (config != null) {
return config.baseWidth
}
return 1024
}
/**
private getBaseWidth(): number {
const config = LAYOUT_MODES[this.currentMode.value] as LayoutModeConfig | null;
if (config != null) {
return config.baseWidth;
}
return 1024;
}
/**
* 解析取值:values[w] 存在则用,否则 baseValue * (w / baseWidth)
* baseValue 优先取 values[baseWidth],否则取最小 key 对应的值
*/
private resolveValue(values: UTSJSONObject, w: number, baseWidth: number): number {
const wStr = w.toString()
const direct = values[wStr]
if (direct != null && typeof direct === 'number') {
return direct
}
const baseStr = baseWidth.toString()
const baseFromWidth = values[baseStr]
let baseVal: number = 0
let scaleDenom: number = baseWidth
if (baseFromWidth != null && typeof baseFromWidth === 'number') {
baseVal = baseFromWidth
} else {
let minKey: number = 99999
for (const k in values) {
const n = parseInt(k, 10)
if (!isNaN(n) && n < minKey) {
minKey = n
}
}
if (minKey < 99999) {
const v = values[minKey.toString()]
if (v != null && typeof v === 'number') {
baseVal = v
scaleDenom = minKey
}
}
}
return baseVal * (w / scaleDenom)
}
/**
private resolveValue(values: UTSJSONObject, w: number, baseWidth: number): number {
const wStr = w.toString();
const direct = values[wStr];
if (direct != null && typeof direct === "number") {
return direct;
}
const baseStr = baseWidth.toString();
const baseFromWidth = values[baseStr];
let baseVal: number = 0;
let scaleDenom: number = baseWidth;
if (baseFromWidth != null && typeof baseFromWidth === "number") {
baseVal = baseFromWidth;
} else {
let minKey: number = 99_999;
for (const k in values) {
const n = Number.parseInt(k, 10);
if (!isNaN(n) && n < minKey) {
minKey = n;
}
}
if (minKey < 99_999) {
const v = values[minKey.toString()];
if (v != null && typeof v === "number") {
baseVal = v;
scaleDenom = minKey;
}
}
}
return baseVal * (w / scaleDenom);
}
/**
* 更新 CSS 变量缓存(遍历 LAYOUT_VARS)
*/
private updateCSSVariables(): void {
// 对于 portrait 模式,使用物理短边参与缩放,避免横屏手机出现非常大的宽度(例如 800x360),
// 造成与 H5 模拟器(390x844)视觉比例差异过大
const sw = this.screenWidth.value
const sh = this.screenHeight.value
const isPortraitMode = this.currentMode.value == 'portrait'
const w = isPortraitMode ? (sw < sh ? sw : sh) : sw
const baseWidth = this.getBaseWidth()
const out: UTSJSONObject = {}
for (const key in LAYOUT_VARS) {
const def = LAYOUT_VARS[key] as UTSJSONObject | null
if (def == null) continue
const cssName = def['css'] as string | null
if (cssName == null) continue
const vals = def['values'] as UTSJSONObject | null
if (vals == null) continue
const resolved = this.resolveValue(vals, w, baseWidth)
out[cssName] = Math.round(resolved).toString() + 'px'
}
this.cssVariables.value = out
}
/**
* 获取 CSS 变量对象(用于根元素 :style)
*/
getCSSVariables(): UTSJSONObject {
if (!this.initialized.value) {
this.init()
}
return this.cssVariables.value
}
/**
* 按设计稿尺寸缩放
*/
scaleSize(designSize: number): number {
if (!this.initialized.value) {
this.init()
}
return Math.round(designSize * this.scaleRatio.value)
}
/**
* 获取当前模式
*/
getCurrentMode() {
return this.currentMode
}
/**
* 获取缩放比例
*/
getScaleRatio() {
return this.scaleRatio
}
/**
* 获取屏幕信息
*/
getScreenInfo() {
return {
width: this.screenWidth,
height: this.screenHeight
}
}
/**
* 获取当前分辨率档位(例如 1080 / 1920)
* - 仅用于选择 I18n 适配配置,不追求特别细的区分
*/
getResolutionBucket(): string {
if (!this.initialized.value) {
this.init()
}
const sw = this.screenWidth.value
const sh = this.screenHeight.value
const isPortraitMode = this.currentMode.value == 'portrait'
const w = isPortraitMode ? (sw < sh ? sw : sh) : sw
// 简单两档划分:大于等于 1440 归为 1920,否则归为 1080
return w >= 1440 ? '1920' : '1080'
}
/**
* 是否指定模式
private updateCSSVariables(): void {
// 对于 portrait 模式,使用物理短边参与缩放,避免横屏手机出现非常大的宽度(例如 800x360),
// 造成与 H5 模拟器(390x844)视觉比例差异过大
const sw = this.screenWidth.value;
const sh = this.screenHeight.value;
const isPortraitMode = this.currentMode.value == "portrait";
const w = isPortraitMode ? (Math.min(sw, sh)) : sw;
const baseWidth = this.getBaseWidth();
const out: UTSJSONObject = {};
for (const key in LAYOUT_VARS) {
const def = LAYOUT_VARS[key] as null | UTSJSONObject;
if (def == null) continue;
const cssName = def.css as null | string;
if (cssName == null) continue;
const vals = def.values as null | UTSJSONObject;
if (vals == null) continue;
const resolved = this.resolveValue(vals, w, baseWidth);
out[cssName] = `${Math.round(resolved).toString() }px`;
}
this.cssVariables.value = out;
}
/**
* 更新屏幕信息并重新计算
*/
isMode(mode: LayoutMode): boolean {
return this.currentMode.value == mode
}
private updateScreenInfo(): void {
const systemInfo = uni.getSystemInfoSync();
// 使用 UTS 内置的 screenWidth/screenHeight,避免对 GetSystemInfoResult 进行不安全类型转换
this.screenWidth.value = systemInfo.screenWidth;
this.screenHeight.value = systemInfo.screenHeight;
this.currentMode.value = this.detectMode();
const baseWidth = this.getBaseWidth();
this.scaleRatio.value = this.screenWidth.value / baseWidth;
this.updateCSSVariables();
}
}
export const layoutService = new LayoutService()
export const layoutService = new LayoutService();
......@@ -106,9 +106,7 @@ $uni-font-size-paragraph: 15px;
display: flex;
align-items: center;
padding-left: 48rpx;
color: #333333;
font-size: 34rpx;
font-weight: 500;
/* color/font-size/font-weight only on <text> in uni-app-x; use .title-text inside */
&::after {
content: "";
......
/**
* 按设备统一应用屏幕方向锁定(pad 横屏、手机竖屏)
* 供 App.onShow 与全局 mixin onShow 调用,避免每个页面单独写
* pad 锁横屏后延迟刷新屏幕尺寸,使首页等布局按横屏尺寸正确计算
*/
// #ifdef APP
import { layoutService } from '@/services/LayoutService.uts'
import { lockOrientation } from '@/utils/plus-screen.uts'
// #endif
// 防抖:仅保留最后一次延迟刷新,避免快速切页时多次刷新
var refreshTimer: number = 0
export function applyScreenOrientationLock(): void {
// #ifdef APP
if (layoutService.isMode('pad') || layoutService.isMode('desktop')) {
lockOrientation('landscape-primary')
if (refreshTimer != 0) {
clearTimeout(refreshTimer)
}
refreshTimer = setTimeout((): void => {
layoutService.refreshScreenInfo()
refreshTimer = 0
}, 400)
} else {
lockOrientation('portrait-primary')
}
// #endif
}
......@@ -3,20 +3,33 @@
* 用于屏幕方向控制
*/
// #ifdef APP-ANDROID
import ActivityInfo from "android.content.pm.ActivityInfo"
// #endif
/**
* 锁定屏幕方向
* @param orientation 方向:'portrait-primary' | 'landscape-primary' | 'portrait' | 'landscape'
*/
export function lockOrientation(orientation: string): void {
// #ifdef APP
// uni-app x 中屏幕方向通过 manifest.json 或页面配置控制
// 动态控制需要通过 UTS 插件实现
console.log(`[plus-screen] 锁定屏幕方向: ${orientation}`);
console.warn("[plus-screen] uni-app x 中屏幕方向建议在 manifest.json 或页面配置中设置");
// #ifdef APP-ANDROID
const activity = UTSAndroid.getUniActivity()
if (activity != null) {
if (orientation == "landscape" || orientation == "landscape-primary") {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE)
} else {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
}
console.log("[plus-screen] 已锁定屏幕方向: " + orientation)
}
// #endif
// #ifdef APP-IOS
console.log("[plus-screen] iOS 锁定屏幕方向需在 manifest 或页面配置中设置: " + orientation)
// #endif
// #ifndef APP
console.log(`[plus-screen] 非APP平台不支持锁定屏幕方向`);
console.log("[plus-screen] 非APP平台不支持锁定屏幕方向")
// #endif
}
......
import { store } from "@/store/index.uts";
import { applyScreenOrientationLock } from "@/utils/apply-orientation-lock.uts";
export function appMixin(app: VueApp) {
// 注入 $store,兼容旧项目 this.$store 用法
......@@ -8,7 +9,10 @@ export function appMixin(app: VueApp) {
onPageScroll(e) {
// scroller.emit(e.scrollTop);
},
onShow() {},
onShow() {
// 每个页面显示时统一按设备锁定方向(pad 横屏、手机竖屏),无需各页面或 LayoutRoot 单独写
applyScreenOrientationLock();
},
onLoad() {}
});
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!