Commit cfb377b4 by liimin

chore(app): 移除分辨率适配相关代码

- 移除 App.uvue 中的 updateResolutionConfig 导入和调用
- 移除 main.ts 中的分辨率适配模块导入和全局属性挂载
- 修复 api/receiption.uts 中的 saveRecCustomer 函数返回值问题
1 parent 798f61d0
Showing 45 changed files with 469 additions and 833 deletions
<script lang="uts"> <script lang="uts">
import { updateResolutionConfig } from "@/services/adapter/index.uts"; // import { updateResolutionConfig } from "@/services/adapter/index.uts";
// #ifdef APP // #ifdef APP
import { applyScreenOrientationLock } from "@/utils/apply-orientation-lock.uts"; import { applyScreenOrientationLock } from "@/utils/apply-orientation-lock.uts";
import ws from "@/ws"; import ws from "@/ws";
...@@ -17,7 +17,7 @@ export default { ...@@ -17,7 +17,7 @@ export default {
// #endif // #endif
console.log("App Launch"); console.log("App Launch");
// 启动时仅做分辨率配置,避免后台定时器/录音模拟导致对象被长时间持有 // 启动时仅做分辨率配置,避免后台定时器/录音模拟导致对象被长时间持有
updateResolutionConfig(); // updateResolutionConfig();
// 连接(自动登录) // 连接(自动登录)
// #ifdef APP // #ifdef APP
// ws.connect(); // ws.connect();
......
...@@ -9,15 +9,11 @@ export async function getToken(params: UTSJSONObject): Promise<UTSJSONObject> { ...@@ -9,15 +9,11 @@ export async function getToken(params: UTSJSONObject): Promise<UTSJSONObject> {
return http.fetch("dj.api.smartcarlife.recepiton.customer.oss.getToken", data, false, "dj"); return http.fetch("dj.api.smartcarlife.recepiton.customer.oss.getToken", data, false, "dj");
} }
export async function saveRecCustomer(params: UTSJSONObject): Promise<boolean> { export async function saveRecCustomer(params: UTSJSONObject): Promise<boolean> {
try{
const data: UTSJSONObject = { const data: UTSJSONObject = {
projectName: "boutique", projectName: "boutique",
...params ...params
}; };
return await http.fetch("dj.api.smartcarlife.recepiton.customer.saveRecCustomer", data, false, "dj"); return http.fetch("dj.api.smartcarlife.recepiton.customer.saveRecCustomer", data, false, "dj");
}catch (error) {
return false;
}
} }
export async function searchRecordingEndTime(params: UTSJSONObject): Promise<string> { export async function searchRecordingEndTime(params: UTSJSONObject): Promise<string> {
const data: UTSJSONObject = { const data: UTSJSONObject = {
......
...@@ -125,7 +125,6 @@ export async function getSoureData( ...@@ -125,7 +125,6 @@ export async function getSoureData(
}); });
if (res != null && (res as UTSJSONObject).id != null) { if (res != null && (res as UTSJSONObject).id != null) {
console.log((res as UTSJSONObject).id, "res.idres.idres.idres.id");
const data = await getEquityMaterialConfig({ const data = await getEquityMaterialConfig({
id: (res as UTSJSONObject).id id: (res as UTSJSONObject).id
...@@ -215,14 +214,14 @@ export async function getSoureData( ...@@ -215,14 +214,14 @@ export async function getSoureData(
materialInfoList = materialInfoList.concat(moduleOtherList); materialInfoList = materialInfoList.concat(moduleOtherList);
} }
dataObj.toolList = await imgTransformBase64(toolList, ["shortTitleUrl"]); // dataObj.toolList = await imgTransformBase64(toolList, ["shortTitleUrl"]);
dataObj.moduleList = await imgTransformBase64(materialInfoList, ["thumbnail", "receptionSourceDetailList", "screenList"]); // dataObj.moduleList = await imgTransformBase64(materialInfoList, ["thumbnail", "receptionSourceDetailList", "screenList"]);
uni.setStorageSync(storageName, { // uni.setStorageSync(storageName, {
moduleList: dataObj.moduleList, // moduleList: dataObj.moduleList,
toolList: dataObj.toolList, // toolList: dataObj.toolList,
id: (res as UTSJSONObject).id // id: (res as UTSJSONObject).id
}); // });
return dataObj; return dataObj;
} else { } else {
...@@ -340,10 +339,10 @@ async function getBase64(url: string): Promise<string> { ...@@ -340,10 +339,10 @@ async function getBase64(url: string): Promise<string> {
base64 = `data:image/png;base64,${uni.arrayBufferToBase64(data as ArrayBuffer)}`; base64 = `data:image/png;base64,${uni.arrayBufferToBase64(data as ArrayBuffer)}`;
} }
console.log("转换后的 base64:", `${base64.slice(0, 50) }...`); // console.log("转换后的 base64:", `${base64.slice(0, 50) }...`);
resolve(base64); resolve(base64);
} catch (error) { } catch (error) {
console.error("转换 base64 失败:", error, "res.data:", res.data); // console.error("转换 base64 失败:", error, "res.data:", res.data);
resolve(url); resolve(url);
} }
}, },
......
...@@ -23,24 +23,22 @@ ...@@ -23,24 +23,22 @@
:enable-back-to-top="false" :enable-back-to-top="false"
scroll-y> scroll-y>
<!-- 品牌列表 --> <!-- 品牌列表 -->
<view v-show="currentView == 'brand'" class="view-content"> <view v-if="currentView == 'brand'" class="view-content">
<template v-for="(item, index) in carBrandList" :key="index"> <view v-for="(item, index) in carBrandList" :key="index"
<view class="select-item" class="select-item"
:class="[{ 'is-active': selectedBrandIndex == index }]" :class="[{ 'is-active': selectedBrandIndex == index }]"
@click="selectBrand(item, index)"> @click="selectBrand(item, index)">
<text class="select-item-text" :class="[{ 'is-active-text': selectedBrandIndex == index }]">{{ (item as UTSJSONObject).name }}</text> <text class="select-item-text" :class="[{ 'is-active-text': selectedBrandIndex == index }]">{{ (item as UTSJSONObject).name }}</text>
</view> </view>
</template>
</view> </view>
<!-- 车系列表 --> <!-- 车系列表 -->
<view v-show="currentView == 'series'" class="view-content"> <view v-if="currentView == 'series'" class="view-content">
<template v-for="(item, index) in currentCarList" :key="index"> <view v-for="(item, index) in currentCarList" :key="index"
<view class="select-item" class="select-item"
:class="[{ 'is-active': carModel == (item as UTSJSONObject).name }]" :class="[{ 'is-active': carModel == (item as UTSJSONObject).name }]"
@click="handleSelect(item)"> @click="handleSelect(item)">
<text class="select-item-text" :class="[{ 'is-active-text': carModel == (item as UTSJSONObject).name }]">{{ (item as UTSJSONObject).name }}</text> <text class="select-item-text" :class="[{ 'is-active-text': carModel == (item as UTSJSONObject).name }]">{{ (item as UTSJSONObject).name }}</text>
</view> </view>
</template>
</view> </view>
</scroll-view> </scroll-view>
</view> </view>
...@@ -48,20 +46,19 @@ ...@@ -48,20 +46,19 @@
</view> </view>
</template> </template>
<script setup lang="uts"> <script setup lang="uts">
import { computed, ref, watch } from "vue";
import { getCarBrandsListApi, getMerchantCarBrandList } from "@/api/common-api.uts"; import { getCarBrandsListApi, getMerchantCarBrandList } from "@/api/common-api.uts";
import { recordService } from "@/services/recorder/index.uts"; import { recordService } from "@/services/recorder/index.uts";
import { dispatch, state } from "@/store/index.uts"; import { dispatch, state } from "@/store/index.uts";
import { storage } from "@/utils/storage.uts"; import { storage } from "@/utils/storage.uts";
import { resolutionState } from "@/services/adapter/index.uts"; // import { resolutionState } from "@/services/adapter/index.uts";
// 使用 computed 响应式获取最新的分辨率配置 // 使用 computed 响应式获取最新的分辨率配置
const windowHeight = computed(() => { const windowHeight = computed(() => {
const height = resolutionState.windowHeight; // const height = resolutionState.windowHeight;
return height > 0 ? height : uni.getWindowInfo().windowHeight; return uni.getWindowInfo().windowHeight;
}); });
...@@ -228,35 +225,85 @@ function selectBrand(item: any, index: number): void { ...@@ -228,35 +225,85 @@ function selectBrand(item: any, index: number): void {
} as UTSJSONObject; } as UTSJSONObject;
selectItem.value = selectData; selectItem.value = selectData;
const cacheKey = `${_carId}_${_brandId}_carlist`; const cacheKey = `${_carId}_${_brandId}_carlist`;
let _carList = uni.getStorageSync(cacheKey);
// 尝试从缓存加载车系数据 // 尝试从 storage 缓存加载车系数据(iOS 兼容:手动序列化为字符串)
if (_carList != null && _carList != "" && _carList != "null") { let _carListStr = uni.getStorageSync(cacheKey);
_carList = typeof _carList === "string" ? JSON.parse(_carList) as Array<any> : _carList as Array<any>; console.log('[CarBrands] 读取缓存, key:', cacheKey);
currentCarList.value = _carList; console.log('[CarBrands] 缓存原始值类型:', typeof _carListStr);
// 切换到车系视图 if (_carListStr != null && _carListStr != "" && _carListStr != "null") {
currentView.value = "series"; try {
} else { // 如果已经是字符串,解析;否则直接使用
// 从 API 获取车系数据 let _carList: Array<any>;
getCarBrandsListApi({ brandId: _brandId, childBrandId: _carId }).then(res => { if (typeof _carListStr === "string") {
const typedRes = res as UTSArray<any>; console.log('[CarBrands] 缓存是字符串,开始解析');
console.error("获取车系列表成功:", typedRes); _carList = JSON.parse(_carListStr) as Array<any>;
currentCarList.value = typedRes; } else {
if (typedRes.length > 0) { console.log('[CarBrands] 缓存不是字符串,直接使用');
uni.setStorageSync(cacheKey, typedRes); _carList = _carListStr as Array<any>;
} }
// 切换到车系视图 // 验证数据有效性
currentView.value = "series"; console.log('[CarBrands] 解析后数据, isArray:', Array.isArray(_carList), 'length:', _carList != null ? _carList.length : 'null');
}).catch(error => { if (_carList != null && Array.isArray(_carList) && _carList.length > 0) {
// 静默失败 // 检查第一条数据
}); const firstItem = _carList[0] as UTSJSONObject;
console.log('[CarBrands] 缓存第一条数据:', JSON.stringify(firstItem));
console.log('[CarBrands] 使用 storage 缓存, key:', cacheKey, '数量:', _carList.length);
currentCarList.value = _carList;
// 切换到车系视图
currentView.value = "series";
return;
} else {
console.warn('[CarBrands] 缓存数据无效,将重新请求 API');
}
} catch (e) {
console.error('[CarBrands] 解析缓存失败:', e);
}
} else {
console.log('[CarBrands] 缓存为空或无效,将请求 API');
} }
// 从 API 获取车系数据
console.log('[CarBrands] 从 API 获取车系数据, brandId:', _brandId, 'childBrandId:', _carId);
getCarBrandsListApi({ brandId: _brandId, childBrandId: _carId }).then(res => {
const typedRes = res as UTSArray<any>;
console.log('[CarBrands] API 返回成功, 数量:', typedRes.length);
// 检查第一条数据的结构
if (typedRes.length > 0) {
const firstItem = typedRes[0] as UTSJSONObject;
console.log('[CarBrands] 第一条数据结构:', JSON.stringify(firstItem));
}
currentCarList.value = typedRes;
if (typedRes.length > 0) {
// iOS 兼容:手动序列化为字符串存储
try {
const serialized = JSON.stringify(typedRes);
console.log('[CarBrands] 序列化后长度:', serialized.length);
uni.setStorageSync(cacheKey, serialized);
// 验证存储是否成功
const verifyData = uni.getStorageSync(cacheKey);
console.log('[CarBrands] 验证存储, 类型:', typeof verifyData, '长度:', verifyData != null ? `${verifyData}`.length : 0);
console.log('[CarBrands] 已存入 storage 缓存(序列化)');
} catch (error) {
console.error('[CarBrands] 序列化失败:', error);
}
}
// 切换到车系视图
currentView.value = "series";
}).catch(error => {
console.error('[CarBrands] 获取车系列表失败:', error);
});
} }
watch(watchStatus, () => { watch(watchStatus, () => {
close(); close();
}, { immediate: true }); }, { immediate: true });
watch(updateView, () => { watch(updateView, (newVal: number) => {
const carBrandListData = storage.get("carBrandList"); // 优先从 store 读取,避免 storage 序列化问题
carBrandList.value = carBrandListData != null ? (carBrandListData as Array<any>) : []; const carBrandListFromStore = state.user.carBrands;
carBrandList.value = carBrandListFromStore != null ? carBrandListFromStore : [];
}, { immediate: true, deep: true }); }, { immediate: true, deep: true });
function autoSelect(): void { function autoSelect(): void {
const boutiqueDefaultCarBrandIdVal = boutiqueDefaultCarBrandId.value; const boutiqueDefaultCarBrandIdVal = boutiqueDefaultCarBrandId.value;
...@@ -330,6 +377,9 @@ function open(): void { ...@@ -330,6 +377,9 @@ function open(): void {
} }
} }
updateView.value = Date.now(); updateView.value = Date.now();
})
.catch((error) => {
console.error('[CarBrands] getMerchantCarBrandList 失败:', error);
}); });
const carBrandVal = carBrand.value; const carBrandVal = carBrand.value;
......
...@@ -19,17 +19,16 @@ ...@@ -19,17 +19,16 @@
:scroll-with-animation="false" :scroll-with-animation="false"
:enable-back-to-top="false" :enable-back-to-top="false"
scroll-y> scroll-y>
<view v-show="employeeList.length === 0" style="padding: 40px 20px; text-align: center;"> <view v-if="employeeList.length === 0" style="padding: 40px 20px; text-align: center;">
<text style="color: #999; font-size: 14px;">暂无销售人员数据</text> <text style="color: #999; font-size: 14px;">暂无销售人员数据</text>
</view> </view>
<view v-show="employeeList.length > 0" class="view-content"> <view v-if="employeeList.length > 0" class="view-content">
<template v-for="(item, index) in employeeList" :key="index"> <view v-for="(item, index) in employeeList" :key="index"
<view class="select-item" class="select-item"
:class="[{ 'is-active': (salesUuid as string) == (item as UTSJSONObject).uuid }]" :class="[{ 'is-active': (salesUuid as string) == (item as UTSJSONObject).uuid }]"
@click="handleSelect(item)"> @click="handleSelect(item)">
<text class="select-item-text" :class="[{ 'is-active-text': (salesUuid as string) == (item as UTSJSONObject).uuid }]">{{ (item as UTSJSONObject).staffName }}</text> <text class="select-item-text" :class="[{ 'is-active-text': (salesUuid as string) == (item as UTSJSONObject).uuid }]">{{ (item as UTSJSONObject).staffName }}</text>
</view> </view>
</template>
</view> </view>
</scroll-view> </scroll-view>
</view> </view>
...@@ -41,7 +40,7 @@ ...@@ -41,7 +40,7 @@
import { ComponentPublicInstance, computed, ref, watch } from "vue"; import { ComponentPublicInstance, computed, ref, watch } from "vue";
import { getEmployeeListApi } from "@/api/common-api.uts"; import { getEmployeeListApi } from "@/api/common-api.uts";
import { resolutionState } from "@/services/adapter/index.uts"; // import { resolutionState } from "@/services/adapter/index.uts";
import { dispatch, state } from "@/store/index.uts"; import { dispatch, state } from "@/store/index.uts";
import { storage } from "@/utils/storage.uts"; import { storage } from "@/utils/storage.uts";
...@@ -84,15 +83,16 @@ const dynamicZIndex = computed<number>(() => { ...@@ -84,15 +83,16 @@ const dynamicZIndex = computed<number>(() => {
return 10090; return 10090;
}); });
const windowHeight = computed<number>(() => { const windowHeight = computed<number>(() => {
const height = resolutionState.windowHeight; // const height = resolutionState.windowHeight;
return height > 0 ? height : uni.getWindowInfo().windowHeight; return uni.getWindowInfo().windowHeight;
}); });
const employeeList = ref<Array<any>>([]); const employeeList = ref<Array<any>>([]);
watch(updateView, () => { watch(updateView, (newVal: number) => {
const list = storage.get("employeeList") as UTSArray<Any>; // 优先从 store 读取,避免 storage 序列化问题
employeeList.value = list != null ? (list as Array<any>) : []; const employeeListFromStore = state.user.employeeList;
employeeList.value = employeeListFromStore != null ? employeeListFromStore : [];
}, { immediate: true }); }, { immediate: true });
function close(): void { function close(): void {
...@@ -136,6 +136,8 @@ function open(): void { ...@@ -136,6 +136,8 @@ function open(): void {
const listToStore = list != null ? list : []; const listToStore = list != null ? list : [];
storage.set("employeeList", listToStore, 0); storage.set("employeeList", listToStore, 0);
updateView.value = Date.now(); updateView.value = Date.now();
}).catch((error) => {
console.error('[Employee] getEmployeeListApi 失败:', error);
}); });
} }
......
...@@ -411,19 +411,32 @@ const showSuccessMessage = (): void => { ...@@ -411,19 +411,32 @@ const showSuccessMessage = (): void => {
// 提交表单 // 提交表单
const submit = (): void => { const submit = (): void => {
// console.log('[FinishStep] submit 被调用, step:', step.value, 'sceneType:', props.sceneType);
// // 临时调试
// uni.showToast({
// title: `submit: step=${step.value}, scene=${props.sceneType}`,
// icon: 'none',
// duration: 2000
// });
if (step.value == 1) { if (step.value == 1) {
errorTip.value = true; errorTip.value = true;
if (check()) { if (check()) {
console.log('[FinishStep] check 通过');
const sceneType = props.sceneType; const sceneType = props.sceneType;
if (sceneType == 0) { if (sceneType == 0) {
console.log('[FinishStep] 切换到 step 2');
step.value = 2; step.value = 2;
} else { } else {
console.log('[FinishStep] sceneType != 0, 直接完成');
receptionStatus.value = "1"; receptionStatus.value = "1";
showSuccessMessage(); showSuccessMessage();
} }
} else {
console.log('[FinishStep] check 失败');
} }
} else { } else {
// console.log('[FinishStep] step == 2, 检查 receptionStatus');
if (receptionStatus.value == "") { if (receptionStatus.value == "") {
uni.showToast({ uni.showToast({
title: "请完善本次接待结果", title: "请完善本次接待结果",
...@@ -431,6 +444,7 @@ const submit = (): void => { ...@@ -431,6 +444,7 @@ const submit = (): void => {
}); });
return; return;
} }
// console.log('[FinishStep] 调用 showSuccessMessage');
showSuccessMessage(); showSuccessMessage();
} }
}; };
......
...@@ -55,7 +55,7 @@ const props = defineProps<{ ...@@ -55,7 +55,7 @@ const props = defineProps<{
eyebrow: string eyebrow: string
emptyTitle: string emptyTitle: string
emptyText: string emptyText: string
swiperHeight: number // swiperHeight: number
}>(); }>();
const emit = defineEmits<{ const emit = defineEmits<{
......
...@@ -50,7 +50,7 @@ const shellIsPortrait = computed((): boolean => { ...@@ -50,7 +50,7 @@ const shellIsPortrait = computed((): boolean => {
}); });
onMounted((): void => { onMounted((): void => {
requestRecordPermission(); // await requestRecordPermission();
hideNativeTabBar(); hideNativeTabBar();
updateOrientation(); updateOrientation();
}); });
......
...@@ -69,14 +69,14 @@ import { computed, defineExpose, ref } from "vue"; ...@@ -69,14 +69,14 @@ import { computed, defineExpose, ref } from "vue";
import type { UnSwiperItem } from "@/uni_modules/uview-unix"; import type { UnSwiperItem } from "@/uni_modules/uview-unix";
import Entrance from "@/components/Entrance.uvue"; import Entrance from "@/components/Entrance.uvue";
import { cssClassRef, useResolutionConfig } from "@/services/adapter"; // import { cssClassRef, useResolutionConfig } from "@/services/adapter";
import { layoutService } from "@/services/LayoutService.uts"; import { layoutService } from "@/services/LayoutService.uts";
import { requestRecordPermission } from "@/utils/permission.uts"; import { requestRecordPermission } from "@/utils/permission.uts";
import { storage } from "@/utils/storage.uts"; import { storage } from "@/utils/storage.uts";
import HomeFrameMessageIndex from "./MessageIndex.uvue"; import HomeFrameMessageIndex from "./MessageIndex.uvue";
import ProductIntroSwiper from "./ProductIntroSwiper.uvue"; import ProductIntroSwiper from "./ProductIntroSwiper.uvue";
import { recordService } from "@/services/recorder/index.uts";
const props = withDefaults(defineProps<{ const props = withDefaults(defineProps<{
showFooter?: boolean showFooter?: boolean
...@@ -88,7 +88,7 @@ const props = withDefaults(defineProps<{ ...@@ -88,7 +88,7 @@ const props = withDefaults(defineProps<{
introEyebrow?: string introEyebrow?: string
introEmptyTitle?: string introEmptyTitle?: string
introEmptyText?: string introEmptyText?: string
introSwiperHeight?: number | null // introSwiperHeight?: number | null
/** 是否显示「开始接待」按钮;未传或为 true 时显示 */ /** 是否显示「开始接待」按钮;未传或为 true 时显示 */
showStartReception?: boolean showStartReception?: boolean
/** 展业工具区块标题,默认「展业工具」 */ /** 展业工具区块标题,默认「展业工具」 */
...@@ -167,7 +167,7 @@ const resolvedIntroEmptyText = computed((): string => { ...@@ -167,7 +167,7 @@ const resolvedIntroEmptyText = computed((): string => {
// // 从 CSS 变量中获取 module-box-height // // 从 CSS 变量中获取 module-box-height
// const isLandscape = !layoutService.isMode("portrait"); // const isLandscape = !layoutService.isMode("portrait");
// const resolution = layoutService.getResolutionBucket(); // const resolution = layoutService.getResolutionBucket();
// // 根据不同分辨率返回对应的高度 // // 根据不同分辨率返回对应的高度
// if (isLandscape) { // if (isLandscape) {
// if (resolution == "1174x768") return 266; // 360 - 54 - 40 // if (resolution == "1174x768") return 266; // 360 - 54 - 40
......
<template> <template>
<view class="home-frame-container scene-shell-root" <view class="home-frame-container scene-shell-root">
:class="[modeClass, resolutionClass, adapterClass]">
<view class="my-center-wrap"> <view class="my-center-wrap">
<MyCenterMain :user-info="resolvedUserInfo" /> <MyCenterMain :user-info="resolvedUserInfo" />
</view> </view>
...@@ -10,7 +9,7 @@ ...@@ -10,7 +9,7 @@
<script setup lang="uts"> <script setup lang="uts">
import { computed } from "vue"; import { computed } from "vue";
import { cssClassRef, useResolutionConfig } from "@/services/adapter"; // import { cssClassRef, useResolutionConfig } from "@/services/adapter";
import { layoutService } from "@/services/LayoutService.uts"; import { layoutService } from "@/services/LayoutService.uts";
import MyCenterMain from "@/pages/person/MyCenterMain.uvue"; import MyCenterMain from "@/pages/person/MyCenterMain.uvue";
...@@ -18,18 +17,19 @@ const props = defineProps<{ ...@@ -18,18 +17,19 @@ const props = defineProps<{
userInfo?: null | UTSJSONObject userInfo?: null | UTSJSONObject
}>(); }>();
useResolutionConfig(); // useResolutionConfig();
const adapterClass = computed((): string => { // const adapterClass = computed((): string => {
const cls = cssClassRef.value; // const cls = cssClassRef.value;
return cls != null ? (cls as string) : ""; // return cls != null ? (cls as string) : "";
}); // });
const modeClass = computed((): string => { // const modeClass = computed((): string => {
const modeRef = layoutService.getCurrentMode(); // const modeRef = layoutService.getCurrentMode();
const m = modeRef.value; // const m = modeRef.value;
return m == "portrait" ? "mode-portrait" : "mode-landscape"; // return m == "portrait" ? "mode-portrait" : "mode-landscape";
}); // });
// TODO
const resolutionClass = computed((): string => { const resolutionClass = computed((): string => {
const bucket = layoutService.getResolutionBucket(); const bucket = layoutService.getResolutionBucket();
......
...@@ -37,7 +37,7 @@ export default { ...@@ -37,7 +37,7 @@ export default {
portrait: { portrait: {
// 竖屏布局 - 产品介绍占 60% // 竖屏布局 - 产品介绍占 60%
// 可用高度 = 屏幕高度 - 状态栏(44px) - 标题栏(48px) - TabBar(60px) ≈ 屏幕高度 - 152px // 可用高度 = 屏幕高度 - 状态栏(44px) - 标题栏(48px) - TabBar(60px) ≈ 屏幕高度 - 152px
'--module-box-height': '420px', '--module-box-height': '288px',
'--tool-box-min-height': '200px', '--tool-box-min-height': '200px',
'--tool-box-margin-bottom': 'var(--l-spacing-lg)', '--tool-box-margin-bottom': 'var(--l-spacing-lg)',
// Entrance 图标尺寸(竖屏) // Entrance 图标尺寸(竖屏)
...@@ -51,7 +51,7 @@ export default { ...@@ -51,7 +51,7 @@ export default {
landscape: { landscape: {
// 横屏布局 - 产品介绍占 65% // 横屏布局 - 产品介绍占 65%
// 可用高度 = 屏幕高度 - 状态栏(44px) - 标题栏(48px) ≈ 屏幕高度 - 92px (TabBar在左侧,不影响高度) // 可用高度 = 屏幕高度 - 状态栏(44px) - 标题栏(48px) ≈ 屏幕高度 - 92px (TabBar在左侧,不影响高度)
'--module-box-height': '440px', '--module-box-height': '288px',
'--tool-box-height': '200px', '--tool-box-height': '200px',
'--tool-box-min-height': 'auto', '--tool-box-min-height': 'auto',
'--tool-box-margin-bottom': '0', '--tool-box-margin-bottom': '0',
......
<template> <template>
<un-page class="layout-root layout-column-shell" :class="[resolutionState.cssClass]"> <un-page class="layout-root layout-column-shell">
<slot /> <slot />
</un-page> </un-page>
</template> </template>
<script setup lang="uts"> <script setup lang="uts">
import { resolutionState, useResolutionConfig } from "@/services/adapter/index.uts"; // import { resolutionState } from "@/services/adapter/index.uts";
// 在这里统一调用初始化,确保任何使用 Layout 的页面都能获得正确的配置 // 在这里统一调用初始化,确保任何使用 Layout 的页面都能获得正确的配置
useResolutionConfig(); // useResolutionConfig();
</script> </script>
<style> <style>
......
// 导出适配器 // 导出适配器
export { IResolutionAdapter, resolutionAdapters } from "./adapter.uts"; export { IResolutionAdapter, resolutionAdapters } from "./adapter.uts";
// 导出核心逻辑和工具函数
export { getResponsiveImage, updateResolutionConfig, useResolutionConfig } from "./core.uts";
// 导出 Hooks // 导出 Hooks
export { useResponsiveImage } from "./hooks.uts"; export { useResponsiveImage } from "./hooks.uts";
......
import { createSSRApp } from "vue"; import { createSSRApp } from "vue";
// 引入分辨率适配模块 // 引入分辨率适配模块
import { resolutionState, useResponsiveImage } from "@/services/adapter/index.uts"; // import { resolutionState, useResponsiveImage } from "@/services/adapter/index.uts";
import { logger } from "@/services/logger"; import { logger } from "@/services/logger";
import DBRecord from "@/services/recorder/DBRecord.uts"; import DBRecord from "@/services/recorder/DBRecord.uts";
...@@ -16,12 +16,12 @@ export function createApp() { ...@@ -16,12 +16,12 @@ export function createApp() {
initDB(); initDB();
appMixin(app); appMixin(app);
// 注入全局分辨率适配属性 // 注入全局分辨率适配属性
app.config.globalProperties.$resState = resolutionState; // app.config.globalProperties.$resState = resolutionState;
console.log("resolutionState =>", resolutionState); // console.log("resolutionState =>", resolutionState);
// 注意:在 main.ts 中,useResponsiveImage 返回的函数可以直接挂载 // 注意:在 main.ts 中,useResponsiveImage 返回的函数可以直接挂载
// 但因为 useResponsiveImage 本身返回的是一个闭包函数,我们直接挂载它返回的函数可能更方便 // 但因为 useResponsiveImage 本身返回的是一个闭包函数,我们直接挂载它返回的函数可能更方便
// 或者我们直接挂载一个 getter 函数 // 或者我们直接挂载一个 getter 函数
app.config.globalProperties.$getResImg = useResponsiveImage(); // app.config.globalProperties.$getResImg = useResponsiveImage();
return { return {
app app
......
...@@ -208,8 +208,29 @@ const doLogin = async (): Promise<void> => { ...@@ -208,8 +208,29 @@ const doLogin = async (): Promise<void> => {
console.log(`${m}登录失败,失败原因:${message}`); console.log(`${m}登录失败,失败原因:${message}`);
} }
} catch (error) { } catch (error) {
const msg = `${error}`; // 安全提取错误信息
let msg = "登录失败,请稍后重试";
if (error != null) {
const errObj = error as UTSJSONObject;
const errMsg = errObj.message != null ? `${errObj.message}` : null;
if (errMsg != null && errMsg != "") {
msg = errMsg;
} else {
// 尝试其他可能的字段
const errStr = errObj.toString != null ? `${errObj.toString()}` : null;
if (errStr != null && errStr != "[object Object]" && errStr != "") {
msg = errStr;
}
}
}
showError(msg); showError(msg);
// 临时调试:显示详细错误
uni.showModal({
title: "登录错误详情",
content: JSON.stringify(error),
showCancel: false
});
console.error("登录异常:", error);
} finally { } finally {
uni.hideLoading(); uni.hideLoading();
isLogging.value = false; isLogging.value = false;
......
...@@ -137,10 +137,10 @@ function setViewInfo(data: any): void { ...@@ -137,10 +137,10 @@ function setViewInfo(data: any): void {
const idValue = dataObj.id; const idValue = dataObj.id;
mediaId.value = typeof idValue === "number" ? idValue.toString() : (idValue as string) ?? ""; mediaId.value = typeof idValue === "number" ? idValue.toString() : (idValue as string) ?? "";
loadComplete.value = true; loadComplete.value = true;
console.log("[equity] setViewInfo data:", dataObj); // console.log("[equity] setViewInfo data:", dataObj);
console.log("[equity] setViewInfo moduleList:", moduleList.value); // console.log("[equity] setViewInfo moduleList:", moduleList.value);
if (moduleList.value.length > 0) { if (moduleList.value.length > 0) {
console.log("[equity] setViewInfo first module:", moduleList.value[0]); // console.log("[equity] setViewInfo first module:", moduleList.value[0]);
} }
} }
...@@ -261,7 +261,6 @@ async function getSoure(brandIdList: number[], subBrandIdList: number[]): Promis ...@@ -261,7 +261,6 @@ async function getSoure(brandIdList: number[], subBrandIdList: number[]): Promis
console.error("解析缓存数据失败:", error); console.error("解析缓存数据失败:", error);
} }
} }
console.log(data);
if (data != null) { if (data != null) {
setViewInfo(data); setViewInfo(data);
} }
...@@ -271,7 +270,7 @@ async function getSoure(brandIdList: number[], subBrandIdList: number[]): Promis ...@@ -271,7 +270,7 @@ async function getSoure(brandIdList: number[], subBrandIdList: number[]): Promis
brandIdList, brandIdList,
subBrandIdList subBrandIdList
}); });
console.log("[equity] getSoureData response:", requestData); // console.log("[equity] getSoureData response:", requestData);
if (requestData != null) { if (requestData != null) {
setViewInfo(requestData as UTSJSONObject); setViewInfo(requestData as UTSJSONObject);
} else { } else {
...@@ -355,7 +354,6 @@ function get_Vehicle_Sales_Data(): void { ...@@ -355,7 +354,6 @@ function get_Vehicle_Sales_Data(): void {
onLoad((_options) => { onLoad((_options) => {
getMockData(true).then(mockdata => { getMockData(true).then(mockdata => {
console.log(mockdata, "===");
const userInfo = storage.get("userInfo") as UTSJSONObject; const userInfo = storage.get("userInfo") as UTSJSONObject;
const mockDataObj = mockdata as UTSJSONObject; const mockDataObj = mockdata as UTSJSONObject;
const channelType = userInfo.channelType as number; const channelType = userInfo.channelType as number;
......
...@@ -84,8 +84,6 @@ const toolRef = ref<ComponentRef>(null); ...@@ -84,8 +84,6 @@ const toolRef = ref<ComponentRef>(null);
const payRef = ref<ComponentRef>(null); const payRef = ref<ComponentRef>(null);
const stepRef = ref<ComponentRef>(null); const stepRef = ref<ComponentRef>(null);
const backpressRef = ref<ComponentRef>(null); const backpressRef = ref<ComponentRef>(null);
const toolRef = ref(null);
const stepRef = ref(null);
// 用于存储动态ref 的对象 // 用于存储动态ref 的对象
const mediaRefs = ref<UTSJSONObject>({}); const mediaRefs = ref<UTSJSONObject>({});
...@@ -388,10 +386,24 @@ async function findPayInfo(): Promise<void> { ...@@ -388,10 +386,24 @@ async function findPayInfo(): Promise<void> {
} }
paymentTypeList.value = paymentType; paymentTypeList.value = paymentType;
} }
onShow(() => {
console.log("[equity/detail] onShow");
});
onLoad((options) => { onLoad((options) => {
if (recordService != null) { // console.log('[equity/detail] onLoad 开始执行, recordService:', recordService !== null);
recordService.startAudio(); // if (recordService != null) {
} // // 测试开关:true 使用回调风格,false 使用 async/await
// const USE_CALLBACK_TEST = false;
// if (USE_CALLBACK_TEST) {
// console.log('[Test] 使用回调风格测试');
// recordService.testStartAudioWithCallback();
// } else {
// console.log('[Test] 使用 async/await');
// // recordService.startAudio();
// }
// }
console.log("[equity/detail] onLoad", options);
dispatch("setCustomerInfo", {}); dispatch("setCustomerInfo", {});
moduleList.value = [ moduleList.value = [
{ {
...@@ -431,6 +443,7 @@ onLoad((options) => { ...@@ -431,6 +443,7 @@ onLoad((options) => {
ensurePageToolList(); ensurePageToolList();
setPageData(); setPageData();
findPayInfo(); findPayInfo();
recordService.startAudio();
}); });
const open = (): void => { const open = (): void => {
...@@ -448,6 +461,9 @@ const openStep = (): void => { ...@@ -448,6 +461,9 @@ const openStep = (): void => {
function handleFull(val: boolean) { function handleFull(val: boolean) {
backZindex.value = val === true ? 0 : 9; backZindex.value = val === true ? 0 : 9;
} }
onUnmounted(() => {
recordService.stopAudio(true);
});
...@@ -506,7 +522,6 @@ function back(): void { ...@@ -506,7 +522,6 @@ function back(): void {
} }
function done(val: string) { function done(val: string) {
showPayPage.value = false;
callComponentMethod(toolRef, "hide"); callComponentMethod(toolRef, "hide");
callComponentMethod(stepRef, "close"); callComponentMethod(stepRef, "close");
const customerInfo = state.user.customerInfo as UTSJSONObject; const customerInfo = state.user.customerInfo as UTSJSONObject;
......
...@@ -63,7 +63,7 @@ ...@@ -63,7 +63,7 @@
<script setup lang="uts"> <script setup lang="uts">
import { computed, ref, watch } from 'vue' import { computed, ref, watch } from 'vue'
import { cssClassRef } from '@/services/adapter' // import { cssClassRef } from '@/services/adapter'
const props = defineProps<{ const props = defineProps<{
/** 客户档案列表(由父级拉取并传入) */ /** 客户档案列表(由父级拉取并传入) */
...@@ -79,14 +79,16 @@ const skeletonCardCount = 6 ...@@ -79,14 +79,16 @@ const skeletonCardCount = 6
/** 横屏或 768×1174 竖屏:列表双列(与 ListReception 一致;不再依赖 portrait.uts) */ /** 横屏或 768×1174 竖屏:列表双列(与 ListReception 一致;不再依赖 portrait.uts) */
const isListDualColumn = computed((): boolean => { const isListDualColumn = computed((): boolean => {
const cls = cssClassRef.value // const cls = cssClassRef.value
if (cls == null || cls == '') { // if (cls == null || cls == '') {
return false // return false
} // }
if (cls.indexOf('layout-landscape') >= 0) { // if (cls.indexOf('layout-landscape') >= 0) {
return true // return true
} // }
return cls.indexOf('layout-portrait-768x1174') >= 0 // return cls.indexOf('layout-portrait-768x1174') >= 0
// TODO
return true
}) })
const emit = defineEmits<{ const emit = defineEmits<{
......
...@@ -53,7 +53,7 @@ ...@@ -53,7 +53,7 @@
<script setup lang="uts"> <script setup lang="uts">
import { computed } from 'vue' import { computed } from 'vue'
import { cssClassRef } from '@/services/adapter' // import { cssClassRef } from '@/services/adapter'
const props = defineProps<{ const props = defineProps<{
/** 接待记录列表(由父级拉取并传入) */ /** 接待记录列表(由父级拉取并传入) */
...@@ -67,14 +67,16 @@ const skeletonCardCount = 6 ...@@ -67,14 +67,16 @@ const skeletonCardCount = 6
/** 横屏或 768×1174 竖屏:列表双列(与 adapter 注入的 cssClassRef 保持一致) */ /** 横屏或 768×1174 竖屏:列表双列(与 adapter 注入的 cssClassRef 保持一致) */
const isListDualColumn = computed((): boolean => { const isListDualColumn = computed((): boolean => {
const cls = cssClassRef.value // const cls = cssClassRef.value
if (cls == null || cls == '') { // if (cls == null || cls == '') {
return false // return false
} // }
if (cls.indexOf('layout-landscape') >= 0) { // if (cls.indexOf('layout-landscape') >= 0) {
return true // return true
} // }
return cls.indexOf('layout-portrait-768x1174') >= 0 // return cls.indexOf('layout-portrait-768x1174') >= 0
//TODO
return true
}) })
const emit = defineEmits<{ const emit = defineEmits<{
......
...@@ -153,7 +153,7 @@ import ListReception from '../lists/ListReception.uvue' ...@@ -153,7 +153,7 @@ import ListReception from '../lists/ListReception.uvue'
import CustomEmpty from '@/components/CustomEmpty/index.uvue' import CustomEmpty from '@/components/CustomEmpty/index.uvue'
import ReceptionListPrimaryFilter from '../filters/ReceptionListPrimaryFilter.uvue' import ReceptionListPrimaryFilter from '../filters/ReceptionListPrimaryFilter.uvue'
import ReceptionListSecondaryFilter from '../filters/ReceptionListSecondaryFilter.uvue' import ReceptionListSecondaryFilter from '../filters/ReceptionListSecondaryFilter.uvue'
import { cssClassRef } from '@/services/adapter' // import { cssClassRef } from '@/services/adapter'
const props = defineProps<{ const props = defineProps<{
/** 横屏分栏时为 true:子 Tab + 筛选区不参与纵向滚动,固定在列表区域顶部 */ /** 横屏分栏时为 true:子 Tab + 筛选区不参与纵向滚动,固定在列表区域顶部 */
stickyHeader?: boolean stickyHeader?: boolean
...@@ -196,8 +196,10 @@ const showReceptionEmpty = computed((): boolean => { ...@@ -196,8 +196,10 @@ const showReceptionEmpty = computed((): boolean => {
}) })
const isPortraitMode = computed((): boolean => { const isPortraitMode = computed((): boolean => {
const cls = cssClassRef.value // const cls = cssClassRef.value
return cls != null && cls.indexOf('layout-portrait') >= 0 // return cls != null && cls.indexOf('layout-portrait') >= 0
// TODO
return true
}) })
const bottomSafeSpacerStyle = computed((): UTSJSONObject => { const bottomSafeSpacerStyle = computed((): UTSJSONObject => {
......
# 分辨率适配系统 (Resolution Adaptation System)
本系统旨在解决 UniApp x 在不同设备分辨率下的精确样式适配和资源加载问题。通过预定义的配置对象,根据设备实际分辨率自动加载对应的样式值和图片资源,支持横竖屏自动切换及兜底机制。
## 1. 核心机制
系统基于 **“配置对象 (Configuration Object)”** 模式:
1. **自动检测**:App 启动或窗口调整时,自动获取屏幕宽高。
2. **键值匹配**:生成如 `1024x768` 的 Key。
3. **智能加载**:
* 优先加载对应分辨率的专用配置(如 `landscape/1024x768`)。
* 未匹配则降级使用兜底配置(`landscape/common` 或 `portrait/common`)。
4. **响应式更新**:配置对象是 Vue Reactive 的,分辨率变化时页面自动更新。
## 2. 目录结构
配置文件位于 `config/resolution-adapt/`:
```text
config/resolution-adapt/
├── types/
│ └── index.uts # 【类型定义】定义所有页面配置的接口规范
├── index.uts # 【统一入口】聚合导出所有模块
├── core.uts # 【核心逻辑】updateResolutionConfig, getResponsiveImage
├── store.uts # 【状态管理】ResolutionState
├── adapter.uts # 【适配器】ResolutionAdapterImpl
├── hooks.uts # 【Hooks】useResponsiveImage
├── registry.uts # 【注册表】landscapeConfigs, portraitConfigs
├── landscape/ # 【横屏配置组】
│ ├── 1024x768/ # 特定分辨率目录
│ │ ├── demo.uts # Demo 页面专用配置
│ │ └── index.uts # 聚合导出
│ ├── 1920x1080/
│ └── common/ # 横屏兜底配置
└── portrait/ # 【竖屏配置组】
└── common/ # 竖屏兜底配置
```
## 3. 如何在页面中使用
### 3.1 页面模板 (Template)
使用全局组件 `<Layout>` 包裹页面内容,并使用全局属性 `$resState` 和 `$getResImg`。
```html
<template>
<!-- 必须使用 Layout 包裹,它会自动注入 CSS 类名 -->
<Layout>
<!-- 方式 A: 根类名切换 (CSS) -->
<!-- Layout 组件会自动在根元素加上如 layout-landscape-1920x1080 的类名 -->
<view class="content">
<text class="title">Hello World</text>
</view>
<!-- 方式 B: JS 动态样式 (Style Binding) -->
<view class="dynamic-box"
:style="{ paddingLeft: $resState.config.demo.paddingLeft }">
<!-- 动态图片:使用全局方法 $getResImg 自动选择 @2x/@3x 图片 -->
<image :src="$getResImg($resState.config.demo.heroImageSrc)"
:style="{ width: $resState.config.demo.heroImageWidth }"
mode="widthFix" />
</view>
</Layout>
</template>
<script setup lang="uts">
// 无需 import 任何分辨率适配相关的代码!
</script>
<style scoped lang="scss">
// 引入拆分后的样式文件
@import "./styles/common.scss";
@import "./styles/landscape.scss";
@import "./styles/portrait.scss";
</style>
```
### 3.2 样式文件编写 (SCSS)
在 `styles/landscape.scss` 中利用根类名进行覆盖:
```scss
/* styles/landscape.scss */
.layout {
/* 针对 1920x1080 的覆盖样式 */
&.layout-landscape-1920x1080 {
.title {
font-size: 48rpx;
color: red;
}
}
/* 兜底样式 */
&.layout-landscape-common {
.title {
font-size: 32rpx;
color: blue;
}
}
}
```
## 4. 开发指南
### 4.1 定义图片资源 (ResponsiveImage)
系统强制要求图片资源配置必须包含 `x1` 路径,可选 `x2`, `x3`。
```typescript
// types/index.uts
export type DemoPageConfig = {
heroImageSrc: ResponsiveImage // 使用 ResponsiveImage 类型
}
// landscape/common/demo.uts
heroImageSrc: {
x1: '/static/img/hero.png',
x2: '/static/img/hero@2x.png' // 编辑器会智能提示
}
```
### 4.2 添加新页面配置
假设要为 `Home` 页面添加适配:
1. **定义接口**:
在 `types/index.uts` 中添加 `HomePageConfig` 并注册到 `AppResolutionConfig`。
2. **实现配置**:
在 `landscape/common/`, `landscape/1024x768/` 等所有已注册的目录下创建 `home.uts`。
3. **导出配置**:
在各目录的 `index.uts` 中导出新页面。
### 4.3 支持新的分辨率
假设需要支持 `1280x800` 分辨率:
1. **创建目录**:新建 `config/resolution-adapt/landscape/1280x800/`。
2. **编写配置**:复制 `common` 下的文件到新目录并修改数值。
3. **注册分辨率**:
在 `config/resolution-adapt/registry.uts` 中注册新目录。
```typescript
// config/resolution-adapt/registry.uts
import { config as ls_1280 } from './landscape/1280x800/index.uts'
const landscapeConfigs = {
// ...
"1280x800": ls_1280 // 新增
} as UTSJSONObject
```
import { logger } from "@/services/logger/index.uts";
import type { AppResolutionConfig, ResponsiveImage } from "./types/index.uts";
import { initRegistry, landscapeMap, portraitMap } from "./registry.uts";
import { cssClassRef, resolutionState } from "./store.uts";
function isNearResolution(
w: number,
h: number,
tw: number,
th: number,
tolerance: number
): boolean {
return Math.abs(w - tw) <= tolerance && Math.abs(h - th) <= tolerance;
}
// ========================================================================
// 核心适配逻辑
// ========================================================================
/**
* 更新分辨率适配配置
* - 根据屏幕尺寸和方向自动匹配配置
* - 优先精确匹配,失败则使用 common 作为 fallback
*/
export function updateResolutionConfig(): void {
// 确保注册表已初始化
initRegistry();
const systemInfo = uni.getSystemInfoSync();
const { screenWidth: w, screenHeight: h, pixelRatio: pr } = systemInfo;
if (w === 0 || h === 0) {
logger.warn('[ResolutionAdapt] 屏幕尺寸为 0,跳过配置更新');
return;
}
const key = `${Math.round(w)}x${Math.round(h)}`;
const isLandscape = w > h;
const configMap = isLandscape ? landscapeMap : portraitMap;
const prefix = isLandscape ? 'landscape' : 'portrait';
// 查找配置:优先精确匹配,其次 common
let target = configMap.get(key);
let usedKey = key;
let cssClass = `layout-${prefix}-${key}`;
let matchType = "exact";
console.log('target', target)
console.log('isLandscape', isLandscape)
console.log('configMap', configMap)
console.log('prefix', prefix)
console.log('key', key)
console.log('cssClass', cssClass)
console.log('matchType', matchType)
console.log('--------------------------------')
if (target == null) {
if (isLandscape) {
const near1174 = "1174x768";
if (isNearResolution(Math.round(w), Math.round(h), 1174, 768, 64)) {
const cfg1174 = configMap.get(near1174);
if (cfg1174 != null) {
target = cfg1174;
usedKey = near1174;
cssClass = `layout-${prefix}-${near1174}`;
matchType = "near-1174x768";
}
}
if (target == null) {
const near1920 = "1920x1080";
if (isNearResolution(Math.round(w), Math.round(h), 1920, 1080, 96)) {
const cfg1920 = configMap.get(near1920);
if (cfg1920 != null) {
target = cfg1920;
usedKey = near1920;
cssClass = `layout-${prefix}-${near1920}`;
matchType = "near-1920x1080";
}
}
}
} else {
const nearPortrait = "768x1174";
if (isNearResolution(Math.round(w), Math.round(h), 768, 1174, 64)) {
const cfg768 = configMap.get(nearPortrait);
console.log('cfg768', cfg768)
if (cfg768 != null) {
target = cfg768;
usedKey = nearPortrait;
cssClass = `layout-${prefix}-${nearPortrait}`;
matchType = "near-768x1174";
}
}
}
}
console.log('--------------------------------')
console.log('target', target)
console.log('isLandscape', isLandscape)
console.log('configMap', configMap)
console.log('prefix', prefix)
console.log('key', key)
console.log('cssClass', cssClass)
console.log('matchType', matchType)
if (target == null) {
target = configMap.get('common');
usedKey = `${prefix}/common`;
cssClass = `layout-${prefix}-common`;
matchType = "fallback-common";
}
if (target != null) {
console.log(`[ResolutionAdapt] match=${matchType} screen=${w}x${h} key=${key} used=${usedKey} cssClass=${cssClass}`);
applyResolutionConfig(target, usedKey, cssClass, pr, w, h);
}
}
/**
* 应用分辨率配置到状态
*/
function applyResolutionConfig(
cfg: AppResolutionConfig,
key: string,
cssCls: string,
pxRatio: number,
winWidth: number,
winHeight: number
): void {
// 使用 Object.assign 确保响应式更新
Object.assign(resolutionState, {
config: cfg,
currentKey: key,
pixelRatio: pxRatio,
windowWidth: winWidth,
windowHeight: winHeight
});
// 使用 ref 确保 cssClass 的响应式更新
cssClassRef.value = cssCls;
logger.info(`[ResolutionAdapt] Applied config: ${key}, cssClass: ${cssCls}`);
}
// ========================================================================
// Hooks
// ========================================================================
/**
* 获取分辨率配置(惰性加载)
*/
export function useResolutionConfig(): AppResolutionConfig {
const current = resolutionState.config;
if (current != null) {
return current;
}
updateResolutionConfig();
const next = resolutionState.config;
if (next != null) {
return next;
}
const fallbackLandscape = landscapeMap.get("common");
if (fallbackLandscape != null) {
return fallbackLandscape;
}
const fallbackPortrait = portraitMap.get("common");
if (fallbackPortrait != null) {
return fallbackPortrait;
}
throw new Error("Resolution config is unavailable");
}
/**
* 获取当前布局的 CSS 类名
*/
export function useLayoutCssClass(): string {
return resolutionState.cssClass;
}
/**
* 根据 pixelRatio 选择最佳图片
* @param img - 响应式图片配置
* @returns 最佳图片路径
*/
export function getResponsiveImage(img: ResponsiveImage): string {
const pr = resolutionState.pixelRatio;
// 高倍率屏优先使用高清图(可选字段须显式判空,不可直接 if (string?))
if (pr >= 3) {
if (img.x3 != null && img.x3 != "") {
return img.x3;
}
if (img.x2 != null && img.x2 != "") {
return img.x2;
}
return img.x1;
}
if (pr >= 2) {
if (img.x2 != null && img.x2 != "") {
return img.x2;
}
if (img.x3 != null && img.x3 != "") {
return img.x3;
}
return img.x1;
}
// 默认返回 1 倍图
return img.x1;
}
import { getResponsiveImage } from "./core.uts";
import { ResponsiveImage } from "./types/index.uts";
/**
* 获取响应式图片处理函数
* 在 setup 中调用此 hook,返回一个可以直接在 template 中使用的函数
*/
export function useResponsiveImage() {
// 返回一个符合模板调用要求的 wrapper 函数
const getResImg = (img: ResponsiveImage): string => {
return getResponsiveImage(img);
};
return getResImg;
}
...@@ -9,9 +9,7 @@ const windowHeight = ref(0) ...@@ -9,9 +9,7 @@ const windowHeight = ref(0)
export function updateOrientation(): void { export function updateOrientation(): void {
const systemInfo = uni.getSystemInfoSync() const systemInfo = uni.getSystemInfoSync()
const { screenWidth: w, screenHeight: h } = systemInfo const { screenWidth: w, screenHeight: h } = systemInfo
console.log('[useOrientation] screenWidth:', w, 'screenHeight:', h)
console.log('[useOrientation] windowWidth:', systemInfo.windowWidth, 'windowHeight:', systemInfo.windowHeight)
// 使用屏幕物理尺寸 // 使用屏幕物理尺寸
windowWidth.value = Math.round(w) windowWidth.value = Math.round(w)
...@@ -32,7 +30,6 @@ export function useOrientation() { ...@@ -32,7 +30,6 @@ export function useOrientation() {
// 分辨率 key:宽x高 例如 393x816 // 分辨率 key:宽x高 例如 393x816
resolutionKey: computed(() => { resolutionKey: computed(() => {
const key = `${windowWidth.value}x${windowHeight.value}` const key = `${windowWidth.value}x${windowHeight.value}`
console.log('[useOrientation] resolutionKey computed:', key)
return key return key
}), }),
} }
......
// 导出核心逻辑和工具函数
export { getResponsiveImage, updateResolutionConfig, useResolutionConfig } from "./core.uts";
// 导出 Hooks
export { useResponsiveImage } from "./hooks.uts";
// 导出注册表
export { initRegistry, landscapeMap, portraitMap } from "./registry.uts";
// 导出状态
export { resolutionState, ResolutionState, cssClassRef } from "./store.uts";
// 导出类型
export * from "./types/index.uts";
import { DemoPageConfig, ResponsiveImage } from "../../types/index.uts";
export const demoConfig : DemoPageConfig = {
paddingLeft: "100rpx",
paddingRight: "100rpx",
heroImageWidth: "600px",
heroImageSrc: {
x1: "/static/images/landscape/1024/study-hero.png",
x2: "/static/images/landscape/1024/study-hero@2x.png"
} as ResponsiveImage,
titleFontSize: "80rpx"
};
import { AppResolutionConfig } from "../../types/index.uts";
import { demoConfig } from "./demo.uts";
export const config : AppResolutionConfig = {
demo: demoConfig
};
import { DemoPageConfig, ResponsiveImage } from "../../types/index.uts";
export const demoConfig : DemoPageConfig = {
paddingLeft: "150rpx",
paddingRight: "150rpx",
heroImageWidth: "800px",
heroImageSrc: {
x1: "/static/images/landscape/1920/study-hero.png",
x2: "/static/images/landscape/1920/study-hero@2x.png"
} as ResponsiveImage,
titleFontSize: "48rpx"
};
import { AppResolutionConfig } from "../../types/index.uts";
import { demoConfig } from "./demo.uts";
export const config : AppResolutionConfig = {
demo: demoConfig
};
import { DemoPageConfig, ResponsiveImage } from "../../types/index.uts";
export const demoConfig : DemoPageConfig = {
paddingLeft: "32rpx",
paddingRight: "32rpx",
heroImageWidth: "100%",
heroImageSrc: {
x1: "/static/images/common/study-hero.png",
x2: "/static/images/common/study-hero@2x.png"
} as ResponsiveImage,
titleFontSize: "32rpx"
};
import { AppResolutionConfig } from "../../types/index.uts";
import { demoConfig } from "./demo.uts";
export const config : AppResolutionConfig = {
demo: demoConfig
};
import { DemoPageConfig, ResponsiveImage } from "../../types/index.uts";
export const demoConfig : DemoPageConfig = {
paddingLeft: "24rpx",
paddingRight: "24rpx",
heroImageWidth: "100%",
heroImageSrc: {
x1: "/static/images/portrait/common/study-hero.png",
x2: "/static/images/portrait/common/study-hero@2x.png"
} as ResponsiveImage,
titleFontSize: "32rpx"
};
import { AppResolutionConfig } from "../../types/index.uts";
import { demoConfig } from "./demo.uts";
export const config : AppResolutionConfig = {
demo: demoConfig
};
import { DemoPageConfig, ResponsiveImage } from "../../types/index.uts";
export const demoConfig : DemoPageConfig = {
paddingLeft: "24rpx",
paddingRight: "24rpx",
heroImageWidth: "100%",
heroImageSrc: {
x1: "/static/images/portrait/common/study-hero.png",
x2: "/static/images/portrait/common/study-hero@2x.png"
} as ResponsiveImage,
titleFontSize: "30rpx"
};
import { AppResolutionConfig } from "../../types/index.uts";
import { demoConfig } from "./demo.uts";
export const config : AppResolutionConfig = {
demo: demoConfig
};
// ========================================================================
// 静态导入所有支持的分辨率配置
// 新增分辨率时,请在此处导入并在 initRegistry 中注册
// ========================================================================
import { config as ls_1174 } from "./landscape/1174x768/index.uts";
import { config as ls_1920 } from "./landscape/1920x1080/index.uts";
import { config as ls_common } from "./landscape/common/index.uts";
import { config as pt_768x1174 } from "./portrait/768x1174/index.uts";
import { config as pt_common } from "./portrait/common/index.uts";
import type { AppResolutionConfig } from "./types/index.uts";
// ========================================================================
// 配置注册表
// ========================================================================
const landscapeMap = new Map<string, AppResolutionConfig>();
const portraitMap = new Map<string, AppResolutionConfig>();
// 定义配置映射表,方便统一管理和循环注册
const landscapeConfigs = {
"common": ls_common,
"1174x768": ls_1174,
"1920x1080": ls_1920,
"816x393": ls_common
} as UTSJSONObject;
const portraitConfigs = {
"768x1174": pt_768x1174,
"640x979": pt_common,
"393x816": pt_common,
"common": pt_common
} as UTSJSONObject;
// 导出 Map(只读)
export { landscapeMap, portraitMap };
// 导出初始化函数(内部使用)
export { initRegistry };
/**
* 初始化分辨率配置注册表
* - 懒加载模式,首次调用时初始化
*/
function initRegistry(): void {
if (landscapeMap.size > 0 && portraitMap.size > 0) {
return; // 已初始化,避免重复
}
// 批量注册横屏配置
for (const key in landscapeConfigs) {
const conf = landscapeConfigs[key] as AppResolutionConfig;
landscapeMap.set(key, conf);
}
// 批量注册竖屏配置
for (const key in portraitConfigs) {
const conf = portraitConfigs[key] as AppResolutionConfig;
portraitMap.set(key, conf);
}
}
import { reactive, ref } from "vue";
import type { AppResolutionConfig } from "./types/index.uts";
/**
* 分辨率适配状态
*/
export type ResolutionState = {
config: AppResolutionConfig | null
currentKey: string
pixelRatio: number
windowWidth: number
windowHeight: number
}
/**
* CSS 类名(使用 ref 确保响应式)
*/
export const cssClassRef = ref<string>('layout-default');
/**
* 全局分辨率状态 (响应式)
* - 使用 Object.assign 确保类型正确
*/
const initialState: ResolutionState = {
config: null,
currentKey: '',
pixelRatio: 1,
windowWidth: 0,
windowHeight: 0
};
export const resolutionState = reactive(initialState);
...@@ -61,33 +61,6 @@ export default class DBBase implements IDBBase { ...@@ -61,33 +61,6 @@ export default class DBBase implements IDBBase {
*/ */
async clearRecords(): Promise<void> { async clearRecords(): Promise<void> {
await this.init(); await this.init();
// delete 需要 where 参数,这里可能是清空表
// sqlite.uts 的 delete 实现:`DELETE FROM ${tabName} WHERE ${whereStr}`
// 如果 where 为空,SQL 会变成 `DELETE FROM ${tabName} WHERE ` -> 语法错误
// 需要修改 sqlite.uts 支持无 where 删除,或者在这里传入 1=1
// 让我们看 sqlite.uts 的 delete 实现
/*
delete(tabName: string, where: UTSJSONObject): Promise<any> {
const whereKeys = where.keys()
// ...
const whereStr = whereList.join(' AND ')
const sql = `DELETE FROM ${tabName} WHERE ${whereStr}`
return this.executeSql(sql)
}
*/
// 确实,如果不传 where,whereKeys 为空,whereStr 为空,SQL 错误。
// 应该在 DBBase 里传入一个总是为真的条件,或者修改 sqlite.uts。
// 为了稳妥,这里传入空对象可能不行。
// 让我们传入一个假条件或者修改 sqlite.uts。
// 既然我刚刚重构了 sqlite.uts,我可以再改一下 sqlite.uts 让 delete 支持全表删除,
// 或者在这里调用 executeSql(`DELETE FROM ${this.table_name}`)。
// DBBase 没有直接暴露 executeSql。
// 还是传入一个 trick 条件吧,或者传入 null 让 sqlite 处理。
// 修改 sqlite.uts 比较好。但用户没让我再改 sqlite.uts。
// 我们可以传入 { "1": 1 } ?
// 让我们先暂时注释掉或抛出未实现,或者传入 dummy where。
// 或者直接调用 this.db!.executeSql(`DELETE FROM ${this.table_name}`),虽然是 private 或者是 public?
// sqlite.uts 中 executeSql 是 public 的。
await this.db.executeSql(`DELETE FROM ${this.table_name}`); await this.db.executeSql(`DELETE FROM ${this.table_name}`);
} }
...@@ -105,7 +78,7 @@ export default class DBBase implements IDBBase { ...@@ -105,7 +78,7 @@ export default class DBBase implements IDBBase {
async getRecordById(id: any): Promise<null | UTSJSONObject> { async getRecordById(id: any): Promise<null | UTSJSONObject> {
await this.init(); await this.init();
const where = { id }; const where = { id };
const records = await this.db.select(this.table_name, where, null); const records = await this.db.select(this.table_name, where, null);
// records 是 any[],需要断言 // records 是 any[],需要断言
if (records.length > 0) { if (records.length > 0) {
return records[0] as UTSJSONObject; return records[0] as UTSJSONObject;
...@@ -133,26 +106,17 @@ export default class DBBase implements IDBBase { ...@@ -133,26 +106,17 @@ export default class DBBase implements IDBBase {
return this.db.select(this.table_name, where, null); return this.db.select(this.table_name, where, null);
} }
/**
* 初始化数据库和表结构
*/
async init(): Promise<boolean> { async init(): Promise<boolean> {
try { try {
// db 不可能为 null,因为在 constructor 中初始化了 // 1. 初始化 SQLite 连接
// 移除 isOpen 检查,直接调用 init(),因为 SQLite.init 内部已经处理了幂等性
// const isOpen = this.db!.isOpen()
// if (!isOpen) {
await this.db.init(); await this.db.init();
// }
// if (this.table_name == null) { // 2. 检查并创建/更新表结构
// throw new Error("DBBase: table_name is null"); await this.ensureTableStructure();
// }
const isTableExists = await this.db.isTableExists(this.table_name);
logger.warn(`数据库是否存在isTableExists: ${isTableExists}`, "DBBase");
if (!isTableExists) {
await this.db.createTable(this.table_name, this.table_columns);
this.tableCreated = true;
} else {
logger.warn(`[${this.table_name}] 表已存在, 将检查并更新列`, "DBBase");
}
return true; return true;
} catch (error) { } catch (error) {
logger.error(`初始化数据库失败 error - > ${error}`, "DBBase"); logger.error(`初始化数据库失败 error - > ${error}`, "DBBase");
...@@ -160,6 +124,87 @@ export default class DBBase implements IDBBase { ...@@ -160,6 +124,87 @@ export default class DBBase implements IDBBase {
} }
} }
/**
* 确保表结构正确(创建或增量更新)
*/
private async ensureTableStructure(): Promise<void> {
const isTableExists = await this.db.isTableExists(this.table_name);
logger.warn(`数据库是否存在isTableExists: ${isTableExists}`, "DBBase");
logger.info(`[${this.table_name}] table_columns 数量: ${this.table_columns.length}`, "DBBase");
if (!isTableExists) {
// 表不存在,创建新表
await this.createTable();
} else {
// 表已存在,检查并更新列
await this.updateTableColumns();
}
}
/**
* 创建新表
*/
private async createTable(): Promise<void> {
// iOS 兼容:确保 table_columns 不为空
if (this.table_columns.length === 0) {
logger.error(`[${this.table_name}] table_columns 为空,无法创建表`, "DBBase");
throw new Error(`[${this.table_name}] table_columns is empty`);
}
logger.info(`[${this.table_name}] 开始创建表, 列数: ${this.table_columns.length}`, "DBBase");
await this.db.createTable(this.table_name, this.table_columns);
this.tableCreated = true;
logger.info(`[${this.table_name}] 表创建成功`, "DBBase");
}
/**
* 更新表结构(增量添加缺失的列)
*/
private async updateTableColumns(): Promise<void> {
logger.warn(`[${this.table_name}] 表已存在, 将检查并更新列`, "DBBase");
// 获取现有列
const existingColumns = await this.db.getTableColumns(this.table_name);
logger.info(`[${this.table_name}] 现有列数: ${existingColumns.length}, 期望列数: ${this.table_columns.length}`, "DBBase");
// 如果现有列少于期望列数,增量添加缺失的列
if (existingColumns.length < this.table_columns.length) {
await this.addMissingColumns(existingColumns);
}
this.tableCreated = true;
logger.info(`[${this.table_name}] 表结构更新完成`, "DBBase");
}
/**
* 添加缺失的列
* @param existingColumns 现有的列名列表
*/
private async addMissingColumns(existingColumns: string[]): Promise<void> {
logger.warn(`[${this.table_name}] 表结构不完整,将增量添加缺失的列`, "DBBase");
// 找出缺失的列
const columnsToAdd: UTSJSONObject[] = [];
this.table_columns.forEach(colDef => {
// 解析列名(假设格式为 "columnName TYPE ...")
const parts = colDef.trim().split(" ");
const colName = parts[0];
// 检查是否已存在
if (!existingColumns.includes(colName)) {
// 提取列定义(去掉列名部分)
const definition = colDef.slice(colName.length).trim();
columnsToAdd.push({ name: colName, definition });
}
});
// 添加缺失的列
if (columnsToAdd.length > 0) {
await this.db.addColumns(this.table_name, columnsToAdd);
logger.info(`[${this.table_name}] 成功添加 ${columnsToAdd.length} 个列`, "DBBase");
}
}
async isOpen(): Promise<boolean> { async isOpen(): Promise<boolean> {
return this.db.isOpen(); return this.db.isOpen();
} }
...@@ -205,7 +250,7 @@ export default class DBBase implements IDBBase { ...@@ -205,7 +250,7 @@ export default class DBBase implements IDBBase {
async updateRecord(setData: UTSJSONObject, where: null | UTSJSONObject): Promise<any> { async updateRecord(setData: UTSJSONObject, where: null | UTSJSONObject): Promise<any> {
await this.init(); await this.init();
// const { id, ...record } = setData // UTS 不支持解构剩余参数 // const { id, ...record } = setData // UTS 不支持解构剩余参数
// 如果没有 where,尝试从 setData 中提取 id // 如果没有 where,尝试从 setData 中提取 id
let whereCondition = where; let whereCondition = where;
const dataToUpdate = JSON.parse(JSON.stringify(setData)) as UTSJSONObject; // 深拷贝以避免修改原对象 const dataToUpdate = JSON.parse(JSON.stringify(setData)) as UTSJSONObject; // 深拷贝以避免修改原对象
...@@ -224,11 +269,11 @@ export default class DBBase implements IDBBase { ...@@ -224,11 +269,11 @@ export default class DBBase implements IDBBase {
throw new Error("Update record requires 'id' in setData or explicit 'where' clause"); throw new Error("Update record requires 'id' in setData or explicit 'where' clause");
} }
} }
// 过滤掉表中不存在的字段 // 过滤掉表中不存在的字段
const validColumns = await this.getValidColumns(); const validColumns = await this.getValidColumns();
const filteredData = this.filterValidFields(dataToUpdate, validColumns); const filteredData = this.filterValidFields(dataToUpdate, validColumns);
return this.db.update(this.table_name, filteredData, whereCondition); return this.db.update(this.table_name, filteredData, whereCondition);
} }
...@@ -268,7 +313,7 @@ export default class DBBase implements IDBBase { ...@@ -268,7 +313,7 @@ export default class DBBase implements IDBBase {
const c = col as UTSJSONObject; const c = col as UTSJSONObject;
return (c.name !== null ? c.name : "") as string; return (c.name !== null ? c.name : "") as string;
}).filter((name: string): boolean => name !== ""); }).filter((name: string): boolean => name !== "");
logger.info(`DBBase: 已缓存表 ${this.table_name} 的 ${this.validColumnsCache.length} 个字段`, "DBBase"); logger.info(`DBBase: 已缓存表 ${this.table_name} 的 ${this.validColumnsCache.length} 个字段`, "DBBase");
return this.validColumnsCache; return this.validColumnsCache;
} catch (error) { } catch (error) {
......
...@@ -337,13 +337,15 @@ export default class SQLite { ...@@ -337,13 +337,15 @@ export default class SQLite {
const processedRows: any[] = []; const processedRows: any[] = [];
const rowsArray = rows as any[]; // 此时 rowsArray 可能是 UTSJSONObject[] 或 any[] const rowsArray = rows as any[]; // 此时 rowsArray 可能是 UTSJSONObject[] 或 any[]
rowsArray.forEach((row: any) => { logger.info(`[SQLite] selectSql 返回 ${rowsArray.length} 行数据`, "SQLite");
rowsArray.forEach((row: any, index: number) => {
// 增加类型检查,避免直接强转导致异常 // 增加类型检查,避免直接强转导致异常
if (row instanceof UTSJSONObject) { if (row instanceof UTSJSONObject) {
const rowObj = row as UTSJSONObject; const rowObj = row as UTSJSONObject;
const newRow = {}; const newRow = {};
const map = rowObj.toMap(); const map = rowObj.toMap();
map.forEach((value, key) => { map.forEach((value, key) => {
// 类型安全检查,防止 ClassCastException (如 Integer -> String) // 类型安全检查,防止 ClassCastException (如 Integer -> String)
...@@ -353,7 +355,7 @@ export default class SQLite { ...@@ -353,7 +355,7 @@ export default class SQLite {
} else if (value != null) { } else if (value != null) {
strVal = `${value}`; strVal = `${value}`;
} }
if (strVal.startsWith("{") || strVal.startsWith("[")) { if (strVal.startsWith("{") || strVal.startsWith("[")) {
try { try {
const parsed = JSON.parse(strVal); const parsed = JSON.parse(strVal);
...@@ -367,9 +369,10 @@ export default class SQLite { ...@@ -367,9 +369,10 @@ export default class SQLite {
}); });
processedRows.push(newRow); processedRows.push(newRow);
} else { } else {
// 如果不是 UTSJSONObject (例如是 Boolean 或其他),直接 push 或者忽略 // iOS 兼容:如果不是 UTSJSONObject,尝试直接使用
// 针对 9010007 错误,说明这里可能有非 Object 数据 if (row != null && typeof row === "object") {
// console.warn(`[SQLite] Row is not UTSJSONObject: ${row}`) processedRows.push(row);
}
} }
}); });
resolve(processedRows); resolve(processedRows);
...@@ -420,6 +423,13 @@ export default class SQLite { ...@@ -420,6 +423,13 @@ export default class SQLite {
return this.executeSql(sql); return this.executeSql(sql);
} }
/**
* 获取表的所有列名(公开方法)
*/
async getTableColumns(tableName: string): Promise<string[]> {
return this.getTableColumnsInternal(tableName);
}
private clearTableColumnsCache(tableName: string) { private clearTableColumnsCache(tableName: string) {
SQLite._tableColumnsCache.delete(this.getTableCacheKey(tableName)); SQLite._tableColumnsCache.delete(this.getTableCacheKey(tableName));
} }
...@@ -436,7 +446,7 @@ export default class SQLite { ...@@ -436,7 +446,7 @@ export default class SQLite {
return `${this.name}:${tableName}`; return `${this.name}:${tableName}`;
} }
private async getTableColumns(tableName: string): Promise<string[]> { private async getTableColumnsInternal(tableName: string): Promise<string[]> {
const cacheKey = this.getTableCacheKey(tableName); const cacheKey = this.getTableCacheKey(tableName);
const cached = SQLite._tableColumnsCache.get(cacheKey); const cached = SQLite._tableColumnsCache.get(cacheKey);
if (cached != null && cached.length > 0) { if (cached != null && cached.length > 0) {
......
...@@ -27,7 +27,11 @@ class AudioManager { ...@@ -27,7 +27,11 @@ class AudioManager {
// duration: 10 * 60 * 1000, // uts-recorder 暂不支持 duration 自动停止 // duration: 10 * 60 * 1000, // uts-recorder 暂不支持 duration 自动停止
sampleRate: 16_000, sampleRate: 16_000,
numberOfChannels: 1, numberOfChannels: 1,
format:"mp3" // iOS 兼容:iOS 不支持直接录制 MP3,会保存为 CAF 格式
// 建议使用 AAC 格式,iOS 原生支持且文件更小
format: "aac",
// iOS 兼容:encodeBitRate 必须在 24000-96000 之间
encodeBitRate: 48000
}; };
/** /**
...@@ -142,7 +146,8 @@ class AudioManager { ...@@ -142,7 +146,8 @@ class AudioManager {
const options = { const options = {
sampleRate: this.startOptions.sampleRate, sampleRate: this.startOptions.sampleRate,
numberOfChannels: this.startOptions.numberOfChannels, numberOfChannels: this.startOptions.numberOfChannels,
format: this.startOptions.format format: this.startOptions.format,
encodeBitRate: this.startOptions.encodeBitRate
} as RecorderManagerStartOptions; } as RecorderManagerStartOptions;
this.recorderManager.start(options); this.recorderManager.start(options);
} }
......
...@@ -7,7 +7,7 @@ import type { IRecorderStrategy } from "./types/strategy"; ...@@ -7,7 +7,7 @@ import type { IRecorderStrategy } from "./types/strategy";
* @Author: limin * @Author: limin
* @Date: 2025-01-02 18:34:39 * @Date: 2025-01-02 18:34:39
* @LastEditors: limin * @LastEditors: limin
* @LastEditTime: 2026-03-13 21:15:11 * @LastEditTime: 2026-04-16 16:48:35
* @FilePath: \venus\apps\uniappX\uniapp-x-tape\services\recorder\DBRecord.uts * @FilePath: \venus\apps\uniappX\uniapp-x-tape\services\recorder\DBRecord.uts
*/ */
import DBBase from "../db/DBBase.uts"; import DBBase from "../db/DBBase.uts";
...@@ -25,6 +25,10 @@ const BASE_COLUMNS = [ ...@@ -25,6 +25,10 @@ const BASE_COLUMNS = [
`recordStatus INTEGER DEFAULT 1` `recordStatus INTEGER DEFAULT 1`
]; ];
const defaultStrategy = RecorderStrategyFactory.getDefaultStrategy();
const strategyColumns = defaultStrategy.getTableColumns();
const allColumns = [...BASE_COLUMNS, ...strategyColumns];
class DBRecord extends DBBase implements IDBRecord { class DBRecord extends DBBase implements IDBRecord {
private static instance: DBRecord | null = null; private static instance: DBRecord | null = null;
...@@ -33,13 +37,12 @@ class DBRecord extends DBBase implements IDBRecord { ...@@ -33,13 +37,12 @@ class DBRecord extends DBBase implements IDBRecord {
private strategy: IRecorderStrategy = RecorderStrategyFactory.getDefaultStrategy(); private strategy: IRecorderStrategy = RecorderStrategyFactory.getDefaultStrategy();
private constructor() { private constructor() {
// 初始时使用默认策略的列
super(TABLE_NAME, []); // 传入完整的列定义
// super 构造函数会赋值给 this.table_columns super(TABLE_NAME, allColumns);
// 但我们希望它是动态的。
// DBBase 的 table_columns 是 protected/public? 假设是 protected。 // 设置策略
// 我们在 setStrategy 时更新它。 this.strategy = defaultStrategy;
this.updateColumnsFromStrategy();
} }
static getInstance(): DBRecord { static getInstance(): DBRecord {
...@@ -84,6 +87,26 @@ class DBRecord extends DBBase implements IDBRecord { ...@@ -84,6 +87,26 @@ class DBRecord extends DBBase implements IDBRecord {
return this.parseRecords(records); return this.parseRecords(records);
} }
/**
* 根据 ID 获取单条记录(重写父类方法,处理 JSON 字段)
*/
async getRecordById(id: any): Promise<null | UTSJSONObject> {
await this.init();
// 调用父类方法获取原始数据
const rawRecord = await super.getRecordById(id);
if (rawRecord === null) {
return null;
}
// 使用 parseRecords 处理 JSON 字段
const parsed = this.parseRecords([rawRecord]);
if (parsed.length > 0) {
// 转换回 UTSJSONObject
return JSON.parse(JSON.stringify(parsed[0])) as UTSJSONObject;
}
return rawRecord;
}
override async init(): Promise<boolean> { override async init(): Promise<boolean> {
if (this._initPromise !== null) return this._initPromise; if (this._initPromise !== null) return this._initPromise;
...@@ -138,15 +161,15 @@ class DBRecord extends DBBase implements IDBRecord { ...@@ -138,15 +161,15 @@ class DBRecord extends DBBase implements IDBRecord {
}).filter((name: string): boolean => name !== ""); }).filter((name: string): boolean => name !== "");
logger.info(`DBRecord: existingColumns: ${JSON.stringify(existingColumns)}`, "DBRecord"); logger.info(`DBRecord: existingColumns: ${JSON.stringify(existingColumns)}`, "DBRecord");
const columnsToAdd: UTSJSONObject[] = []; const columnsToAdd: UTSJSONObject[] = [];
this.table_columns.forEach(colDef => { this.table_columns.forEach(colDef => {
// trim().split(/\s+/) 正则在 UTS 可能不完全支持,用 split(' ') // trim().split(/\s+/) 正则在 UTS 可能不完全支持,用 split(' ')
// 假设 colDef 是 "name TYPE ..." // 假设 colDef 是 "name TYPE ..."
const parts = colDef.trim().split(" "); const parts = colDef.trim().split(" ");
const name = parts[0]; const name = parts[0];
// 简单的判断,如果 name 不为空且不在 existingColumns 中 // 简单的判断,如果 name 不为空且不在 existingColumns 中
if (name !== "" && !existingColumns.includes(name)) { if (name !== "" && !existingColumns.includes(name)) {
// 重新组装 definition: 去掉 name,剩下的就是 definition // 重新组装 definition: 去掉 name,剩下的就是 definition
...@@ -154,17 +177,17 @@ class DBRecord extends DBBase implements IDBRecord { ...@@ -154,17 +177,17 @@ class DBRecord extends DBBase implements IDBRecord {
columnsToAdd.push({ name, definition }); columnsToAdd.push({ name, definition });
} }
}); });
if (columnsToAdd.length > 0) { if (columnsToAdd.length > 0) {
await this.db.addColumns(this.table_name, columnsToAdd); await this.db.addColumns(this.table_name, columnsToAdd);
const addedNames: string[] = []; const addedNames: string[] = [];
columnsToAdd.forEach(c => { columnsToAdd.forEach(c => {
addedNames.push(c.name as string); addedNames.push(c.name as string);
}); });
logger.info(`DBRecord: Added columns ${addedNames.join(", ")}`, "DBRecord"); logger.info(`DBRecord: Added columns ${addedNames.join(", ")}`, "DBRecord");
// 清除 DBBase 的表结构缓存,确保下次查询时获取最新的表结构 // 清除 DBBase 的表结构缓存,确保下次查询时获取最新的表结构
this.clearValidColumnsCache(); this.clearValidColumnsCache();
} }
...@@ -184,21 +207,31 @@ class DBRecord extends DBBase implements IDBRecord { ...@@ -184,21 +207,31 @@ class DBRecord extends DBBase implements IDBRecord {
records.forEach((item: any) => { records.forEach((item: any) => {
try { try {
const itemObj = item as UTSJSONObject; // iOS 兼容:可能是普通对象或 UTSJSONObject
let itemObj: UTSJSONObject;
if (item instanceof UTSJSONObject) {
itemObj = item as UTSJSONObject;
} else {
// 如果是普通对象,转换为 UTSJSONObject
itemObj = JSON.parse(JSON.stringify(item)) as UTSJSONObject;
}
// 尝试解析 JSON 字符串字段 // 尝试解析 JSON 字符串字段
listFields.forEach(field => { listFields.forEach(field => {
const val = itemObj.get(field); // iOS 兼容:使用索引访问而不是 .get()
const val = itemObj[field];
if (typeof val === "string") { if (typeof val === "string") {
try { try {
// 如果是字符串,尝试解析为 JSON // 如果是字符串,尝试解析为 JSON
// 注意:UTS 中 JSON.parse 返回 Any?,需要根据实际情况处理 // 注意:UTS 中 JSON.parse 返回 Any?,需要根据实际情况处理
// 这里直接存回去,UTSJSONObject 会处理 // 这里直接存回去,UTSJSONObject 会处理
const parsed = JSON.parse(val as string); const parsed = JSON.parse(val as string);
itemObj.set(field, parsed); // iOS 兼容:使用索引赋值而不是 .set()
itemObj[field] = parsed;
} catch { } catch {
// 解析失败,保持原值或设为 null // 解析失败,保持原值或设为 null
console.warn(`DBRecord: Failed to parse field ${field}: ${val}`); console.warn(`DBRecord: Failed to parse field ${field}: ${val}`);
// itemObj.set(field, null); // 保持原值可能更好,或者设为空数组/对象 // itemObj[field] = null; // 保持原值可能更好,或者设为空数组/对象
} }
} }
}); });
......
...@@ -11,7 +11,7 @@ import { replaceAll } from "../../utils/index.uts"; ...@@ -11,7 +11,7 @@ import { replaceAll } from "../../utils/index.uts";
* @Author: limin * @Author: limin
* @Date: 2026-01-28 20:57:12 * @Date: 2026-01-28 20:57:12
* @LastEditors: limin * @LastEditors: limin
* @LastEditTime: 2026-03-31 17:08:33 * @LastEditTime: 2026-04-16 14:19:14
* @FilePath: \venus\apps\uniappX\uniapp-x-tape\services\recorder\RecordSave.uts * @FilePath: \venus\apps\uniappX\uniapp-x-tape\services\recorder\RecordSave.uts
*/ */
import Queue from "../../utils/Queue.uts"; import Queue from "../../utils/Queue.uts";
...@@ -101,9 +101,8 @@ class RecordSave { ...@@ -101,9 +101,8 @@ class RecordSave {
return _record; return _record;
} }
_record.status = FileStatus.HasFile; _record.status = FileStatus.HasFile;
const recordUrlList = this.urlListFilter(_record.recordUrlList as UTSJSONObject[]);
_record.recordUrlList = recordUrlList;
const recordUrlList = this.urlListFilter(_record.recordUrlList as UTSJSONObject[]);
// find target file // find target file
let targetFile: null | UTSJSONObject = null; let targetFile: null | UTSJSONObject = null;
for (const item of recordUrlList) { for (const item of recordUrlList) {
...@@ -117,6 +116,16 @@ class RecordSave { ...@@ -117,6 +116,16 @@ class RecordSave {
this._updateFileStatus(targetFile, fileInfo); this._updateFileStatus(targetFile, fileInfo);
} else { } else {
logger.warn(`【接待记录保存服务】 == 未找到匹配的文件记录: ${JSON.stringify(fileInfo)}`, "RecordSave"); logger.warn(`【接待记录保存服务】 == 未找到匹配的文件记录: ${JSON.stringify(fileInfo)}`, "RecordSave");
// iOS 兼容:如果没找到,直接添加到 recordUrlList
// 注意:文件对象的结构必须与 _handleCompletedRecord 中期望的一致
const newFileRecord: UTSJSONObject = {
file: fileInfo.serverPath as string, // 服务器路径,用于提交到后端
filePathOnClient: fileInfo.clientPath as string, // 本地路径,用于删除文件
fileName: fileInfo.fileName as string,
status: fileInfo.status as number
};
recordUrlList.push(newFileRecord);
_record.recordUrlList = recordUrlList;
} }
return _record; return _record;
} }
...@@ -243,36 +252,47 @@ class RecordSave { ...@@ -243,36 +252,47 @@ class RecordSave {
}; };
} }
_parseUploadedFile(data: UTSJSONObject): UTSJSONObject { _parseUploadedFile(payload: UTSJSONObject): UTSJSONObject {
const detail = data.detail as UTSJSONObject; // const detail = data.detail as UTSJSONObject;
const dataList = detail.data as UTSJSONObject[]; // const dataList = detail.data as UTSJSONObject[];
const payload = dataList[0]; // const payload = dataList[0];
// iOS 兼容:添加类型断言,确保正确提取字段
const recordId = payload.recordId; const recordId = payload.recordId as null | string;
const fileName = payload.fileName; const fileName = payload.fileName as null | string;
const filePath = payload.filePath; const filePath = payload.filePath as null | string;
const clientPath = (filePath as string ?? "") + (fileName as string ?? ""); const clientPath = (filePath ?? "") + (fileName ?? "");
if (recordId === null) { if (recordId === null) {
return { error: "文件上传回调,缺少recordId", data, filePath: clientPath }; return { error: "文件上传回调,缺少recordId", data: payload, filePath: clientPath };
}
const code = payload.code as null | number;
const message = payload.message as null | string;
const fileData = payload.data as null | UTSJSONObject;
if (fileData === null) {
return { error: `解析异常: fileData为null`, data: payload, recordId, filePath: clientPath };
}
const oss = fileData.oss as null | UTSJSONObject;
if (oss === null) {
return { error: `解析异常: oss为null`, data: payload, recordId, filePath: clientPath };
}
const res = oss.res as null | UTSJSONObject;
if (res === null) {
return { error: `解析异常: res为null`, data: payload, recordId, filePath: clientPath };
}
const requestUrls = res.requestUrls as null | string[];
if (requestUrls === null || requestUrls.length === 0) {
return { error: `解析异常: requestUrls为空`, data: payload, recordId, filePath: clientPath };
} }
const code = payload.code;
const message = payload.message;
const fileData = payload.data as UTSJSONObject;
const oss = fileData.oss as UTSJSONObject;
const res = oss.res as UTSJSONObject;
const requestUrls = res.requestUrls as string[];
const serverUrl = requestUrls[0]; const serverUrl = requestUrls[0];
if (code !== 0 || serverUrl === null) { if (code !== 0 || serverUrl === null) {
return { error: `解析异常: code->${code} message->${message}`, data, recordId, filePath: clientPath }; return { error: `解析异常: code->${code} message->${message}`, data: payload, recordId, filePath: clientPath };
} }
// iOS 兼容:明确返回 error: null
return { return {
error: null,
recordId, recordId,
fileName, fileName,
clientPath, clientPath,
serverPath: `${serverUrl}`.split("?")[0], serverPath: `${serverUrl}`,//.split("?")[0],
status: FileStatus.Uploaded status: FileStatus.Uploaded
}; };
} }
...@@ -572,7 +592,7 @@ class RecordSave { ...@@ -572,7 +592,7 @@ class RecordSave {
} }
isLegalFile(file: string): boolean { isLegalFile(file: string): boolean {
return file !== "" && (file.toLowerCase().endsWith(".mp3") || file.toLowerCase().endsWith(".m4a")); return file !== "" && (file.toLowerCase().endsWith(".mp3") || file.toLowerCase().endsWith(".m4a") || file.toLowerCase().endsWith(".aac"));
} }
off() { off() {
...@@ -596,7 +616,8 @@ class RecordSave { ...@@ -596,7 +616,8 @@ class RecordSave {
// const { data: d, ...o } = payload // UTS 不支持解构剩余 // const { data: d, ...o } = payload // UTS 不支持解构剩余
const input = serializeIfObject(payload); const input = serializeIfObject(payload);
logger.warn(`【接待记录保存服务】 == 开始文件信息解析-> ${input}`, "RecordSave"); logger.warn(`【接待记录保存服务】 == 开始文件信息解析-> ${input}`, "RecordSave");
return this._parseUploadedFile(data); // iOS 兼容:传递 payload 对象,而不是序列化后的字符串
return this._parseUploadedFile(payload);
} }
// CASE 2: 直接调用 (data 是 record 对象) // CASE 2: 直接调用 (data 是 record 对象)
......
...@@ -10,7 +10,7 @@ ...@@ -10,7 +10,7 @@
// #ifdef APP // #ifdef APP
import { layoutService } from '@/services/LayoutService.uts' import { layoutService } from '@/services/LayoutService.uts'
import { lockOrientation, unlockOrientation } from '@/utils/plus-screen.uts' import { lockOrientation, unlockOrientation } from '@/utils/plus-screen.uts'
import { updateResolutionConfig } from '@/services/adapter/index.uts' // import { updateResolutionConfig } from '@/services/adapter/index.uts'
// #endif // #endif
var refreshTimer: number = 0 var refreshTimer: number = 0
...@@ -76,7 +76,7 @@ function scheduleRefresh(delayMs: number): void { ...@@ -76,7 +76,7 @@ function scheduleRefresh(delayMs: number): void {
} }
refreshTimer = setTimeout((): void => { refreshTimer = setTimeout((): void => {
layoutService.refreshScreenInfo() layoutService.refreshScreenInfo()
updateResolutionConfig() // updateResolutionConfig()
refreshTimer = 0 refreshTimer = 0
}, delayMs) }, delayMs)
} }
...@@ -86,7 +86,7 @@ function scheduleRefreshAfterPadUnlock(): void { ...@@ -86,7 +86,7 @@ function scheduleRefreshAfterPadUnlock(): void {
scheduleRefresh(250) scheduleRefresh(250)
setTimeout((): void => { setTimeout((): void => {
layoutService.refreshScreenInfo() layoutService.refreshScreenInfo()
updateResolutionConfig() // updateResolutionConfig()
}, 750) }, 750)
} }
......
...@@ -9,10 +9,11 @@ import { handleError } from "./error.uts"; ...@@ -9,10 +9,11 @@ import { handleError } from "./error.uts";
* @returns Promise<boolean> true: 已获取权限, false: 未获取权限 * @returns Promise<boolean> true: 已获取权限, false: 未获取权限
*/ */
export async function ensurePermission(permissionName: string, hintText: string): Promise<boolean> { export async function ensurePermission(permissionName: string, hintText: string): Promise<boolean> {
return new Promise((resolve) => { return new Promise((resolve,reject) => {
try { try {
checkPermission(permissionName, (result) => { checkPermission(permissionName, (result) => {
if (result === "granted") { if (result === "granted") {
console.log("PermissionUtils", `已获取权限 (${permissionName})`);
resolve(true); resolve(true);
} else { } else {
requestPermissions({ requestPermissions({
...@@ -28,6 +29,7 @@ export async function ensurePermission(permissionName: string, hintText: string) ...@@ -28,6 +29,7 @@ export async function ensurePermission(permissionName: string, hintText: string)
}); });
if (granted) { if (granted) {
console.log("PermissionUtils", `已获取权限1 (${permissionName})`);
resolve(true); resolve(true);
} else { } else {
uni.showToast({ uni.showToast({
...@@ -59,18 +61,18 @@ export async function ensurePermission(permissionName: string, hintText: string) ...@@ -59,18 +61,18 @@ export async function ensurePermission(permissionName: string, hintText: string)
*/ */
export async function ensurePermissions(permissionNames: string[], hintText: string): Promise<boolean> { export async function ensurePermissions(permissionNames: string[], hintText: string): Promise<boolean> {
if (permissionNames.length === 0) return true; if (permissionNames.length === 0) return true;
// 简单实现:逐个检查/请求,或者一次性请求 // 简单实现:逐个检查/请求,或者一次性请求
// 这里的 requestPermissions 似乎支持数组,所以我们可以直接调用 requestPermissions // 这里的 requestPermissions 似乎支持数组,所以我们可以直接调用 requestPermissions
// 但是 checkPermission 似乎只支持单个 string (根据 index.uts 的签名) // 但是 checkPermission 似乎只支持单个 string (根据 index.uts 的签名)
// export function checkPermission(permission: string, complete: (result: string) => void): void // export function checkPermission(permission: string, complete: (result: string) => void): void
// 如果需要检查多个,可能需要先检查一遍,如果有未授权的,再统一请求 // 如果需要检查多个,可能需要先检查一遍,如果有未授权的,再统一请求
// 简化策略:直接调用 requestPermissions 请求所有,它内部应该会处理已授权的情况? // 简化策略:直接调用 requestPermissions 请求所有,它内部应该会处理已授权的情况?
// 或者我们可以先 check 第一个,如果没授权就请求所有。 // 或者我们可以先 check 第一个,如果没授权就请求所有。
// 但 permission-handler-plus 的 requestPermissions 似乎是请求弹窗。 // 但 permission-handler-plus 的 requestPermissions 似乎是请求弹窗。
return new Promise((resolve) => { return new Promise((resolve) => {
try { try {
requestPermissions({ requestPermissions({
......
...@@ -30,7 +30,8 @@ class Storage { ...@@ -30,7 +30,8 @@ class Storage {
* const rawData = storage.getRaw('user'); * const rawData = storage.getRaw('user');
*/ */
get(key: string): any | null { get(key: string): any | null {
return uni.getStorageSync(key); const data = uni.getStorageSync(key);
return data;
} }
/** /**
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!