소스 검색

feat:associated database

0225304 6 일 전
부모
커밋
f6fc9ac4cf

+ 1 - 1
myapp/src/app/tab1/edit/edit.page.html

@@ -51,4 +51,4 @@
       </ion-item>
     </ion-list>
   </form>
-</ion-content>
+</ion-content>

+ 16 - 2
myapp/src/app/tab1/edit/edit.page.ts

@@ -17,18 +17,27 @@ export class EditPage {
     content: '',
     weather: '',
     mood: '',
+    user: '' // 添加用户字段
   };
 
+  currentUser: CloudUser | null = null;
+
   constructor(private modalCtrl: ModalController) {}
 
   ngOnInit() {
     // 生成随机ID
     this.diary.Did = Math.floor(Math.random() * 100000);
+    // 设置当前用户
+    if (this.currentUser) {
+      this.diary.user = this.currentUser.toPointer();
+    }
   }
 
   // 获取当前日期
   private getCurrentDate(): string {
-    return new Date().getDate().toString();
+    //return new Date().getDate().toString();
+    const now = new Date();
+    return `${now.getFullYear()}-${(now.getMonth() + 1).toString().padStart(2, '0')}-${now.getDate().toString().padStart(2, '0')}`;
   }
 
   // 获取当前星期
@@ -44,6 +53,11 @@ export class EditPage {
   }
 
   async saveDiary() {
+    if (!this.diary.user) {
+      console.error('用户未登录,无法保存日记');
+      this.modalCtrl.dismiss({ saved: false });
+      return;
+    }
     // 创建新的日记对象
     const newDiary = new CloudObject("Diary");
     newDiary.set(this.diary);
@@ -62,4 +76,4 @@ export class EditPage {
   dismiss() {
     this.modalCtrl.dismiss({ saved: false });
   }
-}
+}

+ 47 - 10
myapp/src/app/tab1/tab1.page.ts

@@ -14,7 +14,8 @@ import { ActivatedRoute } from '@angular/router';
 export class Tab1Page implements OnInit{
   
   router: any; 
-
+  diaryList: CloudObject[]=[];
+  currentUser: CloudUser | null = null;
   constructor(
     private modalCtrl: ModalController,
     private routerOutlet: IonRouterOutlet,
@@ -22,7 +23,8 @@ export class Tab1Page implements OnInit{
     private activatedRoute: ActivatedRoute
   ) {
     this.activatedRoute.params.subscribe(()=>{
-      this.loadDiaries();
+      //this.loadDiaries();
+      this.loadCurrentUserAndDiaries();
     })
   }
   
@@ -44,10 +46,31 @@ export class Tab1Page implements OnInit{
   }
   
 }
-  diaryList: CloudObject[]=[];
+  
+async loadCurrentUserAndDiaries() {
+    // 获取当前用户
+    this.currentUser = await CloudUser.current();
+    
+    if (this.currentUser) {
+      // 如果用户已登录,加载该用户的日记
+      await this.loadDiaries();
+    } else {
+      // 用户未登录,清空日记列表
+      this.diaryList = [];
+    }
+  }
   async loadDiaries() {
-    let query=new CloudQuery("Diary"); 
-    this.diaryList=await query.find();
+    // let query=new CloudQuery("Diary"); 
+    // this.diaryList=await query.find();
+
+    if (!this.currentUser) return;
+    
+    let query = new CloudQuery("Diary");
+    // 只查询当前用户的日记
+    query.equalTo("user", this.currentUser.toPointer());
+    // 按创建时间降序排列
+    query.queryParams["order"] = "-createdAt";
+    this.diaryList = await query.find();
 
   }
 
@@ -56,12 +79,26 @@ export class Tab1Page implements OnInit{
   }
 
   async goToEditPage(edit?:string) {
-    const modal = await this.modalCtrl.create({
-    component: EditPage,
-    componentProps: {
-      editMode: edit === '编辑'
+  //   const modal = await this.modalCtrl.create({
+  //   component: EditPage,
+  //   componentProps: {
+  //     editMode: edit === '编辑'
+  //   }
+  // });
+
+  if (!this.currentUser) {
+      // 如果用户未登录,跳转到登录页面
+      this.navCtrl.navigateForward(['/login']);
+      return;
     }
-  });
+
+    const modal = await this.modalCtrl.create({
+      component: EditPage,
+      componentProps: {
+        editMode: edit === '编辑',
+        currentUser: this.currentUser
+      }
+    });
   
   // 模态框关闭后的处理
   modal.onDidDismiss().then((result) => {

+ 68 - 22
myapp/src/app/tab1/test-message/test-message.page.ts

@@ -1,7 +1,7 @@
 import { Component, OnInit } from '@angular/core';
 import { ActivatedRoute, Router } from '@angular/router';
-import { NavController, ModalController } from '@ionic/angular';
-import { CloudObject, CloudQuery } from 'src/lib/ncloud';
+import { NavController, ModalController,AlertController } from '@ionic/angular';
+import { CloudObject, CloudQuery,CloudUser } from 'src/lib/ncloud';
 import { EditPage } from '../edit/edit.page';
 
 @Component({
@@ -14,14 +14,16 @@ export class TestMessagePage implements OnInit {
   //diary: CloudObject | null = null;
   diary: any = null;  // 改为 any 类型或创建接口
   diaryId: string = '';
-
+  currentUser: CloudUser | null = null;
   constructor(
     private route: ActivatedRoute, 
     private navCtrl: NavController,
-    private modalCtrl: ModalController
+    private modalCtrl: ModalController,
+     private alertCtrl: AlertController
   ) {}
 
-  ngOnInit() {
+  async ngOnInit() {
+    this.currentUser = await CloudUser.current();
     this.route.queryParams.subscribe(params => {
       this.diaryId = params['Did'];
       this.loadDiary();
@@ -42,12 +44,32 @@ export class TestMessagePage implements OnInit {
         get: (key: string) => result.get(key),
         id: result.id  // 假设 CloudObject 有 id 属性
       };
+      // 检查日记是否属于当前用户
+      const diaryUser = result.get('user');
+      if (diaryUser && diaryUser.objectId !== this.currentUser?.id) {
+        this.showNotOwnerAlert();
+      }
     }
   }
 
+  async showNotOwnerAlert() {
+    const alert = await this.alertCtrl.create({
+      header: '权限不足',
+      message: '这不是你的日记,无法编辑或删除',
+      buttons: ['确定']
+    });
+    await alert.present();
+  }
+
   async editDiary() {
-    if (!this.diary) return;
+    if (!this.diary || !this.currentUser) return;
 
+    // 检查日记是否属于当前用户
+    const diaryUser = this.diary.get('user');
+    if (diaryUser && diaryUser.objectId !== this.currentUser.id) {
+      this.showNotOwnerAlert();
+      return;
+    }
     // 准备要编辑的数据
     const diaryData = {
       Did: this.diary.get('Did'),
@@ -56,14 +78,16 @@ export class TestMessagePage implements OnInit {
       time: this.diary.get('time'),
       content: this.diary.get('content'),
       weather: this.diary.get('weather'),
-      mood: this.diary.get('mood')
+      mood: this.diary.get('mood'),
+      user: this.currentUser.toPointer()
     };
     
     const modal = await this.modalCtrl.create({
       component: EditPage,
       componentProps: {
         diary: diaryData,
-        editMode: true
+        editMode: true,
+        currentUser: this.currentUser
       }
     });
     
@@ -77,21 +101,43 @@ export class TestMessagePage implements OnInit {
   }
 
   async deleteDiary() {
-    if (!this.diary || !this.diary.id) return;
+    if (!this.diary || !this.diary.id || !this.currentUser) return;
     
-    try {
-      // 创建查询并删除
-      const query = new CloudQuery("Diary");
-      query.equalTo("objectId", this.diary.id);
-      const objectToDelete = await query.first();
-      
-      if (objectToDelete) {
-        // 假设 CloudObject 有 destroy 方法而不是 delete
-        await objectToDelete.destroy(); // 或者使用其他删除方法如 remove()
-        this.navCtrl.navigateBack('/tabs/tab1');
-      }
-    } catch (error) {
-      console.error('删除日记失败:', error);
+    // 检查日记是否属于当前用户
+    const diaryUser = this.diary.get('user');
+    if (diaryUser && diaryUser.objectId !== this.currentUser.id) {
+      this.showNotOwnerAlert();
+      return;
     }
+
+    const alert = await this.alertCtrl.create({
+      header: '确认删除',
+      message: '确定要删除这篇日记吗?',
+      buttons: [
+        {
+          text: '取消',
+          role: 'cancel'
+        },
+        {
+          text: '删除',
+          handler: async () => {
+            try {
+              const query = new CloudQuery("Diary");
+              query.equalTo("objectId", this.diary.id);
+              const objectToDelete = await query.first();
+              
+              if (objectToDelete) {
+                await objectToDelete.destroy();
+                this.navCtrl.navigateBack('/tabs/tab1');
+              }
+            } catch (error) {
+              console.error('删除日记失败:', error);
+            }
+          }
+        }
+      ]
+    });
+    
+    await alert.present();
   }
 } 

+ 1 - 1
myapp/src/app/tab2/tab2.page.html

@@ -47,7 +47,7 @@
       <div class="user-info">
         <div class="user-left">
           <div class="user-avatar">{{ dynamic.get('author')?.get('username')?.charAt(0) || 'U' }}</div>
-          <div class="user-name">{{ dynamic.get('author')?.objectId|| '匿名用户' }}</div>
+          <div class="user-name">{{ dynamic.get('author')?.objectId || '匿名用户' }}</div>
         </div>
         <ion-icon name="ellipsis-horizontal" class="more-icon"></ion-icon>
       </div>

+ 10 - 5
myapp/src/app/tab2/thanks-cloud/thanks-cloud.page.html

@@ -5,9 +5,9 @@
     </ion-buttons>
     <ion-title>感恩清单</ion-title>
     <ion-buttons slot="end">
-    <ion-button (click)="importThanks()">
-        <ion-icon name="cloud-outline"></ion-icon>
-    </ion-button>
+        <ion-button (click)="addNewThanks()">
+            <ion-icon name="add"></ion-icon>
+        </ion-button>
     </ion-buttons>
   </ion-toolbar>
   
@@ -15,9 +15,14 @@
 
 <ion-content class="ion-padding" [fullscreen]="true">
   
+  <!-- 当列表为空时显示的提示 -->
+  <div *ngIf="thanksList.length === 0" class="empty-state">
+    <ion-icon name="document-text-outline" class="empty-icon"></ion-icon>
+    <h2>还没有感恩清单</h2>
+    <p>点击右上角 <ion-icon name="add"></ion-icon> 创建第一篇感恩清单</p>
+  </div>
     
-  <div *ngFor="let thanks of thanksList" class="gratitude-container">
-    
+  <div *ngFor="let thanks of thanksList" class="gratitude-container"> 
     <!-- 单个感恩卡片 -->
     <ion-card  class="gratitude-card">
       <ion-card-header class="card-header">

+ 34 - 0
myapp/src/app/tab2/thanks-cloud/thanks-cloud.page.scss

@@ -177,4 +177,38 @@ ion-accordion {
     font-size: 15px;
     padding: 12px;
   }
+}
+
+.empty-state {
+  display: flex;
+  flex-direction: column;
+  align-items: center;
+  justify-content: center;
+  height: 70vh;
+  text-align: center;
+  color: var(--ion-color-medium);
+
+  .empty-icon {
+    font-size: 64px;
+    margin-bottom: 16px;
+    color: var(--ion-color-medium-shade);
+  }
+
+  h2 {
+    font-size: 18px;
+    font-weight: 500;
+    margin-bottom: 8px;
+    color: var(--ion-color-dark);
+  }
+
+  p {
+    font-size: 14px;
+    margin: 0;
+    color: var(--ion-color-medium);
+  }
+
+  ion-icon {
+    vertical-align: middle;
+    color: var(--ion-color-primary);
+  }
 }

+ 185 - 122
myapp/src/app/tab2/thanks-cloud/thanks-cloud.page.ts

@@ -1,6 +1,6 @@
 import { Component, OnInit } from '@angular/core';
-import { CloudObject, CloudQuery } from 'src/lib/ncloud';
-//import { ParseService } from '../../services/parse.service';
+import { CloudObject, CloudQuery,CloudUser } from 'src/lib/ncloud';
+import { AlertController } from '@ionic/angular';
 
 @Component({
   selector: 'app-thanks-cloud',
@@ -12,141 +12,204 @@ export class ThanksCloudPage implements OnInit {
 
   constructor(
     //private parseService: ParseService
+    private alertController: AlertController
   ) { 
-    this.loadThanksType()
+    this.checkLoginAndLoadData();
   }
-
+  currentUser: CloudUser | null = null;
   thanksList: CloudObject[]=[];
+
   async loadThanksType(){
 
-    //修改前
     let query=new CloudQuery("ThanksType")
     this.thanksList=await query.find();
-    //修改后
-    //this.parseService.fetchThanksList();
   } 
 
   ngOnInit() {
-    this.loadThanksType()
-    this.thanksList=[];
+    //this.checkLoginAndLoadData();
   }
-  async importThanks(){
-    const thanksDataset = [
-    {
-        Tid: 1,
-        date: 17,
-        weekday: "周五",
-        time: "07:15",
-        content: "清晨被窗外的鸟鸣唤醒,发现室友已经煮好了咖啡。阳光透过窗帘的缝隙在地板上画出一道金线,突然觉得平凡的生活里藏着好多温柔。",
-        weather: "晴",
-        mood: "☕️",
-        tags:["情感分析","行动计划"],
-        reflection: "原来幸福可以这么简单,明天我要早起为室友做早餐",
-        actionStep: "记录3个晨间值得感恩的细节",
-        emotionalImpact: "安全感+2 | 社会联结感+1",
-        emotionalJournal: "安静→温暖→感恩的情绪流动"
-    },
-    {​
-        Tid: 2,
-        date: 18,
-        weekday: "周六",
-        time: "14:30",
-        content: "去菜市场买了把新鲜的小雏菊,回家插在旧玻璃瓶里。路过的邻居夸花好看,还分享了她的插花技巧,平凡的午后变得格外明亮。",
-        weather: "多云",
-        mood: "🌼",
-        tags:["情感分析","生活仪式感"],
-        reflection: "生活中的小美好,往往藏在与他人的善意互动里,以后要多和邻居交流",
-        actionStep: "每周尝试一种新的鲜花装饰房间",
-        emotionalImpact: "愉悦感 + 3 | 归属感 + 1",
-        emotionalJournal: "平淡→惊喜→满足的情绪转变"
-    }​,
-    {​
-        Tid: 3,
-        date: 19,
-        weekday: "周日",
-        time: "19:45",
-        content: "加班到很晚,疲惫地走出公司,发现地铁站口的流浪歌手在唱我喜欢的歌。驻足听了一会儿,歌声好像驱散了所有的劳累。",
-        weather: "阴",
-        mood: "🎵",
-        tags:["情感分析","自我疗愈"],
-        reflection: "音乐真的有治愈人心的力量,以后要多给自己留一些听音乐的时间",
-        actionStep: "整理一份专属治愈歌单",
-        emotionalImpact: "压力缓解 + 3 | 平静感 + 2",
-        emotionalJournal: "疲惫→舒缓→放松的情绪过渡"
-    }​,
-    {​
-        Tid: 4,
-        date: 20,
-        weekday: "周一",
-        time: "12:10",
-        content: "午餐时和同事拼桌,聊到小时候的趣事,大家笑得前仰后合。原来一顿简单的午饭,也能成为拉近彼此距离的桥梁。",
-        weather: "晴",
-        mood: "😄",
-        tags:["情感分析","职场社交"],
-        reflection: "工作之余的轻松交流很重要,以后要多参与同事间的互动",
-        actionStep: "主动发起一次同事间的午餐聚会",
-        emotionalImpact: "幸福感 + 2 | 团队融入感 + 2",
-        emotionalJournal: "平淡→欢乐→温暖的情绪变化"
-    }​,
-    {​
-        Tid: 5,
-        date: 21,
-        weekday: "周二",
-        time: "21:30",
-        content: "下雨天忘记带伞,正发愁时,一位陌生的阿姨撑着伞邀请我共行。短短一段路,却让我感受到陌生人的善意如此珍贵。",
-        weather: "雨",
-        mood: "🌧️→☀️",
-        tags:["情感分析","陌生人善意"],
-        reflection: "原来善意可以传递,下次遇到他人有困难,我也要主动帮忙",
-        actionStep: "本周内为一位陌生人提供一次帮助",
-        emotionalImpact: "感动 + 3 | 对世界的信任感 + 2",
-        emotionalJournal: "焦虑→惊喜→温暖的情绪起伏"
-    }​,
-    {​
-        Tid: 6,
-        date: 22,
-        weekday: "周三",
-        time: "08:20",
-        content: "晨跑时发现小区里的石榴树结了小果子,嫩绿的叶片间藏着星星点点的生机。突然觉得,只要用心观察,处处都是生命的奇迹。",
-        weather: "晴",
-        mood: "🌱",
-        tags:["情感分析","自然观察"],
-        reflection: "生活需要放慢脚步,多留意身边的美好",
-        actionStep: "每天记录一个自然观察小发现",
-        emotionalImpact: "愉悦感 + 2 | 对生活的热爱 + 2",
-        emotionalJournal: "平常→惊喜→热爱的情绪流动"
-    }
-    ];
-    const ThanksType=new CloudObject("ThanksType");
-    const query=new CloudQuery("ThanksType");
 
-    for(const thanks of thanksDataset){
-      try{
-        const query=new CloudQuery("ThanksType");
-        //检查是否已存在相同内容
-        query.equalTo("Tid",thanks.Tid);
-        const existing=await query.first();
+    async checkLoginAndLoadData() {
+    // 获取当前用户
+    this.currentUser = await CloudUser.current();
+    if (this.currentUser) {
+      await this.loadThanksList();
+    } else {
+      // 如果用户未登录,可以跳转到登录页面或显示登录提示
+      console.warn('用户未登录');
+      this.showLoginAlert();
+    }
+  }
 
-        if(existing){
-          console.log(`清单${thanks.content}"已存在,保存跳过`);
-          continue;
+  async showLoginAlert() {
+    const alert = await this.alertController.create({
+      header: '未登录',
+      message: '请先登录才能查看和创建感恩清单',
+      buttons: [
+        {
+          text: '取消',
+          role: 'cancel'
+        },
+        {
+          text: '去登录',
+          handler: () => {
+            // 这里可以导航到登录页面
+            // this.router.navigate(['/login']);
+          }
         }
-        //创建新感恩清单
-        const newThanks=new CloudObject("ThanksType");
-        newThanks.set(thanks);
-        //保存到数据库
-        await newThanks.save();
-        console.log(`清单${thanks.content}保存成功`);
-      }catch(error){
-        console.error(`保存清单${thanks.content}时出错`,error);
-      }
-    }
-    console.log("所有清单数据处理完成");
+      ]
+    });
+    await alert.present();
+  }
+
+  async loadThanksList() {
+    if (!this.currentUser) return;
+
+    // 创建查询,只获取当前用户的感恩清单
+    let query = new CloudQuery("ThanksType");
+    query.equalTo("user", {
+      __type: "Pointer",
+      className: "_User",
+      objectId: this.currentUser.id
+    });
+    query.include("user"); // 包含用户信息
+    
+    this.thanksList = await query.find();
   }
   
-  addNewThanks(){
-    console.log("添加清单")
+  async importThanks(){
+  
   }
-    
-    
+  
+  async addNewThanks(){
+ 
+    if (!this.currentUser) {
+      this.showLoginAlert();
+      return;
+    }
+      const alert = await this.alertController.create({
+      header: '添加感恩清单',
+      inputs: [
+        {
+          name: 'content',
+          type: 'textarea',
+          placeholder: '感恩内容'
+        },
+        {
+          name: 'weather',
+          type: 'text',
+          placeholder: '天气 (如: 晴)'
+        },
+        {
+          name: 'mood',
+          type: 'text',
+          placeholder: '心情表情 (如: 😊)'
+        },
+        {
+          name: 'tags',
+          type: 'text',
+          placeholder: '标签 (用逗号分隔, 如: 情感分析,生活仪式感)'
+        },
+        {
+          name: 'reflection',
+          type: 'textarea',
+          placeholder: '反思记录'
+        },
+        {
+          name: 'actionStep',
+          type: 'textarea',
+          placeholder: '行动计划'
+        },
+        {
+          name: 'emotionalImpact',
+          type: 'text',
+          placeholder: '情感影响 (如: 幸福感 + 2)'
+        },
+        {
+          name: 'emotionalJournal',
+          type: 'textarea',
+          placeholder: '情绪日记'
+        }
+      ],
+      buttons: [
+        {
+          text: '取消',
+          role: 'cancel',
+          handler: () => {
+          return true; // 明确返回 true 表示取消操作
+        }
+        },
+        {
+          text: '保存',
+          handler: async (data) => {
+            if (!data.content) {
+              return false; // 阻止关闭
+            }
+            
+            // 获取当前日期时间信息
+            const now = new Date();
+            const weekday = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'][now.getDay()];
+            const date = now.getDate();
+            const hours = now.getHours().toString().padStart(2, '0');
+            const minutes = now.getMinutes().toString().padStart(2, '0');
+            const time = `${hours}:${minutes}`;
+            
+            // 处理标签
+            const tags = data.tags ? data.tags.split(',').map((tag: string) => tag.trim()) : [];
+            
+            // 创建新的感恩清单对象
+            const newThanks = new CloudObject("ThanksType");
+            newThanks.set({
+              Tid: Date.now(), // 使用时间戳作为临时ID
+              date: date,
+              weekday: weekday,
+              time: time,
+              content: data.content,
+              weather: data.weather || '晴',
+              mood: data.mood || '😊',
+              tags: tags,
+              reflection: data.reflection || '',
+              actionStep: data.actionStep || '',
+              emotionalImpact: data.emotionalImpact || '',
+              emotionalJournal: data.emotionalJournal || '',
+              // 关联当前用户
+              user: {
+                __type: "Pointer",
+                className: "_User",
+                objectId: this.currentUser?.id
+              }
+            });
+            
+            try {
+              // 保存到数据库
+              await newThanks.save();
+              
+              // 重新加载列表
+              await this.loadThanksType();
+              
+              // 显示成功提示
+              const successAlert = await this.alertController.create({
+                header: '成功',
+                message: '感恩清单已添加',
+                buttons: ['确定']
+              });
+              await successAlert.present();
+              
+            } catch (error) {
+              console.error('保存失败:', error);
+              const errorAlert = await this.alertController.create({
+                header: '错误',
+                message: '保存失败,请重试',
+                buttons: ['确定']
+              });
+              await errorAlert.present();
+            }
+            return true; // 明确返回 true 表示操作完成
+          }
+        }
+      ]
+    });
+
+    await alert.present();
+  }  
 }

+ 6 - 6
myapp/src/app/tab4/tab4.page.html

@@ -13,23 +13,23 @@
     <div class="profile-header">
         <div class="user-info">
             <div>
-                <div class="user-name">匿名兔ffe</div>
-                <div class="user-id">UID:a15143bcf10c4d...</div>
+                <div class="user-name">{{ currentUser?.get('username') || '匿名用户' }}</div>
+                <div class="user-id">UID:{{ currentUser?.id?.substring(0, 16) || '未登录' }}...</div>
             </div>
-            <button (click)="goLogin('登录')" class="copy-btn">登录</button>
+            <button (click)="goLogin('登录')" class="copy-btn">{{ currentUser ? '已登录' : '登录' }}</button>
         </div>
         
         <div class="stats-container">
             <div class="stat-item">
-                <div class="stat-number">6</div>
+                <div class="stat-number">{{ diaryCount }}</div>
                 <div class="stat-label">日记数量</div>
             </div>
             <div class="stat-item">
-                <div class="stat-number">2</div>
+                <div class="stat-number">{{ recordDays }}</div>
                 <div class="stat-label">记录天数</div>
             </div>
             <div class="stat-item">
-                <div class="stat-number">264</div>
+                <div class="stat-number">{{ totalWords }}</div>
                 <div class="stat-label">总字数</div>
             </div>
         </div>

+ 49 - 2
myapp/src/app/tab4/tab4.page.ts

@@ -1,6 +1,6 @@
 import { Component, OnInit } from '@angular/core';
 import { NavController } from '@ionic/angular';
-
+import { CloudObject, CloudQuery, CloudUser } from 'src/lib/ncloud';
 
 @Component({
   selector: 'app-tab4',
@@ -10,11 +10,58 @@ import { NavController } from '@ionic/angular';
 })
 export class Tab4Page implements OnInit {
 
+  currentUser: CloudUser | null = null;
+  diaryCount: number = 0;
+  recordDays: number = 0;
+  totalWords: number = 0;
+
   constructor(
     private navCtrl:NavController
   ) { }
 
-  ngOnInit() {
+  async ngOnInit() {
+    await this.loadUserData();
+  }
+
+  async loadUserData() {
+    // 获取当前用户
+    this.currentUser = await CloudUser.current();
+    
+    if (this.currentUser) {
+      // 获取用户日记统计
+      await this.getDiaryStats();
+    }
+  }
+
+  async getDiaryStats() {
+    if (!this.currentUser) return;
+    
+    let query = new CloudQuery("Diary");
+    query.equalTo("user", this.currentUser.toPointer());
+    const diaries = await query.find();
+    
+    // 计算统计数据
+    this.diaryCount = diaries.length;
+    this.totalWords = this.calculateTotalWords(diaries);
+    this.recordDays = this.calculateRecordDays(diaries);
+  }
+
+  private calculateTotalWords(diaries: CloudObject[]): number {
+    return diaries.reduce((total, diary) => {
+      const content = diary.get('content') || '';
+      return total + content.length;
+    }, 0);
+  }
+
+  private calculateRecordDays(diaries: CloudObject[]): number {
+    const uniqueDates = new Set();
+    diaries.forEach(diary => {
+      const date = diary.get('date');
+      if (date) {
+        uniqueDates.add(date);
+      }
+    });
+    return uniqueDates.size;
   }
 
   goLogin(user?:string){

+ 9 - 2
myapp/src/lib/ncloud.ts

@@ -215,8 +215,14 @@ export class CloudQuery {
 
 // CloudUser.ts
 export class CloudUser extends CloudObject {
-    static current(): CloudUser | PromiseLike<CloudUser | null> | null {
-      throw new Error('Method not implemented.');
+    // static current(): CloudUser | PromiseLike<CloudUser | null> | null {
+    //   throw new Error('Method not implemented.');
+    // }
+    // 在 CloudUser 类中添加
+    static async current(): Promise<CloudUser | null> {
+        const user = new CloudUser();
+        const current = await user.current();
+        return current ? user : null;
     }
     constructor() {
         super("_User"); // 假设用户类在Parse中是"_User"
@@ -254,6 +260,7 @@ export class CloudUser extends CloudObject {
         // }
         // return result;
     }
+    
 
     /** 登录 */
     async login(username: string, password: string):Promise<CloudUser|null> {