Parcourir la source

feat: 完成首页下食谱计划的变更和采购清单的交互

YuJing il y a 1 mois
Parent
commit
5a24ff7da3

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

@@ -19,7 +19,7 @@ export class BabyFoodApi{
   }
 
   // 已购买状态修改(0=未购买 | 1=已购买)
-  static updatePurchaseStatus(id: number): Promise<null> {
+  static updatePurchaseStatus(id: number): Promise<string> {
     return YTRequest.post(ApiUrl.updatePurchaseStatus, null, {id})
   }
 
@@ -29,13 +29,11 @@ export class BabyFoodApi{
   }
 
   // 获取本周食谱计划
-  // todo
   static getWeeklyPlan(babyId?: number, startDate?: string): Promise<WeeklyPlan> {
     return YTRequest.get(ApiUrl.getWeeklyPlan, {babyId, startDate})
   }
 
   // 编辑本周食谱
-  // todo
   static updateWeeklyPlan(weeklyPlan: WeeklyPlanPurchaseList): Promise<null> {
     return YTRequest.post(ApiUrl.updateWeeklyPlan, weeklyPlan)
   }

+ 9 - 1
features/feature/src/main/ets/model/Index.ets

@@ -42,7 +42,7 @@ export class PurchaseList {
 // 菜品菜单
 @ObservedV2
 export class Cuisine {
-  id?: number;
+  @Trace id?: number;
   @Trace name?: string;
 }
 
@@ -87,6 +87,14 @@ export class DayPlan {
   @Trace breakfast?: Cuisine;
   @Trace lunch?: Cuisine;
   @Trace dinner?: Cuisine;
+
+  constructor(i?: DayPlan) {
+    if (i) {
+      this.breakfast = i.breakfast;
+      this.lunch = i.lunch;
+      this.dinner = i.dinner;
+    }
+  }
 }
 
 // 周计划食材清单

+ 128 - 64
features/feature/src/main/ets/view/MainView.ets

@@ -119,7 +119,7 @@ export struct MainView {
             Swiper(){
               ForEach(this.vm.week, (item: string, index: number) => {
                 Row(){
-                  RecipeWidget({ week: item, vm: this.vm })
+                  RecipeWidget({ week: item, vm: this.vm, index: index })
                 }
                 .padding(5)
                 .width(320)
@@ -168,14 +168,24 @@ export struct MainView {
 
           Column(){
             Column(){
-              if(true){              // 菜品列表
-                ForEach(new Array(3).fill(0), (item: number, index: number) =>{
+              if(this.vm.purchaseList && this.vm.purchaseList?.length > 0){              // 菜品列表
+                ForEach(new Array(Math.min(this.vm.purchaseList?.length ?? 0, 3)).fill(0), (item: number, index: number) =>{
                   Row(){
-                    Text('南瓜-100g')
+                    Text(){
+                      Span(this.vm.purchaseList?.[index].ingredientName ?? '南瓜')
+                      Span('-')
+                      Span((this.vm.purchaseList?.[index].amount ?? 1) + '')
+                      Span(this.vm.purchaseList?.[index].unit ?? 'g')
+                    }
+                    .fontSize(14)
+                    .fontColor('#4F4F4F')
 
-                    Image($r('app.media.icon_select'))
+                    // 是否购买按钮
+                    Image(this.vm.purchaseList?.[index].purchased ?
+                    $r('app.media.icon_select') : $r('app.media.icon_unSelect'))
                       .width(20)
                       .aspectRatio(1)
+                      .onClick(() => { this.vm.updateBuyStatus(this.vm.purchaseList?.[index].id ?? 0, index) })
                   }
                   .width("100%")
                   .justifyContent(FlexAlign.SpaceBetween)
@@ -196,11 +206,13 @@ export struct MainView {
                   Text('查看全部')
                     .fontSize(12)
                     .fontColor('#95C50A')
+                    .onClick(() => { this.vm.goToPurchaseDetail() })
                 }
                 .width("100%")
                 .alignItems(VerticalAlign.Center)
                 .justifyContent(FlexAlign.End)
                 .padding({ left: 16, right: 16, top: 5, bottom: 16 })
+
               } else {
                 Row(){
                   Text('暂无数据')
@@ -258,59 +270,112 @@ export struct MainView {
  */
 @ComponentV2
 struct RecipeWidget{
-  @Require @Param week: string = "周一"
-  @Require @Param vm: MainViewModel = new MainViewModel()
+  @Require @Param week: string
+  @Require @Param index: number
+  @Require @Param vm: MainViewModel
 
-  @Local isShowEnum: string = ''
+  // 当前选中的菜品
+  @Local selectCuisine: number = -1
   @Local toDayPlan?: DayPlan
 
-  threeMeals: Array<BasicType<Cuisine>> = []
+  threeMeals: Array<BasicType<Cuisine>> = [
+    {
+      text: '早餐',
+      id: 'breakfast'
+    },
+    {
+      text: '午餐',
+      id: 'lunch'
+    },
+    {
+      text: '晚餐',
+      id: 'dinner'
+    }
+  ]
 
-  getToDayPlan(){
+  getToDayPlan(needReload: boolean = true){
     switch (this.week) {
       case '周一':
-        this.toDayPlan = this.vm.planList?.monday
-        break;
+        if(needReload){
+          this.toDayPlan = new DayPlan(this.vm.planList?.monday)
+        }
+        return this.vm.planList?.monday
       case '周二':
-        this.toDayPlan = this.vm.planList?.tuesday
-        break;
+        if(needReload){
+          this.toDayPlan = new DayPlan(this.vm.planList?.tuesday)
+        }
+          return this.vm.planList?.tuesday
       case '周三':
-        this.toDayPlan = this.vm.planList?.wednesday
-        break;
+        if(needReload){
+          this.toDayPlan = new DayPlan(this.vm.planList?.wednesday)
+        }
+        return this.vm.planList?.wednesday
       case '周四':
-        this.toDayPlan = this.vm.planList?.thursday
-        break;
+        if(needReload){
+          this.toDayPlan = new DayPlan(this.vm.planList?.thursday)
+        }
+        return this.vm.planList?.thursday
       case '周五':
-        this.toDayPlan = this.vm.planList?.friday
-        break;
+        if(needReload){
+          this.toDayPlan = new DayPlan(this.vm.planList?.friday)
+        }
+        return this.vm.planList?.friday
       case '周六':
-        this.toDayPlan = this.vm.planList?.saturday
-        break;
+        if(needReload){
+          this.toDayPlan = new DayPlan(this.vm.planList?.sunday)
+        }
+        return this.vm.planList?.saturday
       case '周日':
-        this.toDayPlan = this.vm.planList?.sunday
-        break;
+        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 === '早餐') {
+      return this.toDayPlan?.breakfast
+    } else if(text === '午餐') {
+      return this.toDayPlan?.lunch
+    } else if(text === '晚餐') {
+      return this.toDayPlan?.dinner
+    }
+    return undefined
+  }
+
+  // 展开菜单
+  openMenu(text: string){
+    let cuisine: Cuisine | undefined = this.getCuisine(text)
+    if(cuisine) {
+      this.selectCuisine = cuisine.id ?? -1
     }
-    if(this.toDayPlan && this.toDayPlan.breakfast) {
-      this.toDayPlan!.breakfast!.name = "我改一改看看"
+  }
+
+  // 选中修改菜品
+  updateCuisine(id: number){
+    let origin = this.getToDayPlan(false)
+    let cuisine: Cuisine | undefined = this.vm.getCuisineInfo(id)
+    if(this.toDayPlan?.breakfast?.id == this.selectCuisine) {
+      this.toDayPlan.breakfast = cuisine
+      origin!.breakfast = this.toDayPlan?.breakfast
+    } else if (this.toDayPlan?.lunch?.id == this.selectCuisine) {
+      this.toDayPlan.lunch = cuisine
+      origin!.lunch = this.toDayPlan?.lunch
+    } else if (this.toDayPlan?.dinner?.id == this.selectCuisine) {
+      this.toDayPlan.dinner = cuisine
+      origin!.dinner = this.toDayPlan?.dinner
     }
+
+    this.vm.updateWeeklyPlan()
   }
 
   aboutToAppear(): void {
-    this.getToDayPlan()
-    this.threeMeals = [
-      {
-        text: '早餐',
-        id: 'breakfast'
-      },
-      {
-        text: '午餐',
-        id: 'lunch'
-      },
-      {
-        text: '晚餐',
-        id: 'dinner'
-      }
-    ]
+    this.vm.addEvent(() => {
+      this.getToDayPlan()
+    })
   }
 
   build() {
@@ -337,20 +402,8 @@ struct RecipeWidget{
 
             Row({space: 8}){
               Text(){
-              //   if(true) {
-              //     Span('南瓜-100g')
-              //   } else {
-              //     Span('无')
-              //       .fontSize(14)
-              //       .fontColor('#A6A6AB')
-              //   }
-
-                if(item.text === '早餐') {
-                  Span(this.toDayPlan?.breakfast?.name)
-                } else if(item.text === '午餐') {
-                  Span(this.toDayPlan?.lunch?.name)
-                } else if(item.text === '晚餐') {
-                  Span(this.toDayPlan?.dinner?.name)
+                if(this.getCuisine(item.text!)?.name){
+                  Span(this.getCuisine(item.text!)?.name)
                 } else {
                   Span('无')
                     .fontSize(14)
@@ -363,9 +416,10 @@ struct RecipeWidget{
                 .rotate({ angle:270 })
                 .width(20)
             }
-            .width(90)
+            .justifyContent(FlexAlign.End)
+            .width(110)
             .bindMenu(this._MenuWidget, { hapticFeedbackMode: HapticFeedbackMode.ENABLED })
-            .onClick(() => { this.isShowEnum = '七七八八'+item.text })
+            .onClick(() => { this.openMenu(item.text!) })
           }
           .width('100%')
           .padding({top: 14, bottom: 14})
@@ -384,14 +438,23 @@ struct RecipeWidget{
 
   // 菜单结构
   @Builder _MenuWidget(){
-    Column(){
-      ForEach(new Array(5).fill(0), (item:number, index: number) => {
-        Text(this.isShowEnum ?? "南瓜米糊米糊")
-          .fontSize(16)
-          .fontWeight(500)
-      })
+    Scroll(){
+      Column(){
+        ForEach(this.vm.dishList, (item:Cuisine, index: number) => {
+          Text(item.name)
+            .fontSize(16)
+            .width("100%")
+            .fontWeight(500)
+            .borderRadius(8)
+            .textAlign(TextAlign.Center)
+            .padding({left: 36, right: 36, top: 15, bottom: 15})
+            .backgroundColor(item.id == this.selectCuisine ? '#F3F3F3' : '#FFFFFF')
+            .onClick(() => { this.updateCuisine(item.id!) })
+        })
+      }
     }
-    .width(160)
+    .width(220)
+    .height(250)
     .padding({left: 12, right: 12, top: 5, bottom: 5})
   }
 
@@ -405,6 +468,7 @@ struct RecipeWidget{
           .backgroundColor(color)
       })
     }
+    .width("100%")
   }
 }
 

+ 71 - 10
features/feature/src/main/ets/viewModel/MainViewModel.ets

@@ -2,7 +2,7 @@ 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, WeeklyPlan, WeeklyPlanPurchaseList } from "../model/Index"
+import { BabyInfo, Cuisine, DayPlan, PurchaseList, WeeklyPlan, WeeklyPlanPurchaseList } from "../model/Index"
 
 @ObservedV2
 export class MainViewModel{
@@ -18,10 +18,15 @@ export class MainViewModel{
   @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
@@ -32,16 +37,19 @@ export class MainViewModel{
     this.userInfo.setUserInfoAndLogin(userInfo, false)
 
     if(this.userInfo.checkLogin()){
-      // 如果需要同步操作记得加  await
-      await this.getBabyList()
-      await this.getWeeklyPlan()
-      await this.getDishList()
+      // 宝宝信息没有的话也没必要加载后续数据了
+      this.getBabyList().then(async () => {
+        await this.getWeeklyPlan()
+        await this.getDishList()
+        await this.getWeeklyPurchaseList()
+        this.eventFunc.forEach(f => f())
+      })
     } else {
       this.babyList = []
     }
   }
 
-  // 登录校验函数
+  // 登录校验 - 宝宝信息校验
   checkLogin(f: () => void, isCheckBaby: boolean = true) {
     if(this.userInfo.checkLogin()) {
       if(this.babyInfo?.id || !isCheckBaby){
@@ -61,16 +69,51 @@ export class MainViewModel{
     this.selectedBabyIndex = index
   }
 
+  // 添加事件
+  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]
+  }
+
   // 获取本周食谱计划
   async getWeeklyPlan(startDate?: string){
-    if(!startDate) startDate = YTDateUtil.formatDate(new Date(), DateFormat.UNDERLINE)
-    this.allPlan = await BabyFoodApi.getWeeklyPlan(this.babyInfo.id, startDate)
-    this.planList = this.allPlan.weeklyPlan
+      try {
+        if(!startDate) startDate = YTDateUtil.formatDate(new Date(), DateFormat.UNDERLINE)
+        this.allPlan = await BabyFoodApi.getWeeklyPlan(this.babyInfo.id, startDate)
+        this.planList = this.allPlan.weeklyPlan
+      } catch (e){
+        console.log(`e = ${JSON.stringify(e)}`)
+      }
+  }
+
+  // 更新本周食谱计划
+  async updateWeeklyPlan(): Promise<boolean>{
+    try {
+      await BabyFoodApi.updateWeeklyPlan(this.planList!)
+      return true
+    } catch (e) {
+      return false
+    }
+  }
+
+  // 获取本周所有采购清单
+  async getWeeklyPurchaseList(): Promise<void>{
+    this.purchaseList = await BabyFoodApi.getWeeklyPurchaseList(this.babyInfo.id!)
   }
 
   // 获取菜品列表
   async getDishList(){
-    this.dishList = await BabyFoodApi.getDishList()
+    try {
+      this.dishList = await BabyFoodApi.getDishList()
+    } catch (e){
+      console.log(`e = ${JSON.stringify(e)}`)
+    }
   }
 
   // 获取宝宝信息列表
@@ -79,6 +122,19 @@ export class MainViewModel{
     this.updateBabyInfo(0)
   }
 
+  // 修改购买状态 - 清单 id
+  async updateBuyStatus(Id: number, index: number){
+    try {
+      let ans = await BabyFoodApi.updatePurchaseStatus(Id)
+      let l = this.purchaseList![index]
+      if(ans == '0') l.purchased = true
+      else l.purchased = false
+      this.purchaseList?.splice(index, 1, l)
+    } catch (e) {
+      console.log(`e = ${JSON.stringify(e)}`)
+    }
+  }
+
   // 进入添加宝宝信息页面
   increaseBabyInfo(){
     routerUtils.router2IncreaseBabyInfo((res) => {
@@ -86,6 +142,11 @@ export class MainViewModel{
     })
   }
 
+  // 跳转至采购详情页
+  goToPurchaseDetail() {
+
+  }
+
   /**
    * 重写的返回逻辑
    * @returns