Commit 1c9d6a27 by 张立顺

fix: 拆分素材图片缓存并优化离线车系切换

1 parent da6f3b46
import http from '../request/http'
import { env } from '../../env'
import materialCache from '../../utils/materialCache'
const ENV = env == 'ip' ? 'develop' : env,
serverConfig = {
......@@ -133,7 +134,12 @@ const getImageVersion = async () => {
return accountInfo?.version || Date.now()
}
/**获取素材配置 */
const sourceRequests = new Map()
const getSoureData = async (shopMerchantId, sceneType, params = {}) => {
const storageName = materialCache.getSourceKey(shopMerchantId, sceneType, params)
const requestId = (sourceRequests.get(storageName) || 0) + 1
sourceRequests.set(storageName, requestId)
const isCurrent = () => sourceRequests.get(storageName) === requestId
try {
const res = await getEquityMaterialId({
merchantId: shopMerchantId,
......@@ -144,11 +150,9 @@ const getSoureData = async (shopMerchantId, sceneType, params = {}) => {
id: res.id
})
if (data) {
let { toolList, materialInfoList } = data,
storageName = `source_${sceneType}_${shopMerchantId}`
if (params.brandId && params.subBrandId) storageName += `_${params.brandId}_${params.subBrandId}`
let { toolList = [], materialInfoList = [] } = data
let insurance = materialInfoList.find(e => e.componentName == 'insurance'),
hasEquity = toolList.find(e => e.id == insurance.id)
hasEquity = insurance && toolList.find(e => e.id == insurance.id)
if (insurance && hasEquity) {
let configList
try {
......@@ -157,6 +161,7 @@ const getSoureData = async (shopMerchantId, sceneType, params = {}) => {
} catch (error) {
configList = uni.$storage.get('findReceptionpriproConfigList')
}
configList = Array.isArray(configList) ? configList : []
const toolOtherList = configList.map(i => {
return {
id: hasEquity.id + 100 + i.id,
......@@ -181,14 +186,22 @@ const getSoureData = async (shopMerchantId, sceneType, params = {}) => {
})
materialInfoList = materialInfoList.concat(moduleOtherList)
}
data.toolList = await imgTransformBase64(toolList, ['shortTitleUrl'])
data.moduleList = await imgTransformBase64(materialInfoList, ['thumbnail', 'receptionSourceDetailList', 'screenList'])
uni.setStorageSync(storageName, {
moduleList: data.moduleList,
toolList: data.toolList,
id: res.id
})
return Promise.resolve(data)
if (!isCurrent()) return
data = { ...data, id: res.id, toolList, moduleList: materialInfoList }
let cacheSaved = false
try {
const base = await materialCache.saveSourceCache(storageName, data)
data = { ...data, ...base }
cacheSaved = true
} catch (error) {
console.warn('素材基础缓存写入失败', storageName)
}
if (!isCurrent()) return
// 首屏只等待基础数据;图片下载、转换和写入在后台进行。
setTimeout(() => {
if (cacheSaved && isCurrent()) materialCache.cacheMaterialImages(storageName, data).catch(() => {})
}, 0)
return data
} else throw false
} else throw false
} catch (error) {
......@@ -201,64 +214,6 @@ const getSoureData = async (shopMerchantId, sceneType, params = {}) => {
})
}
}
/**批量图片转base64 */
const imgTransformBase64 = async (imgList = [], keyList = []) => {
return await Promise.all(
imgList?.map(async e => {
await Promise.all(
Object.keys(e).map(async key => {
if (keyList.includes(key)) {
let isArray = Array.isArray(e[key])
if (isArray) {
await Promise.all(
e[key].map(async i => {
await Promise.all(
Object.keys(i).map(async k => {
// i[`original_${k}`] = JSON.parse(JSON.stringify(i[k]))
if (k == 'detailUrl' && i[k]) i[k] = await getBase64(i[k])
})
)
})
)
} else {
if (typeof e[key] === 'string' && e[key]) {
// e[`original_${key}`] = JSON.parse(JSON.stringify(e[key]))
e[key] = await getBase64(e[key])
}
if (e[key] && typeof e[key] === 'object') {
await Promise.all(
Object.keys(e[key]).map(async k => {
// e[key][`original_${k}`] = JSON.parse(JSON.stringify(e[key][k]))
if (e[key][k]) e[key][k] = await getBase64(e[key][k])
})
)
}
}
}
})
)
return e
})
)
}
/**转base64 */
const getBase64 = async 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)}`
resolve(base64)
},
fail: err => {
resolve(url)
// reject(err)
}
})
})
}
module.exports = {
getImageVersion,
getMockData,
......
......@@ -53,7 +53,7 @@ class Request {
title: '网络异常',
icon: 'none'
})
uni.$logger.locale.error('网络异常')
uni.$logger.local.error('网络异常')
reject('网络异常')
return
}
......
......@@ -22,6 +22,8 @@
</template>
<script type='text/ecmascript-6'>
import materialCache from '@/utils/materialCache'
export default {
name: 'CarBrands',
props: {
......@@ -81,6 +83,9 @@ export default {
},
mounted() {
},
beforeDestroy() {
this.cancelPendingRequests()
},
methods: {
autoSelect() {
const { carBrandList, boutiqueDefaultCarBrandId, defaultCarId } = this
......@@ -89,26 +94,11 @@ export default {
if (carIndex < 0) carIndex = 0
if (carBrandList.length) this.selectCar(carBrandList[carIndex], true, defaultCarId)
},
open() {
async open() {
const requestId = (this._brandRequestId || 0) + 1
this._brandRequestId = requestId
this.$store.dispatch('setCarBrandOpenStatus', true)
const userInfo = uni.$storage.get("userInfo"),
{ shopMerchantId } = userInfo;
/**获取品牌车型 */
uni.$api.commonApi
.getMerchantCarBrandList([shopMerchantId])
.then(({ data }) => {
let list = data[0].carBrandList,
carBrandList = [];
list?.map((e) => {
e.childs.map((i) => {
i.brandName = e.name
i.brandId = e.id;
carBrandList.push(i);
});
});
this.$store.dispatch("setCarBrandsList", carBrandList);
uni.$storage.set("carBrandList", carBrandList);
})
// 已有品牌先展示,离线时不再触发品牌接口。
const { carBrand } = this
if (carBrand) {
const { carBrandList } = this,
......@@ -118,12 +108,28 @@ export default {
this.$refs.carBrandListVisible.open()
this.carBrandListOff = true
}
return
} else {
this.$refs.carBrandListVisible.open()
this.carBrandListOff = true
}
if (!await materialCache.getNetworkStatus() || this._brandRequestId !== requestId) return
try {
const { shopMerchantId } = uni.$storage.get('userInfo') || {}
const { data } = await uni.$api.commonApi.getMerchantCarBrandList([shopMerchantId])
if (this._brandRequestId !== requestId) return
const carBrandList = []
;(data?.[0]?.carBrandList || []).forEach(brand => {
;(brand.childs || []).forEach(child => {
carBrandList.push({ ...child, brandName: brand.name, brandId: brand.id })
})
})
this.$store.dispatch('setCarBrandsList', carBrandList)
uni.$storage.set('carBrandList', carBrandList)
} catch (error) {
// 刷新失败时保留当前可用的品牌列表。
}
this.$refs.carBrandListVisible.open()
this.carBrandListOff = true
},
selectCar(e, auto = false, carId) {
async selectCar(e, auto = false, carId) {
if (!e.brandId || !e.id) return uni.showToast({
title: "车型ID或品牌ID为空",
icon: "none",
......@@ -132,6 +138,9 @@ export default {
index = 0
if (clickFlga) return
this.clickFlga = true
const requestId = (this._carRequestId || 0) + 1
this._carRequestId = requestId
const isCurrent = () => this._carRequestId === requestId
// 进入车系选择过程中保持弹层打开态,避免「查看长图」按钮冒出来
this.$store.dispatch('setCarBrandOpenStatus', true)
this.selectItem = {
......@@ -140,8 +149,14 @@ export default {
carChildsBrandName: e.name,
carChildsBrandId: e.id
}
const carList = uni.getStorageSync(`${e.id}_${e.brandId}_carlist`)
if (carList) {
const cacheKey = `${e.id}_${e.brandId}_carlist`
const refreshIds = this._carRefreshIds || (this._carRefreshIds = new Map())
const refreshId = (refreshIds.get(cacheKey) || 0) + 1
refreshIds.set(cacheKey, refreshId)
const isLatestRefresh = () => refreshIds.get(cacheKey) === refreshId
const carList = uni.getStorageSync(cacheKey)
const hasCache = Array.isArray(carList) && carList.length > 0
if (hasCache) {
this.clickFlga = false
this.carlist = carList
if (auto && carList.length) {
......@@ -151,39 +166,60 @@ export default {
}
else this.$refs.carBoxVisible.open()
} else {
this.carlist = []
if (!auto) uni.showLoading({
mask: true
})
}
uni.$api.commonApi.getCarBrandsList({
brandId: e.brandId,
childBrandId: e.id
}).then(res => {
uni.hideLoading()
this.carlist = res
if (res) uni.setStorageSync(`${e.id}_${e.brandId}_carlist`, res)
if (!carList) {
if (auto && res.length) {
if (carId) index = res.findIndex(i => i.id == carId)
try {
const online = await materialCache.getNetworkStatus()
// 缓存已自动选中时仍允许后台刷新,弹层状态只由当前选择更新。
if (!isLatestRefresh() || (!isCurrent() && !hasCache)) return
if (!online) {
if (!hasCache) uni.showToast({ title: '该品牌车系尚未缓存,请联网后重试', icon: 'none' })
return
}
const res = await uni.$api.commonApi.getCarBrandsList({
brandId: e.brandId,
childBrandId: e.id
})
if (!isLatestRefresh()) return
if (Array.isArray(res)) uni.setStorageSync(cacheKey, res)
if (!isCurrent()) return
const nextList = Array.isArray(res) ? res : []
this.carlist = nextList
if (!hasCache) {
if (auto && nextList.length) {
if (carId) index = nextList.findIndex(i => i.id == carId)
if (index < 0) index = 0
this.handleSelect(res[index])
}
else {
this.handleSelect(nextList[index])
} else {
this.$store.dispatch('setCarBrandOpenStatus', true)
this.$refs.carBoxVisible.open()
}
}
this.clickFlga = false
}).catch(err => {
this.clickFlga = false
uni.hideLoading()
})
} catch (error) {
// 请求过程中断网时保留已展示的缓存。
} finally {
if (isCurrent()) {
this.clickFlga = false
uni.hideLoading()
}
}
},
cancelPendingRequests() {
this._brandRequestId = (this._brandRequestId || 0) + 1
this._carRequestId = (this._carRequestId || 0) + 1
if (this.clickFlga) uni.hideLoading()
this.clickFlga = false
},
handleSelect(item) {
const customerInfo = this.$store.state.user.customerInfo,
this.cancelPendingRequests()
const customerInfo = { ...this.$store.state.user.customerInfo },
{ selectItem, linkage } = this
Object.assign(customerInfo, {
carModel: item.name,
carModelId: item.id,
carBrand: selectItem.carChildsBrandName,
carBrandId: selectItem.carChildsBrandId,
oneCarBrand: selectItem.carBrand,
......@@ -198,8 +234,8 @@ export default {
oneCarBrand:${customerInfo.oneCarBrand},
oneCarBrandId:${customerInfo.oneCarBrandId}`)
this.$store.dispatch('setCustomerInfo', customerInfo)
this.$store.dispatch('updateViewKey')
this.$store.dispatch('setCurrentCarInfo', selectItem)
this.$store.dispatch('updateViewKey')
}
this.$refs.carBoxVisible?.close();
this.$refs.carBrandListVisible?.close();
......@@ -211,6 +247,7 @@ export default {
})
},
close() {
this.cancelPendingRequests()
this.$refs?.carBoxVisible?.close();
this.$refs?.carBrandListVisible?.close()
this.carBrandListOff = false
......@@ -218,6 +255,7 @@ export default {
},
closeCarBoxVisible() {
this.cancelPendingRequests()
// 关车系弹窗:若还要从品牌列表回来,保持打开态;否则关闭
if (this.carBrandListOff) {
this.$store.dispatch('setCarBrandOpenStatus', true)
......@@ -227,6 +265,7 @@ export default {
this.$emit('close')
},
clickClose() {
this.cancelPendingRequests()
this.carBrandListOff = false
this.$store.dispatch('setCarBrandOpenStatus', false)
this.$emit('close')
......@@ -260,4 +299,4 @@ export default {
}
}
}
</style>
\ No newline at end of file
</style>
......@@ -9,7 +9,7 @@
<view class="list-body">
<template v-for="(i, index) in data">
<view :class="['item', { active: i[idKey] == id }]" :key="index" @click="jump(i)">
<image class="icon" :src="i.shortTitleUrl" mode="scaleToFill" />
<image v-if="!show" class="icon" :src="i.shortTitleUrl" mode="scaleToFill" />
{{ i.shortTitle }}
</view>
</template>
......@@ -59,6 +59,9 @@ export default {
},
},
watch: {
show (hidden) {
this.$emit('visibility-change', !hidden)
},
watchStatus: {
immediate: true,
handler (newval) {
......@@ -209,4 +212,4 @@ export default {
// 移除之前的 keyframes
// @keyframes scale-up-top-right { ... }
}
</style>
\ No newline at end of file
</style>
......@@ -34,6 +34,7 @@
import detail from './detail/detail'
import { mapMutations } from 'vuex'
import HomeFrame from '@/components/HomeFrame/index.vue'
import materialCache from '@/utils/materialCache'
// import storge from "@/mixin/storge";
export default {
// mixins: [storge],
......@@ -78,7 +79,29 @@ export default {
},
async onLoad () {
uni.hideLoading()
const mockdata = await uni.$api.systemApi.getMockData(true) //获取APP配置信息
this._sourceDisposed = false
this._sourceNetworkHandler = ({ isConnected }) => {
this.restoreSourceCache(isConnected).then(() => {
if (isConnected && !this._sourceDisposed) this.get_Vehicle_Sales_Data()
})
}
uni.onNetworkStatusChange(this._sourceNetworkHandler)
const online = await materialCache.getNetworkStatus()
// 素材恢复不能等待配置中心或品牌接口,否则断网冷启动无法展示缓存。
await this.restoreSourceCache(online)
if (this._sourceDisposed) return
if (!online) {
this.get_Vehicle_Sales_Data(false)
this.requested = true
return
}
let mockdata = uni.$storage.get('mock_data') || {}
try {
mockdata = await uni.$api.systemApi.getMockData(true) || mockdata
} catch (error) {
// 已恢复的素材不受配置接口失败影响。
}
if (this._sourceDisposed) return
if (this.channelType == 1 && mockdata.boutiqueDefaultCarBrandId) {
this.$store.state.user.boutiqueDefaultCarBrandId = mockdata.boutiqueDefaultCarBrandId //默认车辆品牌
if (mockdata.defaultCarId) this.$store.state.user.defaultCarId = mockdata.defaultCarId //默认车系
......@@ -87,6 +110,11 @@ export default {
this.requested = true
this.$refs.home.updateApp(true)
},
onUnload () {
this._sourceDisposed = true
this._sourceRequestId = (this._sourceRequestId || 0) + 1
if (this._sourceNetworkHandler) uni.offNetworkStatusChange(this._sourceNetworkHandler)
},
async onShow () {
const userInfo = uni.$storage.get('userInfo')
if (!userInfo.shopMerchantId || !userInfo.shopMerchantName) {
......@@ -101,20 +129,23 @@ export default {
},
methods: {
...mapMutations('audio', ['setReceptionStatus']),
init () {
this.findPayInfo()
async init () {
if (!await materialCache.getNetworkStatus() || this._sourceDisposed) return
this.findPayInfo().catch(() => {})
if (this.requested && !this.id) this.$refs.home.updateApp()
},
/**获取车型&销售数据 */
get_Vehicle_Sales_Data () {
get_Vehicle_Sales_Data (online = true) {
const userInfo = uni.$storage.get('userInfo'),
storageCarBrandList = uni.$storage.get('carBrandList'),
storageEmployeeList = uni.$storage.get('employeeList'),
{ shopMerchantId } = userInfo
if (storageCarBrandList) this.$store.dispatch('setCarBrandsList', storageCarBrandList)
if (storageEmployeeList) this.$store.dispatch('setEmployeeList', storageEmployeeList)
if (!online) return
/**获取品牌车型 */
uni.$api.commonApi.getMerchantCarBrandList([shopMerchantId]).then(({ data }) => {
if (this._sourceDisposed) return
let list = data[0].carBrandList,
carBrandList = [],
brandIdList = [],
......@@ -136,26 +167,57 @@ export default {
this.getCarBrandsList(carBrandList, index)
}
}).catch(() => {
if (this._sourceDisposed) return
const brands = Array.isArray(storageCarBrandList) ? storageCarBrandList : []
this.getSoure(brands.map(item => item.brandId), brands.map(item => item.id))
})
/**获取销售人员 */
uni.$api.commonApi.getEmployeeList({
merchantId: shopMerchantId
}).then(res => {
if (this._sourceDisposed) return
this.$store.dispatch('setEmployeeList', res || [])
uni.$storage.set('employeeList', res || [])
}).catch(() => {})
},
async restoreSourceCache (online) {
const requestId = this._sourceRequestId = (this._sourceRequestId || 0) + 1
const isCurrent = () => !this._sourceDisposed && requestId === this._sourceRequestId
const key = materialCache.getSourceKey(this.shopMerchantId, this.sceneType)
const data = await this.readHomeSource(key, online, isCurrent)
if (!isCurrent()) return
if (data) this.setViewInfo(data)
else this.loadComplete = true
},
async readHomeSource (key, online, isCurrent) {
const base = await materialCache.readSourceCache(key, online, { baseOnly: true, isCurrent })
if (!base || online || !isCurrent()) return base
// 首页只用封面,不读取详情页和所有车系的正文图片。
return materialCache.hydrateSourceImages(key, base, {
moduleIds: base.moduleList.map(item => item.id), toolIds: [],
fields: ['thumbnail', 'homeEntranceCover'], isCurrent
})
},
// 查询素材
async getSoure (brandIdList, subBrandIdList) {
const requestId = this._sourceRequestId = (this._sourceRequestId || 0) + 1
const isCurrent = () => !this._sourceDisposed && requestId === this._sourceRequestId
const { shopMerchantId, sceneType } = this
let data = uni.getStorageSync(`source_${sceneType}_${shopMerchantId}`)
const online = await materialCache.getNetworkStatus()
const key = materialCache.getSourceKey(shopMerchantId, sceneType)
const data = await this.readHomeSource(key, online, isCurrent)
if (!isCurrent()) return
if (data) this.setViewInfo(data)
let requestData = await uni.$api.systemApi.getSoureData(shopMerchantId, sceneType, {
brandIdList,
subBrandIdList
})
if (requestData) this.setViewInfo(requestData)
else this.loadComplete = true
if (!online) { this.loadComplete = true; return }
try {
const requestData = await uni.$api.systemApi.getSoureData(shopMerchantId, sceneType, { brandIdList, subBrandIdList })
if (isCurrent() && requestData) this.setViewInfo(requestData)
} catch (error) {
// 保留已经展示的缓存数据。
} finally {
if (isCurrent()) this.loadComplete = true
}
},
errorImg (index) {
this.moduleList[index].showAlt = true
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!