Jelajahi Sumber

feat:
1. 完成 《日记View》 中的日记请求逻辑
2. 完善 weekUtils 类,新增日期对象装换
3. 完善 日记Vm 的请求类逻辑
4. 完成 新增日记/ 编辑日记 page 的交互逻辑和请求

YuJing 2 bulan lalu
induk
melakukan
78bf802f48

+ 1 - 1
features/feature/src/main/ets/apis/DiaryApi.ets

@@ -26,7 +26,7 @@ export class DiaryApi {
    * @param id 日记id
    * @returns
    */
-  static queryDiaryLogById(id: string): Promise<DiaryData> {
+  static queryDiaryLogById(id: number): Promise<DiaryData> {
     return YTRequest.get<DiaryData>(ApiUrl.QUERY_DIARY_LOG_BY_ID + '?id=' + id)
   }
 

+ 31 - 0
features/feature/src/main/ets/components/DiaryTitleItem.ets

@@ -0,0 +1,31 @@
+@Component
+export struct DiaryTitleItem {
+  title: string = ''
+  onClickBack: () => void = () => {}
+  onActionBack: (event: GestureEvent) => void = () => {}
+
+  build() {
+    Column() {
+      Text(this.title)
+        .fontSize(20)
+    }
+    .height(60)
+    .width("100%")
+    .borderRadius(20)
+    .backgroundColor("#D7D7D7")
+    .alignItems(HorizontalAlign.Start)
+    .justifyContent(FlexAlign.Center)
+    .padding({
+      left: 16,
+      right: 16,
+      top: 8,
+      bottom: 8
+    })
+    .margin({ top: 5, bottom: 5 })
+    .onClick(this.onClickBack)
+    .gesture(
+      LongPressGesture()
+        .onAction(this.onActionBack)
+    )
+  }
+}

+ 54 - 6
features/feature/src/main/ets/models/index.ets

@@ -1,17 +1,65 @@
 /**
  * 日记详细数据模型
  */
-export interface DiaryData{
+export class DiaryData{
   // 富文本正文
-  content?: string,
+  content?: string
   // 日记日期
-  diaryDate?: string,
+  diaryDate?: string
   // 日记id
-  id?: number,
+  id?: number
   // 图片地址集合
-  imageUrls?: string[],
+  imageUrls?: string[]
   // 日记标题
-  title?: string,
+  title?: string
   // 用户id
   userId?: number
+
+  // 设置日记日期
+  setDiaryDate(date: Date){
+    // 转换为 YY-MM-DD HH:mm:ss 格式
+    const year = date.getFullYear().toString().slice(-2);
+    const month = (date.getMonth() + 1).toString().padStart(2, '0');
+    const day = date.getDate().toString().padStart(2, '0');
+    const hours = date.getHours().toString().padStart(2, '0');
+    const minutes = date.getMinutes().toString().padStart(2, '0');
+    const seconds = date.getSeconds().toString().padStart(2, '0');
+
+    this.diaryDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
+  }
+
+  // 解析日记日期
+  parseDiaryDate(): Date {
+    if (!this.diaryDate)
+      return new Date();
+
+    // 分解字符串
+    const parts = this.diaryDate.split(' ');
+    const datePart = parts[0];
+    const timePart = parts[1];
+
+    // 解析日期部分
+    const year = datePart.split('-').map(Number)[0];
+    const month = datePart.split('-').map(Number)[1];
+    const day = datePart.split('-').map(Number)[2];
+
+    // 解析时间部分,如果没有则默认为00:00:00
+    let hours = 0;
+    let minutes = 0;
+    let seconds = 0;
+
+    if (timePart) {
+      const timeComponents = timePart.split(':').map(Number);
+      hours = timeComponents[0] || 0;
+      minutes = timeComponents[1] || 0;
+      seconds = timeComponents[2] || 0;
+    }
+
+    // 处理两位数年份(2000年代)
+    const fullYear = year < 50 ? 2000 + year : 1900 + year;
+
+    // 创建 Date 对象(月份需要减1,因为 Date 中月份从0开始)
+    return new Date(fullYear, month - 1, day, hours, minutes, seconds);
+  }
+
 }

+ 188 - 79
features/feature/src/main/ets/pages/IncreaseDiaryPage.ets

@@ -1,12 +1,23 @@
 import { YTAvoid, yTRouter } from 'basic'
 import { photoAccessHelper } from '@kit.MediaLibraryKit';
-
+import { DiaryDatePicker } from '../components/DiaryDatePicker';
+import { DiaryData } from '../models';
+import { DiaryViewModel } from '../viewModels/DiaryViewModel';
+import { DateUtils } from '../utils/DateUtils';
+
+/**
+ * 新增/编辑 日记
+ */
 @Component
 struct IncreaseDiaryPage {
   @StorageProp(YTAvoid.SAFE_TOP_KEY) safeTop: number = 0
-
-  @State titleInfo: string = ""
   @State imageList: string[] = []
+  // 页面编辑中的状态 - 默认为可编辑
+  @State pageReadOnly: boolean = false
+  // 时间选择器 开启控制
+  @State showTimePicker: boolean = false
+  // 日记详细数据
+  @State diaryData: DiaryData = new DiaryData();
 
   /**
    * 选择图片
@@ -25,6 +36,62 @@ struct IncreaseDiaryPage {
     }
   }
 
+  /**
+   * 点击 完成 按钮
+   */
+  async onComplete() {
+    if(this.pageReadOnly) {
+      this.pageReadOnly = false;
+      return;
+    }
+
+    // 判断是否是新增日记 - 有 id 时为 修改日记
+    if(!this.diaryData.id) {
+      console.log("保存")
+      const ans = await DiaryViewModel.saveDiaryLog(this.diaryData)
+      console.log("保存结果" + JSON.stringify(ans))
+    } else {
+      console.log("修改")
+      const ans = await DiaryViewModel.updateDiaryLog(this.diaryData)
+      console.log("修改结果" + JSON.stringify(ans))
+    }
+  }
+
+  /**
+   * 重写返回逻辑 - 拦截返回手势
+   * @returns
+   */
+  onRouterBack(): boolean {
+    // this.openToast(wrapBuilder(agreePrivacy), item)
+    yTRouter.routerBack()
+    return true;
+  }
+
+  async aboutToAppear(): Promise<void> {
+    const params = yTRouter.getParamByName("IncreaseDiaryPage").pop() as Record<string, boolean | number>;
+    this.pageReadOnly = (params?.pageReadOnly ?? false) as boolean;
+    console.log("pageEditing: " + !this.pageReadOnly)
+
+    let id = (params?.id ?? -1) as number;
+    if (id != -1) {
+      this.diaryData = await DiaryViewModel.queryDiaryLogById(id)
+    } else {
+      this.diaryData.diaryDate = DateUtils.formatDateToCustomString(new Date())
+    }
+
+    // TODO 在没有数据的时候 时间选择器的回显为 undefined
+
+    // 测试用
+    // this.diaryData.imageUrls = [
+    //   'https://hm-static.ytpm.net/upload/20250820/fa210da5-b364-4469-a6c8-d8a9038af687-1755657677967.jpeg',
+    //   'https://hm-static.ytpm.net/upload/20250820/fa210da5-b364-4469-a6c8-d8a9038af687-1755657677967.jpeg',
+    //   'https://hm-static.ytpm.net/upload/20250820/fa210da5-b364-4469-a6c8-d8a9038af687-1755657677967.jpeg',
+    //   'https://hm-static.ytpm.net/upload/20250820/fa210da5-b364-4469-a6c8-d8a9038af687-1755657677967.jpeg',
+    //   'https://hm-static.ytpm.net/upload/20250820/fa210da5-b364-4469-a6c8-d8a9038af687-1755657677967.jpeg',
+    //   'https://hm-static.ytpm.net/upload/20250820/fa210da5-b364-4469-a6c8-d8a9038af687-1755657677967.jpeg'
+    // ]
+  }
+
   build() {
     NavDestination() {
       Column({ space: 5 }) {
@@ -32,94 +99,137 @@ struct IncreaseDiaryPage {
           Image($r("app.media.close"))
             .width(20)
             .aspectRatio(1)
-            .onClick(()=>{
-              yTRouter.pop()
-            })
+            .onClick(this.onRouterBack)
 
-          Text("创")
+          Text("创作")
             .fontSize(20)
             .fontWeight(700)
 
-          Text("完成")
+          Text(this.pageReadOnly ? "编辑" : "完成")
+            .onClick(() => {
+              this.onComplete()
+            })
         }
         .width("100%")
         .justifyContent(FlexAlign.SpaceBetween)
 
         Column({space: 5}) {
-          // 标题栏
-          Row() {
-            TextInput({ text: $$this.titleInfo, placeholder: "输入标题会更受欢迎(✪ω✪)" })
-              .backgroundColor(Color.Transparent)
-              .height('100%')
-              .layoutWeight(1)
-              .fontSize(20)
-              .borderRadius(0)
-              .placeholderFont({ size: 20, weight: FontWeight.Bold })
-              .placeholderColor("#BFBFBF")
-              .padding(0)
-              .maxLength(20)
-              .caretColor('app.color.main_ac_color_dark')
-              // .onChange((text: string) => {
-              //   this.titleInfo = text
-              // })
-
-            Text(`${20 - this.titleInfo.length}`)
-              .fontColor("#BFBFBF")
+          Stack(){
+            Column(){
+              // 标题栏
+              Row() {
+                TextInput({ text: $$this.diaryData.title, placeholder: "输入标题会更受欢迎(✪ω✪)" })
+                  .padding(0)
+                  .fontSize(20)
+                  .maxLength(20)
+                  .height('100%')
+                  .layoutWeight(1)
+                  .borderRadius(0)
+                  .placeholderColor("#BFBFBF")
+                  .backgroundColor(Color.Transparent)
+                  .caretColor('app.color.main_ac_color_dark')
+                  .placeholderFont({ size: 20, weight: FontWeight.Bold })
+
+                Text(`${20 - (this.diaryData.title ? this.diaryData.title.length : 0) }`)
+                  .fontColor("#BFBFBF")
+              }
+              .height(50)
+              .border({
+                width: {
+                  bottom: 0.1
+                },
+                color: 20 - (this.diaryData.title ? this.diaryData.title.length : 0) === 0 ? Color.Red : "#BFBFBF"
+              })
+
+              // 内容栏
+              TextArea({ text: $$this.diaryData.content, placeholder: "记录此刻" })
+                .backgroundColor(Color.Transparent)
+                .padding(0)
+                .height(450)
+                .fontSize(16)
+                .width("100%")
+                .borderRadius(0)
+                .placeholderFont({ size: 16 })
+                .placeholderColor("#BFBFBF")
+                .caretColor('app.color.main_ac_color_dark')
+            }
+
+            // 当页面不可编辑时添加覆盖层
+            if(this.pageReadOnly) {
+              Row()
+                .width('100%')
+                .height('100%')
+                .backgroundColor(Color.Transparent) // 透明覆盖层
+                .onTouch((event: TouchEvent) => {
+                  event.stopPropagation() // 阻止触摸事件
+                })
+            }
           }
-          .height(50)
-          .border({
-            width: {
-              bottom: 0.1
-            },
-            color: 20 - this.titleInfo.length === 0 ? Color.Red : "#BFBFBF"
+          .height(500)
+          .onClick(() => {
+            this.showTimePicker = false
           })
-
-          // 内容栏
-          TextArea({ placeholder: "记录此刻" })
-            .backgroundColor(Color.Transparent)
-            .height(450)
+          Stack(){
+            Column(){
+              // 时间选择器
+              Row(){
+                Text("这是一个时间选择器" + this.diaryData.diaryDate?.split(' ')[0])
+              }
+              .onClick(() => {
+                this.showTimePicker = !this.showTimePicker
+              })
+
+              // 图片显示器
+              Scroll(){
+                Row({space: 5}){
+                  ForEach(this.diaryData.imageUrls, (item: string, index: number) => {
+                    Image(item)
+                      .width(100)
+                      .height(150)
+                  })
+                }
+              }
+              .scrollable(ScrollDirection.Horizontal)
+
+              // 图片选择器
+              Row(){
+                Row({space: 5}){
+                  Image($r('app.media.photoAlbum'))
+                    .width(20)
+                    .aspectRatio(1)
+
+                  Text("相册")
+                    .fontSize(16)
+                    .fontWeight(700)
+                }
+                .onClick(()=>{
+                  this.photoSelect()
+                })
+              }
+              .width("100%")
+              .alignItems(VerticalAlign.Center)
+              .justifyContent(FlexAlign.End)
+            }
             .width("100%")
-            .fontSize(16)
-            .borderRadius(0)
-            .placeholderFont({ size: 16 })
-            .placeholderColor("#BFBFBF")
-            .padding(0)
-            .caretColor('app.color.main_ac_color_dark')
-
-
-          // 时间选择器
-          Row(){
-            Text("这是一个时间选择器")
-          }
-
-          // 图片显示器
-          Row({space: 5}){
-            ForEach(this.imageList, (item: string, index: number) => {
-              Image(item)
-                .width(100)
-                .height(150)
+            .height("100%")
+            .onClick(() => {
+              this.showTimePicker = false
             })
-          }
 
-          // 图片选择器
-          Row(){
-            Row({space: 5}){
-              Image($r('app.media.photoAlbum'))
-                .width(20)
-                .aspectRatio(1)
-
-              Text("相册")
-                .fontSize(16)
-                .fontWeight(700)
+            if(this.showTimePicker) {
+              DiaryDatePicker({
+                selectedDate: new Date(this.diaryData.diaryDate ?? new Date().toISOString()),
+                selectDateBack: (date: Date) => {
+                  this.showTimePicker = false
+                  let result = DateUtils.formatDateToCustomString(date)
+                  this.diaryData.diaryDate = result
+                }
+              })
+                .width("80%")
             }
-            .onClick(()=>{
-              this.photoSelect()
-            })
           }
           .width("100%")
-          .alignItems(VerticalAlign.Center)
-          .justifyContent(FlexAlign.End)
-
+          .layoutWeight(1)
         }
         .alignItems(HorizontalAlign.Start)
         .justifyContent(FlexAlign.Start)
@@ -130,13 +240,12 @@ struct IncreaseDiaryPage {
       .height("100%")
       .padding({ top: this.safeTop, left: 16, right: 16 })
     }
+    .hideTitleBar(true)
+    .onBackPressed(this.onRouterBack)
   }
 }
 
 @Builder
 function IncreaseDiaryBuilder() {
-  NavDestination() {
-    IncreaseDiaryPage()
-  }
-  .hideTitleBar(true)
-}
+  IncreaseDiaryPage()
+}

+ 105 - 0
features/feature/src/main/ets/utils/DateUtils.ets

@@ -0,0 +1,105 @@
+import { DateInfo } from "../models/DateInfo";
+
+// 星期中文映射表
+const WEEK_MAP = ['日', '一', '二', '三', '四', '五', '六'];
+
+/**
+ * 创建一个日期信息对象
+ * @param date 日期对象
+ * @returns DateInfo 对象
+ */
+function createDateInfo(date: Date): DateInfo {
+  const year = date.getFullYear();
+  const month = date.getMonth() + 1;
+  const day = date.getDate();
+  const week = WEEK_MAP[date.getDay()];
+
+  return {
+    year: year,
+    month: month,
+    day: day,
+    week: week,
+    id: new Date(date)
+  };
+}
+
+
+export class DateUtils {
+  static formatDateToCustomString(date: Date, needTime: boolean = true) {
+    // 转换为 YY-MM-DD HH:mm:ss 格式
+    const year = date.getFullYear().toString();
+    const month = (date.getMonth() + 1).toString().padStart(2, '0');
+    const day = date.getDate().toString().padStart(2, '0');
+    const hours = date.getHours().toString().padStart(2, '0');
+    const minutes = date.getMinutes().toString().padStart(2, '0');
+    const seconds = date.getSeconds().toString().padStart(2, '0');
+
+    const result = `${year}-${month}-${day}` + (needTime ? ` ${hours}:${minutes}:${seconds}` : '');
+    return result;
+  }
+
+  /**
+   * 生成从指定日期开始向前的连续日期数组
+   * @param startDate 起始日期(默认当前日期)
+   * @param count 生成的日期数量(默认7天)
+   * @returns 日期对象数组
+   */
+  static generateForwardDateArray(
+    startDate: Date = new Date(),
+    count: number = 7
+  ): DateInfo[] {
+    const dateArray: DateInfo[] = [];
+
+    // 复制起始日期,避免修改原对象
+    const currentDate = new Date(startDate);
+
+    for (let i = 0; i < count; i++) {
+      // 添加日期信息到数组
+      dateArray.push(createDateInfo(currentDate));
+
+      // 日期减1天(向前)
+      currentDate.setDate(currentDate.getDate() - 1);
+    }
+
+    return dateArray;
+  }
+
+  /**
+   * 生成从指定日期开始向后的连续日期数组,可以包含今天但不能超过今天
+   * @param startDate 起始日期(默认当前日期)
+   * @param count 生成的日期数量(默认7天)
+   * @returns 日期对象数组,包含今天但不包含超过今天的日期
+   */
+  static generateBackwardDateArray(
+    startDate: Date = new Date(),
+    count: number = 7
+  ): DateInfo[] {
+    const dateArray: DateInfo[] = [];
+
+    // 复制起始日期,避免修改原对象
+    const currentDate = new Date(startDate);
+
+    // 获取今天的日期
+    // 获取今天的日期并设置时间为23:59:59:999,便于比较
+    const today = new Date();
+    today.setHours(0, 0, 0, 0);
+    today.setDate(today.getDate() + 1);
+    today.setTime(today.getTime() - 1); // 设置为今天的最后一毫秒
+
+    for (let i = 0; i < count; i++) {
+      // 检查当前日期是否超过今天
+      if (currentDate > today) {
+        break;
+      }
+
+      // 添加日期信息到数组
+      dateArray.push(createDateInfo(currentDate));
+
+      // 日期加1天(向后)
+      currentDate.setDate(currentDate.getDate() + 1);
+    }
+
+    return dateArray;
+  }
+}
+

+ 84 - 61
features/feature/src/main/ets/view/DiaryView.ets

@@ -1,7 +1,8 @@
 import { IBestToast, YTAvoid, yTRouter, yTToast } from "basic"
-import { ArrayList } from "@kit.ArkTS"
-import { yTDoubleConfirm } from "basic/src/main/ets/components/generalComp/YtDoubleConfirm";
-import { generateBackwardDateArray, generateCenteredDateArray, generateForwardDateArray } from "../utils/weekUtil";
+import { DiaryTitleItem } from "../components/DiaryTitleItem"
+import { DiaryData } from "../models"
+import { DateUtils } from "../utils/DateUtils"
+import { DiaryViewModel } from "../viewModels/DiaryViewModel"
 
 /**
  * 日记页面
@@ -9,19 +10,18 @@ import { generateBackwardDateArray, generateCenteredDateArray, generateForwardDa
 @Component
 export struct DiaryView {
   @StorageProp(YTAvoid.SAFE_TOP_KEY) safeTop: number = 0
+  @State Vm: DiaryViewModel = new DiaryViewModel()
 
   /**
-   * 增加日记
+   * 跳转日记详情
+   * @param id 日记 id (可选),没有 id 表示新增日记
    */
-  increaseDiary() {
-    let res = generateForwardDateArray(new Date(), 20)
-    console.log("向前  " + JSON.stringify(res))
-    let res2 = generateBackwardDateArray(new Date(), 20)
-    console.log("向后  " + JSON.stringify(res2))
-    res2 = generateCenteredDateArray(new Date(), 20)
-    console.log("向后  " + JSON.stringify(res2))
-
-    // yTRouter.pushPathByName("IncreaseDiaryPage", null);
+  routerDiaryPage(id?: number) {
+    const pageReadOnly = id ? true : false
+    yTRouter.pushPathByName("IncreaseDiaryPage", {
+      'pageReadOnly': pageReadOnly,
+      'id': id
+    } as Record<string, boolean | number>);
   }
 
   /**
@@ -32,9 +32,14 @@ export struct DiaryView {
     yTToast.doubleConfirm({
       text: "删除日记",
       message: "确定删除日记吗?",
-      click: () => {
-        IBestToast.show({ message: '删除了日记' })
+      click: async () => {
         yTToast.hide()
+
+        let ans = await this.Vm.deleteDiaryLog(index)
+        if(ans){
+          IBestToast.show({ message: '删除了日记' })
+          this.reloadDiaryData()
+        }
       }
     })
   }
@@ -47,32 +52,66 @@ export struct DiaryView {
   }
 
   /**
-   * 查看日记详情
-   * @param index 日记索引
+   * 打开日期选择器
    */
-  routerDiaryDetail(index: number){
-
+  openDatePicker(){
+    CalendarPickerDialog.show({
+      selected: new Date(),
+      // backgroundColor: Color.Gray,
+      // backgroundBlurStyle: BlurStyle.NONE,
+      // shadow: ShadowStyle.OUTER_FLOATING_SM,
+      onAccept: (value) => {
+        // this.selectedDate = value;
+        console.info("calendar onAccept:" + JSON.stringify(value));
+      },
+      onCancel: () => {
+        console.info("calendar onCancel");
+      },
+      onChange: (value) => {
+        console.info("calendar onChange:" + JSON.stringify(value));
+      },
+      onDidAppear: () => {
+        console.info("calendar onDidAppear");
+      },
+      onDidDisappear: () => {
+        console.info("calendar onDidDisappear");
+      },
+      onWillAppear: () => {
+        console.info("calendar onWillAppear");
+      },
+      onWillDisappear: () => {
+        console.info("calendar onWillDisappear");
+      }
+    })
   }
 
   /**
-   * 打开日期选择器
+   * 重新加载日记数据
    */
-  openDatePicker(){
+  reloadDiaryData() {
+    this.Vm.queryDiaryLogList(DateUtils.formatDateToCustomString(new Date(), false))
+  }
 
+  aboutToAppear(): void {
+    this.reloadDiaryData()
   }
 
   build() {
     /**
      * 1. 令日期作为 listGroup 可以方便进行跳转
      * 2. 内部存在多个 listItem 时添加粘性标题
-     * 3.
+     * 3. 通过日历选择器进行跳转时, 如果当天没有日记, 则向上寻找,还行向下
+     * 4.
      */
     Column() {
+      // title
       Row() {
         Image($r("app.media.calendar"))
           .width(30)
           .aspectRatio(1)
-
+          .onClick(() => {
+            this.openDatePicker()
+          })
 
         Text("日记本")
           .fontSize(20)
@@ -86,35 +125,48 @@ export struct DiaryView {
       .justifyContent(FlexAlign.SpaceBetween)
       .padding({ bottom: 10 })
 
+      // swiper
       Stack({ alignContent: Alignment.BottomEnd }) {
+        // 日记列表
         List({ space: 15 }) {
-          ForEach([0, 0, 0, 0, 0], (item: string, index: number) => {
+          ForEach(this.Vm.dateList, (groupTitle: string, index: number) => {
             ListItemGroup({
-              header: this.DiaryHead("2025/08/12"),
+              header: this.DiaryHead(groupTitle),
             }) {
-              ForEach(new Array(10).fill(0), (title: string, i: number) => {
+              ForEach(this.Vm.diaryDataList.filter((item) => item.diaryDate == groupTitle), (item: DiaryData, i: number) => {
                 ListItem() {
-                  this.DiaryItem("每日一记", i)
+                  DiaryTitleItem({
+                    title: item.title,
+                    onClickBack: () => {
+                      this.routerDiaryPage(item.id)
+                    },
+                    onActionBack: (event: GestureEvent) => {
+                      console.log("触发删除")
+                      this.decreaseDiary(item.id ?? -1)
+                    }
+                  })
                 }
                 .swipeAction({
-                  end: this.DiaryDel(i)
+                  end: this.DiaryDel(item.id),
+                  edgeEffect: SwipeEdgeEffect.None
                 })
-              })
+              }, (item: DiaryData) => item.id?.toString())
             }
-          })
+          }, (item: DiaryData) => item.diaryDate)
         }
         .width("100%")
         .height("100%")
         .scrollBar(BarState.Off)
 
-
         // 增加日记按钮
         Row() {
           Image($r("app.media.add"))
             .width(20)
             .aspectRatio(1)
         }
-        .onClick(this.increaseDiary)
+        .onClick(() => {
+          this.routerDiaryPage()
+        })
         .width(40)
         .aspectRatio(1)
         .border({
@@ -140,35 +192,6 @@ export struct DiaryView {
     Text(time)
   }
 
-  // 日记条目组件
-  @Builder
-  DiaryItem(title: string, index: number) {
-    Column() {
-      Text(title)
-        .fontSize(20)
-    }
-    .height(60)
-    .width("100%")
-    .borderRadius(20)
-    .backgroundColor("#D7D7D7")
-    .alignItems(HorizontalAlign.Start)
-    .justifyContent(FlexAlign.Center)
-    .padding({
-      left: 16,
-      right: 16,
-      top: 8,
-      bottom: 8
-    })
-    .margin({ top: 5, bottom: 5 })
-    .gesture(
-      LongPressGesture()
-        .onAction((event: GestureEvent) => {
-          console.log("触发删除")
-          this.decreaseDiary(index)
-        })
-    )
-  }
-
   // 日记条目删除组件
   @Builder
   DiaryDel(index: number) {

+ 103 - 0
features/feature/src/main/ets/viewModels/DiaryViewModel.ets

@@ -0,0 +1,103 @@
+import { IBestToast, YTLog, yTToast } from "basic"
+import { DiaryApi } from "../apis/DiaryApi"
+import { DiaryData } from "../models"
+import { DateUtils } from "../utils/DateUtils"
+import { HashMap } from "@kit.ArkTS"
+
+export class DiaryViewModel{
+  // 日记列表
+  diaryDataList: DiaryData[] = []
+  // 时间列表
+  dateList: string[] = []
+
+  /**
+   * 删除日记
+   * @param id 日记 id
+   */
+  async deleteDiaryLog(id: number) {
+    const result = await DiaryApi.deleteDiaryLog(id)
+    YTLog.info(`删除日记结果 ${result}`)
+    // if(result) {
+    //   IBestToast.show("删除成功")
+    //   yTToast.hide()
+    // } else {
+    //   IBestToast.show("删除失败")
+    //   yTToast.hide()
+    // }
+    return result
+  }
+
+  /**
+   * 查询日记列表
+   * @param nowTime 当前选中时间
+   * @returns 日记列表
+   */
+  async queryDiaryLogList(nowTime: string){
+    const result: DiaryData[] = await DiaryApi.queryDiaryLogList(nowTime)
+    YTLog.info(`查询日记列表结果 ${JSON.stringify(result)}`)
+    this.diaryDataList = result
+
+    let i = 0;
+    this.dateList[0] = result[0].diaryDate!
+    for (let index = 0; index < result.length; index++) {
+      if(result[index].diaryDate != this.dateList[i]){
+        this.dateList.push(result[index].diaryDate!)
+        i++;
+      }
+    }
+
+    console.log('title_List ' + JSON.stringify(this.dateList))
+  }
+
+  /**
+   * 日记搜索
+   * @param keyWord 日记标题关键字
+   * @returns
+   */
+  async diaryLogSearch(keyWord: string) {
+    const result: DiaryData[] = await DiaryApi.diaryLogSearch(keyWord)
+    YTLog.info(`查询日记搜索结果 ${JSON.stringify(result)}`)
+  }
+
+  /**
+   * 修改日记
+   * @param params 日记数据结构
+   * @returns
+   */
+  static async updateDiaryLog(params: DiaryData) {
+    let ans = params.diaryDate?.split(' ')[1]
+    if(!ans) {
+      params.diaryDate += ' 00:00:01'
+    }
+    const result = await DiaryApi.updateDiaryLog(params)
+    YTLog.info(`修改日记结果 ${result}`)
+  }
+
+  /**
+   * 查询日记详情
+   * @param id
+   * @returns
+   */
+  static async queryDiaryLogById(id: number) {
+    const result: DiaryData = await DiaryApi.queryDiaryLogById(id)
+    YTLog.info(`查询日记结果 ${JSON.stringify(result)}`)
+    return result
+  }
+
+  /**
+   * 新增日记
+   * @param params 日记数据结构
+   * @returns
+   */
+  static async saveDiaryLog(params: DiaryData) {
+    const result = await DiaryApi.saveDiaryLog(params)
+    YTLog.info(`新增日记结果 ${result}`)
+    // if(result) {
+    //   IBestToast.show("删除成功")
+    //   yTToast.hide()
+    // } else {
+    //   IBestToast.show("删除失败")
+    //   yTToast.hide()
+    // }
+  }
+}