import { DateFormat, IBestToast, userInfo, UserInfo, YTAvoid, YTDateUtil, yTRouter } from "basic" import { BabyFoodApi } from "../Apis/BabyFoodApi" import { routerUtils } from "../utils/RouterUtils" import { AppStorageV2 } from "@kit.ArkUI" import { AddRecipeEventData, BabyInfo, Cuisine, DayPlan, PurchaseList, WeeklyPlan, WeeklyPlanPurchaseList } from "../model/Index" import { emitter } from "@kit.BasicServicesKit" import { EventConstant } from "../model/Constant" @ObservedV2 export class MainViewModel{ @Trace safeTop: number = 0 @Trace babyList: BabyInfo[] = [] // 当前选择的宝宝信息 @Trace selectedBabyIndex: number = -1 // 当前的宝宝信息 @Trace babyInfo: BabyInfo = AppStorageV2.connect(BabyInfo, () => new BabyInfo())! // 用户信息 @Trace userInfo: UserInfo = AppStorageV2.connect(UserInfo, 'UserInfo', () => userInfo)! // 菜品下拉菜单 @Trace dishList: Cuisine[] = [] // 本周的食谱计划 @Trace allPlan: WeeklyPlan = {} // 本周的食谱详情 @Trace planList?: WeeklyPlanPurchaseList // 本周的采购清单 @Trace purchaseList?: PurchaseList[] // 一周 week: string[] = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'] // 钩子函数列表 eventFunc: Array<() => void> = [] constructor() { this.safeTop = AppStorage.get(YTAvoid.SAFE_TOP_KEY) as number // emitter.on(EventConstant.ADD_RECIPE_TO_WEEKLY_PLAN, (ans) => { this.addRecipeEvent(ans.data as AddRecipeEventData) }) } // 登录状态改变 async LoginStatusChange(){ this.userInfo.setUserInfoAndLogin(userInfo, false) if(this.userInfo.checkLogin()){ await this.getBabyList() await this.getDishList() } else { this.clearDataSource(true) } } // 登录校验 - 宝宝信息校验 checkLogin(f: () => void, isCheckBaby: boolean = false) { if(this.userInfo.checkLogin()) { if(this.babyInfo?.id || !isCheckBaby){ f() } else { IBestToast.show('请先添加宝宝信息吧!') this.increaseBabyInfo() } } else { yTRouter.router2LoginPage(true) } } // 修改选中的宝宝信息 async updateBabyInfo(index: number) { if(index == this.selectedBabyIndex) return this.clearDataSource() BabyInfo.override(this.babyInfo, this.babyList[index]) this.selectedBabyIndex = index await this.getWeeklyPlan() await this.getWeeklyPurchaseList() this.eventFunc.forEach(f => f()) } // 添加事件 - addEvent(f: () => void) { this.eventFunc.push(f) f() } // 返回菜品信息 getCuisineInfo(id: number): Cuisine { let index = this.dishList.findIndex(item => item.id === id) return this.dishList[index] } // 清空数据源 clearDataSource(isLoginOut: boolean = false) { this.allPlan = {} this.planList = {} this.purchaseList = [] if(isLoginOut){ BabyInfo.override(this.babyInfo) this.babyList = [] } } // 返回对应天数的菜谱计划 getDayPlan(week: number | string): DayPlan { let switchFlag: string = '' if(typeof week === 'string') { switchFlag = week } else { switchFlag = this.week[week] } if(!this.planList) this.planList = new WeeklyPlanPurchaseList() switch (switchFlag) { case '周一': if(this.planList.monday == undefined) this.planList.monday = new DayPlan() return this.planList.monday case '周二': if(this.planList.tuesday == undefined) this.planList.tuesday = new DayPlan() return this.planList.tuesday case '周三': if(this.planList.wednesday == undefined) this.planList.wednesday = new DayPlan() return this.planList.wednesday case '周四': if(this.planList.thursday == undefined) this.planList.thursday = new DayPlan() return this.planList?.thursday case '周五': if(this.planList.friday == undefined) this.planList.friday = new DayPlan() return this.planList?.friday case '周六': if(this.planList.saturday == undefined) this.planList.saturday = new DayPlan() return this.planList?.saturday case '周日': if(this.planList.sunday == undefined) this.planList.sunday = new DayPlan() return this.planList?.sunday } return new DayPlan() } // 监听添加食谱事件 addRecipeEvent(data: AddRecipeEventData){ console.log(`监听添加食谱事件 data = ${JSON.stringify(data)}`) let week: number = Number.parseInt(data.week!) let meal: number = Number.parseInt(data.meal!) let dayPlan: DayPlan = this.getDayPlan(week) const cuisine: Cuisine = this.getCuisineInfo(data.recipe!.id!) if(meal == 0) { dayPlan.breakfast = cuisine } else if(meal == 1) { dayPlan.lunch = cuisine } else if(meal == 2) { dayPlan.dinner = cuisine } this.updateWeeklyPlan() } // 获取本周食谱计划 async getWeeklyPlan(startDate?: string){ try { if(!startDate) startDate = YTDateUtil.formatDate(new Date(), DateFormat.UNDERLINE) this.allPlan = await BabyFoodApi.getWeeklyPlan(this.babyInfo.id, startDate) this.planList = this.allPlan.weeklyPlan this.planList!.id = this.allPlan.id } catch (e){ console.log(`e = ${JSON.stringify(e)}`) } } // 更新本周食谱计划 async updateWeeklyPlan(isReload: boolean = true): Promise{ try { IBestToast.showLoading({message: "修改中"}) await BabyFoodApi.updateWeeklyPlan(WeeklyPlanPurchaseList.clone(this.planList!)) // 修改食谱清单后需刷新采购清单 this.getWeeklyPurchaseList() // 刷新数据源 if(isReload) this.getWeeklyPlan() return true } catch (e) { // 如果在更新食谱时发生错误,则刷新数据源 this.getWeeklyPlan() return false } finally { IBestToast.hide() } } // 获取本周所有采购清单 async getWeeklyPurchaseList(): Promise{ try { this.purchaseList = await BabyFoodApi.getWeeklyPurchaseList(this.babyInfo.id!) } catch (e) { console.log(`e = ${JSON.stringify(e)}`) } } // 获取菜品列表 async getDishList(){ try { this.dishList = await BabyFoodApi.getDishList() } catch (e){ console.log(`e = ${JSON.stringify(e)}`) } } // 获取宝宝信息列表 async getBabyList(){ try { this.babyList = await BabyFoodApi.getBabyList() let index = this.babyList.findIndex(item => item.id === this.babyInfo.id) if(index != -1) { this.updateBabyInfo(index) } else { if(this.babyList.length > 0) { this.updateBabyInfo(0) } else { this.clearDataSource() } } } catch (e) { console.log(`e = ${JSON.stringify(e)}`) } } // 修改购买状态 - 清单 id async updateBuyStatus(Id: number, index: number){ try { let ans = await BabyFoodApi.updatePurchaseStatus(Id) let l = this.purchaseList![index] l.purchased = l.purchased == '1' ? '0' : '1' this.purchaseList?.splice(index, 1, l) } catch (e) { console.log(`e = ${JSON.stringify(e)}`) } } // 进入添加宝宝信息页面 increaseBabyInfo(){ routerUtils.router2IncreaseBabyInfo((res) => { this.getBabyList() }) } // 跳转至采购详情页 goToPurchaseDetail() { routerUtils.router2PurchasingPage((res) => { this.getWeeklyPurchaseList() }) } // 进入编辑宝宝信息页面 editBabyInfo() { routerUtils.router2BabyInfoPage((res) => { this.getBabyList() }) } /** * 重写的返回逻辑 * @returns */ _onBackPressed(){ yTRouter.pop('') return true; } }