ソースを参照

feat: 完成添加食谱计划的部分交互逻辑, 和修复了相关的部分BUG

YuJing 1 ヶ月 前
コミット
6cba544c22

+ 1 - 1
features/feature/src/main/ets/Apis/BabyFoodApi.ets

@@ -5,7 +5,7 @@ import { ApiUrl } from './ApiUrl'
 export class BabyFoodApi{
   // 获取所有食谱列表
   static getAllRecipes(keyword?: string, monthRange?: string): Promise<Recipe[]> {
-    return YTRequest.get(ApiUrl.getAllRecipes, {keyword, monthRange})
+    return YTRequest.get<Recipe[]>(ApiUrl.getAllRecipes, {keyword, monthRange})
   }
 
   // 获取食物详情信息

+ 125 - 0
features/feature/src/main/ets/components/RecipeComp.ets

@@ -0,0 +1,125 @@
+import { IBestToast, yTRouter } from "basic"
+import { DiaLogPageEnum, DiaLogParam, YTDiaLogModel } from "basic/src/main/ets/models/YTDiaLogModel"
+import { BabyInfo, Recipe } from "../model/Index"
+import { AppStorageV2 } from "@kit.ArkUI"
+import { routerUtils } from "../utils/RouterUtils"
+import { emitter } from "@kit.BasicServicesKit"
+import { EventConstant } from "../model/Constant"
+
+@ComponentV2
+export struct RecipeComp {
+  @Require @Param recipe: Recipe[] = []
+  // 当前的宝宝信息
+  @Local babyInfo: BabyInfo = AppStorageV2.connect<BabyInfo>(BabyInfo, () => new BabyInfo())!
+
+  // 展开食谱弹窗
+  async expandRecipe(item: Recipe){
+    item.ingredients = ['南瓜100g', '高铁面粉100g', '高铁面粉100g']
+    item.steps = ['1. 南瓜去皮去籽,切成小块', '2. 上锅蒸15分钟至软烂', '3. 用勺子压成泥状', '4.米粉用温水调成糊状', '5.将南瓜泥与米粉混合均匀']
+    item.description = '富含β-胡萝卜素和膳食纤维,\n' +
+      '有助于宝宝视力发展和消化\n' +
+      '系统健康'
+
+    let param: DiaLogParam = {
+      pageEnum: DiaLogPageEnum.RecipePopup,
+      align: YTDiaLogModel.Center,
+      param: {
+        generics: item,
+      }
+    }
+    yTRouter.router2NaviDiaLog(param, (res) => {
+      setTimeout(() => {
+        this.addToPlan(item)
+      }, 200)
+    })
+  }
+
+  // 打开 添加至食谱计划弹窗
+  async addToPlan(item: Recipe){
+    let param: DiaLogParam = {
+      pageEnum: DiaLogPageEnum.AddToRecipe,
+      align: YTDiaLogModel.Center,
+      param: {
+        generics: item,
+      }
+    }
+    yTRouter.router2NaviDiaLog(param, (res) => {
+      /**
+       * 0-1 周一 - 早餐
+       * 1-2 周二 - 午餐
+       * 2-3 周三 - 晚餐
+       */
+      let ans = res.result as string
+
+      if(!this.babyInfo.id) {
+        IBestToast.show('请先添加宝宝信息')
+        return routerUtils.router2IncreaseBabyInfo(() => {
+          this.addToPlanEvent(item, ans)
+        })
+      }
+      this.addToPlanEvent(item, ans)
+    })
+  }
+
+  // 触发添加至计划 事件
+  addToPlanEvent(item: Recipe, ans: string){
+    emitter.emit(EventConstant.ADD_RECIPE_TO_WEEKLY_PLAN, { data: {
+      recipe: item,
+      week: ans.split('-')[0],
+      meal: ans.split('-')[1]
+    } })
+  }
+
+  build() {
+    Column() {
+      Grid(){
+        ForEach(this.recipe, (item: Recipe, index) => {
+          GridItem(){
+            this.RecipeBuilder(item)
+          }
+        })
+      }
+      .rowsGap(12)
+      .width("100%")
+      .height("100%")
+      .scrollBar(BarState.Off)
+      .columnsTemplate("1fr 1fr")
+      .padding({ bottom: 25 })
+    }
+    .width("100%")
+    .height("100%")
+  }
+
+
+  @Builder RecipeBuilder(item: Recipe){
+    Column({space: 10}){
+      Image(item.imageUrl)
+        .width('100%')
+        .height(112)
+        .borderRadius({topLeft: 8, topRight: 8})
+
+      Column({space: 4}){
+        Text(item.name)
+          .fontSize(12)
+          .fontWeight(400)
+
+        Text(item.monthRange)
+          .fontSize(10)
+          .borderRadius(10)
+          .fontColor('#F0A040')
+          .backgroundColor('#F8F0E6')
+          .padding({left: 10, right: 10, top: 5, bottom: 5})
+      }
+      .width("100%")
+      .alignItems(HorizontalAlign.Start)
+      .padding({left: 12, right: 10, bottom: 8, top: 8})
+    }
+    .width(154)
+    .borderRadius(8)
+    .backgroundColor(Color.White)
+    .shadow({
+      radius: 15, type: ShadowType.COLOR, color: 'rgba(0, 0, 0, 0.1)', offsetY: 4
+    })
+    .onClick(() => { this.expandRecipe(item) })
+  }
+}

+ 5 - 5
features/feature/src/main/ets/components/YTDiaLogBuild.ets

@@ -465,7 +465,7 @@ struct AddPlanComp{
   @Monitor('week', 'meal')
   checkAns(){
     if(this.week != -1 && this.meal != -1) {
-      this.onBack('得嘞')
+      this.onBack(`${this.week}-${this.meal}`)
     }
   }
 
@@ -538,13 +538,13 @@ struct AddPlanComp{
       }
       .width("100%")
       .layoutWeight(1)
-      .padding({ left: 16, right: 16, top: 12 })
-      .alignItems(HorizontalAlign.Start)
-      .justifyContent(FlexAlign.Center)
+      .padding({ left: 16, right: 16, top: 12})
+      .alignItems(HorizontalAlign.Center)
+      .justifyContent(FlexAlign.Start)
       .borderRadius({bottomLeft: 8, bottomRight: 8})
     }
     .width(320)
-    .height(288)
+    .height(270)
     .borderRadius(8)
     .backgroundColor(Color.White)
   }

+ 2 - 1
features/feature/src/main/ets/components/bigwheel/BigWheelView.ets

@@ -233,8 +233,9 @@ export struct BigWheelView{
       this.context.beginPath()
       this.context.moveTo(centerX, centerY)
       this.context.lineTo(endX, endY)
-      this.context.strokeStyle = '#efd4f9' // 红色半径线
+      this.context.strokeStyle = '#D6E8A2' // 红色半径线
       this.context.lineWidth = 1.5
+      this.context.setLineDash([5, 5])
       this.context.stroke()
     })
 

+ 4 - 0
features/feature/src/main/ets/model/Constant.ets

@@ -0,0 +1,4 @@
+export class EventConstant{
+  // 添加食谱至食谱周计划中
+  static readonly ADD_RECIPE_TO_WEEKLY_PLAN: string = "ADD_RECIPE_TO_WEEKLY_PLAN";
+}

+ 29 - 8
features/feature/src/main/ets/model/Index.ets

@@ -1,6 +1,6 @@
 // 食谱
 export class Recipe {
-  id?: string;
+  id?: number;
   name?: string;
   description?: string;
   cookingTime?: number;
@@ -114,15 +114,16 @@ export class DayPlan {
 }
 
 // 周计划食材清单
+@ObservedV2
 export class WeeklyPlanPurchaseList {
   id?: number;
-  friday?: DayPlan
-  monday?: DayPlan
-  saturday?: DayPlan
-  sunday?: DayPlan
-  thursday?: DayPlan
-  tuesday?: DayPlan
-  wednesday?: DayPlan
+  @Trace friday?: DayPlan
+  @Trace monday?: DayPlan
+  @Trace saturday?: DayPlan
+  @Trace sunday?: DayPlan
+  @Trace thursday?: DayPlan
+  @Trace tuesday?: DayPlan
+  @Trace wednesday?: DayPlan
 
   constructor() {
     this.friday = new DayPlan();
@@ -133,4 +134,24 @@ export class WeeklyPlanPurchaseList {
     this.tuesday = new DayPlan();
     this.wednesday = new DayPlan();
   }
+
+  static clone(plan: WeeklyPlanPurchaseList){
+    return {
+      friday: plan.friday,
+      monday: plan.monday,
+      saturday: plan.saturday,
+      sunday: plan.sunday,
+      thursday: plan.thursday,
+      tuesday: plan.tuesday,
+      wednesday: plan.wednesday,
+      id: plan.id,
+    } as WeeklyPlanPurchaseList
+  }
+}
+
+// 触发添加食谱事件数据结构
+export class AddRecipeEventData {
+  week?: string
+  meal?: string
+  recipe?: Recipe
 }

+ 2 - 1
features/feature/src/main/ets/model/Persistence.ets

@@ -1,3 +1,4 @@
+@ObservedV2
 export class RecipSearch{
-  searchList: string[] = []
+  @Trace searchList: string[] = []
 }

+ 52 - 59
features/feature/src/main/ets/pages/RecipeSearchPage.ets

@@ -1,7 +1,8 @@
 import { yTRouter } from 'basic'
 import { LengthMetrics } from '@kit.ArkUI'
 import { RecipeSearchViewModel } from '../viewModel/RecipeSearchViewModel'
-import { Cuisine } from '../model/Index'
+import { Cuisine, Recipe } from '../model/Index'
+import { RecipeComp } from '../components/RecipeComp'
 
 
 @ComponentV2
@@ -15,77 +16,68 @@ struct RecipeSearchPage{
     NavDestination(){
       Column(){
         // Title
-        Row(){
+        Row({space: 21}){
+          // 返回按钮
           Image($r("app.media.back"))
             .width(20)
             .aspectRatio(1)
             .onClick(() => {
               yTRouter.pop()
             })
-        }
-        .width('100%')
-        .alignItems(VerticalAlign.Top)
-        .justifyContent(FlexAlign.Start)
-        .padding({top: 10, bottom: 10})
-
-        // 搜索框
-        Row({space: 15}){
-          Image($r("app.media.Search"))
-            .width(18)
-            .aspectRatio(1)
 
-          TextInput({ placeholder: "输入日记标题", text: $$this.vm.keyWord })
-            .padding(0)
-            .fontSize(16)
-            .layoutWeight(1)
-            .borderRadius(0)
-            .placeholderColor('#ff777272')
-            .placeholderFont({ size: 16 })
-            .backgroundColor(Color.Transparent)
-            .caretColor('app.color.main_ac_color_dark')
-            .onSubmit(()=>{ this.vm.onSearch() })
-
-
-          if(this.vm.keyWord.length > 0) {
-            Image($r('app.media.Diary_close'))
-              .width(25)
-              // .padding(5)
+          // 搜索框
+          Row({space: 15}){
+            Image($r("app.media.Search"))
+              .width(18)
               .aspectRatio(1)
-              .borderRadius(15)
-              .onClick(() => { this.vm.clearKeyWord() })
-          }
 
-          Text("确认")
-            .borderRadius(32)
-            .linearGradient(this.vm.linearInfo)
-            .padding({ left: 17, top: 5.5, right: 17, bottom: 5.5 })
-            .onClick(() => { this.vm.onSearch() })
+            TextInput({ placeholder: "开始搜索吧", text: $$this.vm.keyWord })
+              .padding(0)
+              .fontSize(16)
+              .layoutWeight(1)
+              .borderRadius(0)
+              .placeholderColor('#ff777272')
+              .placeholderFont({ size: 16 })
+              .backgroundColor(Color.Transparent)
+              .caretColor('app.color.main_ac_color_dark')
+              .onSubmit(()=>{ this.vm.onSearch() })
+
+
+            if(this.vm.keyWord.length > 0) {
+              Image($r('app.media.Diary_close'))
+                .width(25)
+                // .padding(5)
+                .aspectRatio(1)
+                .borderRadius(15)
+                .onClick(() => { this.vm.clearKeyWord() })
+            }
 
+            Text("确认")
+              .borderRadius(32)
+              .linearGradient(this.vm.linearInfo)
+              .padding({ left: 17, top: 5.5, right: 17, bottom: 5.5 })
+              .onClick(() => { this.vm.onSearch() })
+
+          }
+          .layoutWeight(1)
+          .borderRadius(30)
+          .backgroundColor(Color.White)
+          .alignItems(VerticalAlign.Center)
+          .padding({left: 16, right: 16, top: 8, bottom: 8})
         }
-        .width("100%")
+        .width('100%')
         .alignItems(VerticalAlign.Center)
-        .border({ width: { bottom: 1 } })
-        .padding({ bottom: 21, top: 13 })
+        .justifyContent(FlexAlign.SpaceBetween)
+        .padding({top: 10, bottom: 20})
+
 
         // 历史记录
         Column({space: 15}){
           if(this.vm.searchList.length !== 0) {
             Column(){
-              List(){
-                ForEach(this.vm.searchList, (item: Cuisine, i: number) => {
-                  ListItem() {
-                    // DiaryTitleItem({
-                    //   title: item.title,
-                    //   onClickBack: () => {
-                    //     this.routerDiaryPage(item.id)
-                    //   }
-                    // })
-                  }
-                }, (item: Cuisine) => item.id?.toString())
-              }
-              .width("100%")
-              .height("100%")
-              .scrollBar(BarState.Off)
+              // 食谱列表
+              RecipeComp({ recipe: this.vm.searchList })
+                .height("100%")
             }
             .width("100%")
             .layoutWeight(1)
@@ -117,10 +109,11 @@ struct RecipeSearchPage{
         }
         .width("100%")
         .layoutWeight(1)
-        .padding({ top: 35 })
       }
+      .backgroundColor('#F7F9FA')
       .padding({ top: this.vm.safeTop, left: 24, right: 24 })
     }
+    .hideTitleBar(true)
   }
 
   // 搜索记录关键字
@@ -138,7 +131,7 @@ struct RecipeSearchPage{
       }
     }
     .borderRadius(8)
-    .backgroundColor("#F7F7F7")
+    .backgroundColor("#ffffff")
     .padding({top: 8, bottom: 8, left: 25, right: this.vm.delModel ? 5 : 25})
     .onClick(() => {
       if(this.vm.delModel) {
@@ -166,8 +159,8 @@ struct RecipeSearchPage{
             .fontColor('#ff625a5a')
         } else {
           Image($r('app.media.del'))
-            .width(20)
-            .height(30)
+            .width(30)
+            .height(50)
         }
       }
       .onClick(() => {

+ 0 - 0
features/feature/src/main/ets/utils/Index.ets


+ 17 - 0
features/feature/src/main/ets/utils/RouterUtils.ets

@@ -1,17 +1,34 @@
 import { yTRouter } from "basic";
 
 class RouterUtils{
+  /**
+   * 添加宝宝信息页面
+   * @param back
+   */
   router2IncreaseBabyInfo(back?: Callback<PopInfo>){
     yTRouter.pushPathByName('IncreaseBabyInfo', null, back, true)
   }
 
+  /**
+   * 采购详情页
+   * @param back
+   */
   router2PurchasingPage(back?: Callback<PopInfo>){
     yTRouter.pushPathByName('PurchasingPage', null, back, true)
   }
 
+  /**
+   * 编辑宝宝信息页面
+   * @param back
+   */
   router2BabyInfoPage(back?: Callback<PopInfo>){
     yTRouter.pushPathByName('BabyInfoPage', null, back, true)
   }
+
+  /**
+   * 搜索食谱页面
+   * @param back
+   */
   router2RecipeSearchPage(back?: Callback<PopInfo>){
     yTRouter.pushPathByName('RecipeSearchPage', null, back, true)
   }

+ 26 - 56
features/feature/src/main/ets/view/MainView.ets

@@ -1,7 +1,7 @@
 import { ytBuildComp } from "../components/ytBuildComp"
 import { MainViewModel } from "../viewModel/MainViewModel"
 import { emitter } from "@kit.BasicServicesKit"
-import { BasicType, EmitterKeyCollection } from "basic"
+import { BasicType, EmitterKeyCollection, IBestToast } from "basic"
 import { BabyInfo, Cuisine, DayPlan } from "../model/Index"
 
 @ComponentV2
@@ -128,7 +128,7 @@ export struct MainView {
                 }
                 .padding(5)
                 .width(320)
-              })
+              }, (item: string, index: number) => JSON.stringify(this.vm.getDayPlan(item)) + item)
             }
             .width('100%')
             .loop(false)
@@ -236,6 +236,11 @@ export struct MainView {
       .height('100%')
       .backgroundColor('#F7F9FA')
       .padding({ top: this.vm.safeTop + 12})
+      .onVisibleAreaChange([0, 1], (e, r) => {
+        if(e && r == 1){
+          this.vm.LoginStatusChange()
+        }
+      })
     }
   }
 
@@ -297,47 +302,6 @@ struct RecipeWidget{
     }
   ]
 
-  getToDayPlan(needReload: boolean = true){
-    switch (this.week) {
-      case '周一':
-        if(needReload){
-          this.toDayPlan = new DayPlan(this.vm.planList?.monday)
-        }
-        return this.vm.planList?.monday
-      case '周二':
-        if(needReload){
-          this.toDayPlan = new DayPlan(this.vm.planList?.tuesday)
-        }
-          return this.vm.planList?.tuesday
-      case '周三':
-        if(needReload){
-          this.toDayPlan = new DayPlan(this.vm.planList?.wednesday)
-        }
-        return this.vm.planList?.wednesday
-      case '周四':
-        if(needReload){
-          this.toDayPlan = new DayPlan(this.vm.planList?.thursday)
-        }
-        return this.vm.planList?.thursday
-      case '周五':
-        if(needReload){
-          this.toDayPlan = new DayPlan(this.vm.planList?.friday)
-        }
-        return this.vm.planList?.friday
-      case '周六':
-        if(needReload){
-          this.toDayPlan = new DayPlan(this.vm.planList?.sunday)
-        }
-        return this.vm.planList?.saturday
-      case '周日':
-        if(needReload){
-          this.toDayPlan = new DayPlan(this.vm.planList?.sunday)
-        }
-        return this.vm.planList?.sunday
-    }
-    return new DayPlan()
-  }
-
   // 返回对应的菜品
   getCuisine(text: string): Cuisine | undefined {
     if(text === '早餐') {
@@ -364,29 +328,35 @@ struct RecipeWidget{
   // 选中修改菜品
   updateCuisine(id: number){
     if(!this.toDayPlan) this.toDayPlan = new DayPlan()
-
-    let origin = this.getToDayPlan(false)
+    let origin: DayPlan = this.vm.getDayPlan(this.week)
     let cuisine: Cuisine | undefined = this.vm.getCuisineInfo(id)
     if(this.selectMeal == 0) {
-      this.toDayPlan.breakfast = cuisine
-      if(!origin?.breakfast) origin!.breakfast = new Cuisine()
-      origin!.breakfast = this.toDayPlan?.breakfast
+      // this.toDayPlan.breakfast = cuisine
+      origin.breakfast = cuisine
     } else if (this.selectMeal == 1) {
-      this.toDayPlan.lunch = cuisine
-      if(!origin?.lunch) origin!.lunch = new Cuisine()
-      origin!.lunch = this.toDayPlan?.lunch
+      // this.toDayPlan.lunch = cuisine
+      origin.lunch = cuisine
     } else if (this.selectMeal == 2) {
-      this.toDayPlan.dinner = cuisine
-      if(!origin?.dinner) origin!.dinner = new Cuisine()
-      origin!.dinner = this.toDayPlan?.dinner
+      // this.toDayPlan.dinner = cuisine
+      origin.dinner = cuisine
     }
 
-    this.vm.updateWeeklyPlan()
+    this.vm.updateWeeklyPlan(false).then(res => {
+      if(res) {
+        if(this.selectMeal == 0) {
+          this.toDayPlan!.breakfast = cuisine
+        } else if (this.selectMeal == 1) {
+          this.toDayPlan!.lunch = cuisine
+        } else if (this.selectMeal == 2) {
+          this.toDayPlan!.dinner = cuisine
+        }
+      }
+    })
   }
 
   aboutToAppear(): void {
     this.vm.addEvent(() => {
-      this.getToDayPlan()
+      this.toDayPlan = new DayPlan(this.vm.getDayPlan(this.week))
     })
   }
 

+ 3 - 44
features/feature/src/main/ets/view/SecondView.ets

@@ -1,5 +1,5 @@
+import { RecipeComp } from "../components/RecipeComp";
 import { ytBuildComp } from "../components/ytBuildComp";
-import { Recipe } from "../model/Index";
 import { SecondViewModel } from "../viewModel/SecondViewModel";
 
 @ComponentV2
@@ -56,19 +56,8 @@ export struct SecondView {
         .onClick(() => { this.vm.goToSearchPage() })
 
         // 食谱列表
-        Grid(){
-          ForEach(this.vm.recipe, (item: Recipe, index) => {
-            GridItem(){
-              this.RecipeBuilder(item)
-            }
-          })
-        }
-        .rowsGap(12)
-        .width("100%")
-        .layoutWeight(1)
-        .scrollBar(BarState.Off)
-        .columnsTemplate("1fr 1fr")
-        .padding({ bottom: 25 })
+        RecipeComp({ recipe: this.vm.recipe})
+          .layoutWeight(1)
       }
       .width('100%')
       .height('100%')
@@ -78,35 +67,5 @@ export struct SecondView {
     }
   }
 
-  @Builder RecipeBuilder(item: Recipe){
-    Column({space: 10}){
-      Image(item.imageUrl)
-        .width('100%')
-        .height(112)
-        .borderRadius({topLeft: 8, topRight: 8})
-
-      Column({space: 4}){
-        Text(item.name)
-          .fontSize(12)
-          .fontWeight(400)
 
-        Text(item.monthRange)
-          .fontSize(10)
-          .borderRadius(10)
-          .fontColor('#F0A040')
-          .backgroundColor('#F8F0E6')
-          .padding({left: 10, right: 10, top: 5, bottom: 5})
-      }
-      .width("100%")
-      .alignItems(HorizontalAlign.Start)
-      .padding({left: 12, right: 10, bottom: 8, top: 8})
-    }
-    .width(154)
-    .borderRadius(8)
-    .backgroundColor(Color.White)
-    .shadow({
-      radius: 15, type: ShadowType.COLOR, color: 'rgba(0, 0, 0, 0.1)', offsetY: 4
-    })
-    .onClick(() => { this.vm.expandRecipe(item) })
-  }
 }

+ 95 - 14
features/feature/src/main/ets/viewModel/MainViewModel.ets

@@ -2,7 +2,11 @@ import { DateFormat, IBestToast, userInfo, UserInfo, YTAvoid, YTDateUtil, yTRout
 import { BabyFoodApi } from "../Apis/BabyFoodApi"
 import { routerUtils } from "../utils/RouterUtils"
 import { AppStorageV2 } from "@kit.ArkUI"
-import { BabyInfo, Cuisine, DayPlan, PurchaseList, WeeklyPlan, WeeklyPlanPurchaseList } from "../model/Index"
+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{
@@ -30,6 +34,11 @@ export class MainViewModel{
 
   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)
+    })
   }
 
   // 登录状态改变
@@ -37,7 +46,6 @@ export class MainViewModel{
     this.userInfo.setUserInfoAndLogin(userInfo, false)
 
     if(this.userInfo.checkLogin()){
-      // 宝宝信息没有的话也没必要加载后续数据了
       await this.getBabyList()
       await this.getDishList()
     } else {
@@ -73,7 +81,7 @@ export class MainViewModel{
     this.eventFunc.forEach(f => f())
   }
 
-  // 添加事件
+  // 添加事件 -
   addEvent(f: () => void) {
     this.eventFunc.push(f)
     f()
@@ -97,6 +105,63 @@ export class MainViewModel{
     }
   }
 
+  // 返回对应天数的菜谱计划
+  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 {
@@ -110,20 +175,32 @@ export class MainViewModel{
   }
 
   // 更新本周食谱计划
-  async updateWeeklyPlan(): Promise<boolean>{
+  async updateWeeklyPlan(isReload: boolean = true): Promise<boolean>{
     try {
-      await BabyFoodApi.updateWeeklyPlan(this.planList!)
+      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<void>{
-    this.purchaseList = await BabyFoodApi.getWeeklyPurchaseList(this.babyInfo.id!)
+    try {
+      this.purchaseList = await BabyFoodApi.getWeeklyPurchaseList(this.babyInfo.id!)
+    } catch (e) {
+      console.log(`e = ${JSON.stringify(e)}`)
+    }
   }
 
   // 获取菜品列表
@@ -137,17 +214,21 @@ export class MainViewModel{
 
   // 获取宝宝信息列表
   async getBabyList(){
-    this.babyList = await BabyFoodApi.getBabyList()
-    let index = this.babyList.findIndex(item => item.id === this.babyInfo.id)
+    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)
+      if(index != -1) {
+        this.updateBabyInfo(index)
       } else {
-        this.clearDataSource()
+        if(this.babyList.length > 0) {
+          this.updateBabyInfo(0)
+        } else {
+          this.clearDataSource()
+        }
       }
+    } catch (e) {
+      console.log(`e = ${JSON.stringify(e)}`)
     }
   }
 

+ 9 - 6
features/feature/src/main/ets/viewModel/RecipeSearchViewModel.ets

@@ -1,17 +1,19 @@
-import { IBestToast, userInfo, UserInfo, YTAvoid } from "basic"
+import { IBestToast, userInfo, UserInfo, YTAvoid, yTRouter } from "basic"
 import { AppStorageV2, PersistenceV2 } from "@kit.ArkUI"
 import { RecipSearch } from "../model/Persistence"
-import { Cuisine } from "../model/Index"
+import { Cuisine, Recipe } from "../model/Index"
+import { BabyFoodApi } from "../Apis/BabyFoodApi"
+import { DiaLogPageEnum, DiaLogParam, YTDiaLogModel } from "basic/src/main/ets/models/YTDiaLogModel"
 
 @ObservedV2
 export class RecipeSearchViewModel{
   @Trace safeTop: number = 0
   @Trace delModel: boolean = false
-  @Trace historicalSearchRecords: RecipSearch = new RecipSearch()
   @Trace keyWord: string = ''
-  @Trace searchList: Cuisine[] = []
+  @Trace searchList: Recipe[] = []
   // 用户信息
   @Trace userInfo: UserInfo = AppStorageV2.connect<UserInfo>(UserInfo, 'UserInfo', () => userInfo)!
+  @Trace historicalSearchRecords: RecipSearch = PersistenceV2.connect(RecipSearch, `${this.userInfo.getId()}Tags`, () => new RecipSearch())!
 
   linearInfo: LinearGradientOptions = {
     colors: [ ['#B9FD2A', 0.01], ['#F5FD6D', 1] ],
@@ -20,9 +22,9 @@ export class RecipeSearchViewModel{
 
   constructor() {
     this.safeTop = AppStorage.get(YTAvoid.SAFE_TOP_KEY) as number;
-    this.historicalSearchRecords =  PersistenceV2.connect(RecipSearch, `${this.userInfo.getId()}Tags`, () => new RecipSearch())!
   }
 
+  // 点击开始搜索
   async onSearch(){
     if(!this.keyWord) {
       IBestToast.show('请输入搜索内容')
@@ -35,12 +37,13 @@ export class RecipeSearchViewModel{
     }
     this.historicalSearchRecords.searchList.unshift(this.keyWord)
 
-    // this.searchList = await DiaryViewModel.diaryLogSearch(this.keyWord)
+    this.searchList = await BabyFoodApi.getAllRecipes(this.keyWord)
     if(this.searchList.length === 0) {
       IBestToast.show('没有搜索结果')
     }
   }
 
+  // 删除搜索记录
   onDelSearch(index: number){
     this.historicalSearchRecords.searchList.splice(index, 1)
   }

+ 0 - 36
features/feature/src/main/ets/viewModel/SecondViewModel.ets

@@ -23,42 +23,6 @@ export class SecondViewModel{
     routerUtils.router2RecipeSearchPage()
   }
 
-  // 展开食谱弹窗
-  async expandRecipe(item: Recipe){
-    item.ingredients = ['南瓜100g', '高铁面粉100g', '高铁面粉100g']
-    item.steps = ['1. 南瓜去皮去籽,切成小块', '2. 上锅蒸15分钟至软烂', '3. 用勺子压成泥状', '4.米粉用温水调成糊状', '5.将南瓜泥与米粉混合均匀']
-    item.description = '富含β-胡萝卜素和膳食纤维,\n' +
-      '有助于宝宝视力发展和消化\n' +
-      '系统健康'
-
-    let param: DiaLogParam = {
-      pageEnum: DiaLogPageEnum.RecipePopup,
-      align: YTDiaLogModel.Center,
-      param: {
-        generics: item,
-      }
-    }
-    yTRouter.router2NaviDiaLog(param, (res) => {
-      setTimeout(() => {
-        this.addToPlan(item)
-      }, 200)
-    })
-  }
-
-  // 打开 添加至食谱计划弹窗
-  async addToPlan(item: Recipe){
-    let param: DiaLogParam = {
-      pageEnum: DiaLogPageEnum.AddToRecipe,
-      align: YTDiaLogModel.Center,
-      param: {
-        generics: item,
-      }
-    }
-    yTRouter.router2NaviDiaLog(param, (res) => {
-    // this.addToPlan(item)
-    })
-  }
-
   // 获取食谱列表
   async getRecipeList(){
     this.recipe = await BabyFoodApi.getAllRecipes(this.keyword, this.monthRange)

BIN
features/feature/src/main/resources/base/media/xuanzhuankuang.png