Commit 5a91d0e7 by liimin

refactor(store): 重构全局状态管理以兼容旧项目

- 将原有的模块化 store 重构为 Vuex 风格的扁平化结构
- 实现与旧项目 gl_tape/store 兼容的 API(dispatch, commit, getters)
- 暂时注释 RecordService 中的 watch 监听以避免潜在冲突
- 新增状态持久化功能(如 customerInfo 的本地存储)
1 parent 102cd697
...@@ -86,40 +86,40 @@ class RecordService { ...@@ -86,40 +86,40 @@ class RecordService {
initWatchers() { initWatchers() {
// 监听 customerKey // 监听 customerKey
this.unwatchCustomer = watch( // this.unwatchCustomer = watch(
(): string => storeState.customerKey, // (): string => storeState.customerKey,
(val: string) => { // (val: string) => {
const customerInfo = storeState.customerInfo // const customerInfo = storeState.customerInfo
this.handler('updateCustomerInfo', customerInfo, (val: UTSJSONObject | null) => { this.updateCustomerInfo(val) }, 1000) // this.handler('updateCustomerInfo', customerInfo, (val: UTSJSONObject | null) => { this.updateCustomerInfo(val) }, 1000)
}, // },
{ immediate: true } // { immediate: true }
) // )
// 监听 receptionStatus // // 监听 receptionStatus
this.unwatchStatus = watch( // this.unwatchStatus = watch(
(): string => storeState.receptionStatus, // (): string => storeState.receptionStatus,
(val: string) => { // (val: string) => {
this.handler('updateReceptionStatus', val, (v: any) => { this.updateReceptionStatus(v as string) }, 200) // this.handler('updateReceptionStatus', val, (v: any) => { this.updateReceptionStatus(v as string) }, 200)
}, // },
{ immediate: true } // { immediate: true }
) // )
this.unwatchBookList = watch( // this.unwatchBookList = watch(
(): UTSJSONObject[] => storeState.booksList, // (): UTSJSONObject[] => storeState.booksList,
(val: UTSJSONObject[]) => { // (val: UTSJSONObject[]) => {
this.handler('updateBookList', val, (v: UTSJSONObject[]) => { this.updateBookList(v) }, 1500) // this.handler('updateBookList', val, (v: UTSJSONObject[]) => { this.updateBookList(v) }, 1500)
}, // },
{ immediate: true } // { immediate: true }
) // )
this.unwatchReceptionKey = watch( // this.unwatchReceptionKey = watch(
(): string => storeState.receptionKey, // (): string => storeState.receptionKey,
(val: string) => { // (val: string) => {
const receptionTrack = storeState.receptionTrack // const receptionTrack = storeState.receptionTrack
this.handler('updateMaterialPointList', receptionTrack, (v: UTSJSONObject[]) => { this.updateMaterialPointList(v) }, 1000) // this.handler('updateMaterialPointList', receptionTrack, (v: UTSJSONObject[]) => { this.updateMaterialPointList(v) }, 1000)
}, // },
{ immediate: true } // { immediate: true }
) // )
} }
// --- 业务逻辑 --- // --- 业务逻辑 ---
...@@ -404,12 +404,12 @@ class RecordService { ...@@ -404,12 +404,12 @@ class RecordService {
businessScene: sceneType businessScene: sceneType
} }
const newPointJson = JSON.parse(JSON.stringify(newPoint)) as UTSJSONObject const newPointJson = JSON.parse(JSON.stringify(newPoint)) as UTSJSONObject
const pMap = point.toMap() const pMap = point.toMap()
pMap.forEach((pv, pk) => { pMap.forEach((pv, pk) => {
newPointJson[pk] = pv newPointJson[pk] = pv
}) })
receptionCustomerMaterialPointList.push(newPointJson) receptionCustomerMaterialPointList.push(newPointJson)
}) })
......
import { reactive } from 'vue'
import {
ReceptionState,
receptionState,
setCustomerKey,
setCustomerInfo,
setReceptionStatus,
setBookList,
setReceptionKey,
setReceptionTrack
} from './modules/reception.uts'
/** /**
* 全局状态管理 * Vuex 风格 Store(uni-app x 专用模块方案)
* 支持模块化拆分,同时兼容 Vuex 风格 API * 与旧项目 gl_tape/store 用法兼容,便于迁移
* 参考:https://doc.dcloud.net.cn/uni-app-x/tutorial/store.html
*/ */
import { reactive } from 'vue'
import { storage } from '@/utils/storage.uts'
// ============ 默认值 ============
const _emptyArr: any[] = [] as any[]
const defaultCustomerInfo = {
customerName: '',
carBrand: '',
carModel: '',
phoneNumber: '',
salesUuid: '',
staffName: '',
newCarFare: '',
carModelId: '',
carBuyers: '',
carPurchaseMethod: '',
oneCarBrand: '',
oneCarBrandId: ''
}
function parseCustomerInfo(raw: any): UTSJSONObject {
if (raw == null) return defaultCustomerInfo as UTSJSONObject
if (typeof raw == 'string') {
if (raw == '') return defaultCustomerInfo as UTSJSONObject
try {
const parsed = JSON.parse(raw) as UTSJSONObject
return { ...defaultCustomerInfo, ...parsed } as UTSJSONObject
} catch (_) {
return defaultCustomerInfo as UTSJSONObject
}
}
return { ...defaultCustomerInfo, ...(raw as UTSJSONObject) } as UTSJSONObject
}
// ============ State 类型 ============
export type UserState = {
customerInfo: UTSJSONObject
historyStatus: number
carBrands: any
employeeList: any
paymentType: any
haveCustomerAccess: boolean
boutiqueMediaConfig: Record<string, any>
receptionTrack: Record<string, any>
boutiqueDefaultCarBrandId: string
viewKey: number
boutiqueCarList: any
receptionKey: number
defaultCarId: string
customerKey: number
currentCarInfo: Record<string, any>
}
export type AudioInfo = {
audioStatus: string
endReasonType: number
receptionStartTime: string
receptionEndTime: string
}
export type AudioState = {
booksList: any
audioList: any
receptionStatus: any
endReasonType: number
perRecordNumber: any
audioInfo: AudioInfo
}
export type SysState = {
isInBackgound: boolean
activityWindowPopStatus: any
}
export type PointState = {
tabIndex: any
}
export type BoutiqueState = {
baseConfigData: UTSJSONObject
}
export type UpdateState = {
status: boolean
}
type ReceptionTrackPayload = { key: string; value: any }
// 1. 定义全局 State 结构
export type RootState = { export type RootState = {
// 扁平化映射 (为了兼容旧代码) user: UserState
customerKey: string audio: AudioState
customerInfo: UTSJSONObject | null sys: SysState
receptionStatus: string point: PointState
booksList: UTSJSONObject[] boutique: BoutiqueState
receptionKey: string update: UpdateState
receptionTrack: UTSJSONObject[]
// 模块化结构 (推荐新代码使用)
// reception: ReceptionState
}
// 2. 组合 State
// 使用 Class + Getter 实现扁平化访问和模块化
export class GlobalState {
get customerKey(): string { return receptionState.customerKey }
get customerInfo(): UTSJSONObject | null { return receptionState.customerInfo }
get receptionStatus(): string { return receptionState.receptionStatus }
get booksList(): UTSJSONObject[] { return receptionState.booksList }
get receptionKey(): string { return receptionState.receptionKey }
get receptionTrack(): UTSJSONObject[] { return receptionState.receptionTrack }
// 模块化访问入口
get reception(): ReceptionState { return receptionState }
}
export const state = new GlobalState()
// 3. 统一 Commit 分发
export const commit = (type: string, payload: any | null) => {
switch (type) {
// --- Reception Module ---
case 'updateCustomerKey':
setCustomerKey(payload as string)
break
case 'updateCustomerInfo':
setCustomerInfo(payload as UTSJSONObject | null)
break
case 'updateReceptionStatus':
setReceptionStatus(payload as string)
break
case 'updateBookList':
setBookList(payload as UTSJSONObject[])
break
case 'updateReceptionKey':
setReceptionKey(payload as string)
break
case 'updateReceptionTrack':
setReceptionTrack(payload as UTSJSONObject[])
break
default:
console.warn(`[Store] Unknown mutation type: ${type}`)
}
}
// 4. 导出 Store 对象
export default {
state,
commit
} }
// ============ 初始化 State ============
const savedCustomerInfo = storage.get('customerInfo')
const initialCustomerInfo = parseCustomerInfo(savedCustomerInfo as any)
export const state = reactive({
user: {
customerInfo: initialCustomerInfo,
historyStatus: Date.now() as number,
carBrands: [] as any[],
employeeList: [] as any[],
paymentType: [] as any[],
haveCustomerAccess: true,
boutiqueMediaConfig: {} as Record<string, any>,
receptionTrack: {} as Record<string, any>,
boutiqueDefaultCarBrandId: '',
viewKey: Date.now() as number,
boutiqueCarList: [] as any[],
receptionKey: Date.now() as number,
defaultCarId: '',
customerKey: Date.now() as number,
currentCarInfo: {} as Record<string, any>
} as UserState,
audio: {
booksList: [] as any[],
audioList: [] as any[],
receptionStatus: '',
endReasonType: 0,
perRecordNumber: 0,
audioInfo: {
audioStatus: '',
endReasonType: 0,
receptionStartTime: '',
receptionEndTime: ''
}
} as AudioState,
sys: {
isInBackgound: false,
activityWindowPopStatus: 0
} as SysState,
point: {
tabIndex: 0
} as PointState,
boutique: {
baseConfigData: {} as UTSJSONObject
} as BoutiqueState,
update: {
status: false
} as UpdateState
} as RootState)
// ============ Getters ============
// UTS 不支持对象字面量中的 get 语法,改用函数包装;属性访问用中括号;返回值 as any 避免 Any? 不匹配
function _getToken(): any { return (state.user as UTSJSONObject)['token'] as any }
function _getSiteData(): any {
const site = (state as UTSJSONObject)['site']
return (site != null ? (site as UTSJSONObject)['siteData'] : null) as any
}
function _getUserData(): any { return (state.user as UTSJSONObject)['userData'] as any }
function _getUserId(): any {
const ud = (state.user as UTSJSONObject)['userData']
return (ud != null ? (ud as UTSJSONObject)['id'] : null) as any
}
function _getIsInBackgound(): boolean { return state.sys.isInBackgound }
function _getCustomerInfo(): UTSJSONObject { return state.user.customerInfo }
function _getReceptionTrack(): Record<string, any> { return state.user.receptionTrack }
function _getReceptionStatus(): any { return state.audio.receptionStatus }
function _getBooksList(): any { return state.audio.booksList }
function _getReceptionKey(): number { return state.user.receptionKey }
function _getCustomerKey(): number { return state.user.customerKey }
function _getActivityWindowPopStatus(): any { return state.sys.activityWindowPopStatus }
export const getters = {
token: (): any => _getToken(),
siteData: (): any => _getSiteData(),
userData: (): any => _getUserData(),
userId: (): any => _getUserId(),
isInBackgound: (): boolean => _getIsInBackgound(),
customerInfo: (): UTSJSONObject => _getCustomerInfo(),
receptionTrack: (): Record<string, any> => _getReceptionTrack(),
receptionStatus: (): any => _getReceptionStatus(),
booksList: (): any => _getBooksList(),
receptionKey: (): number => _getReceptionKey(),
customerKey: (): number => _getCustomerKey(),
activityWindowPopStatus: (): any => _getActivityWindowPopStatus()
} as UTSJSONObject
// ============ Actions(兼容旧项目 dispatch) ============
export function dispatch(actionName: string, payload: any = ({} as any)): any {
const s = state
// user
if (actionName == 'setCustomerInfo') {
const data = (payload != null ? payload : {}) as UTSJSONObject
storage.set('customerInfo', JSON.stringify(data), 0)
s.user.customerInfo = { ...defaultCustomerInfo, ...data } as UTSJSONObject
s.user.customerKey = Date.now()
return null as any
}
if (actionName == 'clearCustomerInfo') {
storage.set('customerInfo', JSON.stringify(defaultCustomerInfo), 0)
s.user.customerInfo = { ...defaultCustomerInfo } as UTSJSONObject
s.user.customerKey = Date.now()
return null as any
}
if (actionName == 'clearHistory') {
s.user.historyStatus = Date.now()
return null as any
}
if (actionName == 'setPaymentType') {
s.user.paymentType = payload != null ? payload : _emptyArr
return null as any
}
if (actionName == 'setCarBrandsList') {
s.user.carBrands = payload != null ? payload : _emptyArr
return null as any
}
if (actionName == 'setEmployeeList') {
s.user.employeeList = payload != null ? payload : _emptyArr
return null as any
}
if (actionName == 'setReceptionTrack') {
const p = payload as ReceptionTrackPayload
if (p != null && p.key != null) {
s.user.receptionTrack[p.key] = p.value
}
s.user.receptionKey = Date.now()
return null as any
}
if (actionName == 'clearReceptionTrack') {
s.user.receptionTrack = {} as Record<string, any>
s.user.receptionKey = Date.now()
return null as any
}
if (actionName == 'updateViewKey') {
s.user.viewKey = Date.now()
return null as any
}
if (actionName == 'setCurrentCarInfo') {
s.user.currentCarInfo = (payload != null ? payload : {}) as Record<string, any>
return null as any
}
if (actionName == 'getCustomerInfo') {
return s.user.customerInfo
}
// audio
if (actionName == 'setReceptionStatus') {
s.audio.receptionStatus = payload != null ? payload : ''
return null as any
}
if (actionName == 'setBooks') {
s.audio.booksList = payload != null ? payload : _emptyArr
return null as any
}
if (actionName == 'setPerRecordNumber') {
s.audio.perRecordNumber = payload != null ? payload : 0
return null as any
}
if (actionName == 'setAudioList') {
s.audio.audioList = payload != null ? payload : _emptyArr
return null as any
}
if (actionName == 'setAudioInfo') {
const data = (payload != null ? payload : {}) as UTSJSONObject
if ((data['audioStatus'] as string) == 'start') {
data['receptionStartTime'] = formatDateTime(new Date(), '/')
data['receptionEndTime'] = ''
}
if ((data['audioStatus'] as string) == 'end') {
data['receptionEndTime'] = formatDateTime(new Date(), '/')
}
s.audio.audioInfo = { ...s.audio.audioInfo, ...data } as AudioInfo
return null as any
}
// sys
if (actionName == 'setBackgroundState') {
s.sys.isInBackgound = payload != null && payload != false
return null as any
}
if (actionName == 'setActivityWindowPopCount') {
s.sys.activityWindowPopStatus = payload != null ? payload : 0
return null as any
}
// point
if (actionName == 'setTab') {
s.point.tabIndex = payload != null ? payload : 0
return null as any
}
// update
if (actionName == 'openUpdateModal') {
s.update.status = true
return null as any
}
// boutique
if (actionName == 'setBoutiqueBaseConfig') {
s.boutique.baseConfigData = (payload != null ? payload : {}) as UTSJSONObject
return ({} as any)
}
return null as any
}
function formatDateTime(d: Date, sep: string): string {
const y = d.getFullYear()
const m = ('0' + (d.getMonth() + 1)).slice(-2)
const day = ('0' + d.getDate()).slice(-2)
const h = ('0' + d.getHours()).slice(-2)
const min = ('0' + d.getMinutes()).slice(-2)
const s = ('0' + d.getSeconds()).slice(-2)
return `${y}${sep}${m}${sep}${day} ${h}:${min}:${s}`
}
/** commit:兼容 mapMutations,内部转调 dispatch */
export function commit(type: string, payload?: any): void {
// 支持命名空间 audio/setReceptionStatus -> setReceptionStatus
const name = type.includes('/') ? type.split('/')[1] : type
dispatch(name, payload != null ? payload : ({} as any))
}
// ============ Store 对象(兼容 this.$store) ============
export const store = {
state: state,
getters: getters,
dispatch: (actionName: string, payload?: any): any => dispatch(actionName, payload != null ? payload : ({} as any)),
commit: (type: string, payload?: any): void => commit(type, payload)
}
export default store
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!