Browse Source

0210348-界面刷新逻辑优化

0210348 4 months ago
parent
commit
c03d22987b

+ 3 - 3
src/app/ai-chat/ai-chat.page.html

@@ -1,6 +1,6 @@
 <ion-header>
   <ion-toolbar class="title">
-    <ion-title >历史聊天</ion-title>
+    <ion-title class="ion-text-center">历史聊天</ion-title>
   </ion-toolbar>
 </ion-header>
 
@@ -11,8 +11,8 @@
       <ion-item *ngFor="let chat of chatHistory" (click)="goToChat(chat.chatId)" class="chat-item">
         <div class="avatar">{{ chat.username[0].toUpperCase() }}</div>
         <ion-label>
-          <h2>{{ chat.userChat.slice(0,18) }}</h2>
-          <p>{{ chat.aiChat.slice(0,18) }}</p>
+          <h2>{{ chat.userChat.slice(0, 18) }}</h2>
+          <p>{{ chat.aiChat.slice(0, 18) }}</p>
         </ion-label>
       </ion-item>
     </ion-list>

+ 85 - 42
src/app/ai-chat/ai-chat.page.ts

@@ -1,12 +1,11 @@
-import { Component, OnInit,OnDestroy } from '@angular/core';
-import { NavController } from '@ionic/angular';
+import { Component, OnInit } from '@angular/core';
+import { AlertController, NavController } from '@ionic/angular';
 import * as Parse from 'parse';
-import { interval, Subscription } from 'rxjs';
 
 interface ChatHistoryItem {
-  chatId: number; // Adjust chatId to number type
+  chatId: number;
   username: string;
-  userChatOrder: number; // Add userChatOrder field
+  userChatOrder: number;
   userChat: string;
   aiChat: string;
 }
@@ -18,55 +17,95 @@ interface ChatHistoryItem {
 })
 export class AiChatPage implements OnInit {
   chatHistory: ChatHistoryItem[] = [];
-  private loadChatHistorySubscription: Subscription | undefined;
+  username: string = ''; // 用户名
+  load: boolean | undefined;
 
-  constructor(private navCtrl: NavController) {}
+  constructor(private navCtrl: NavController, private alertController: AlertController) {}
 
-  ngOnInit() {
+  ngOnInit() {}
+
+  ionViewDidEnter() {
+    this.loadUserData();
     this.loadChatHistory();
-    //每隔一秒检测登录状况
-    this.loadChatHistorySubscription = interval(1000).subscribe(() => {
-      this.loadChatHistory();
-      //console.log(this.username);
-    });
   }
-  ngOnDestroy() {
-    if (this.loadChatHistorySubscription) {
-      this.loadChatHistorySubscription.unsubscribe();
+
+  async loadUserData() {
+    const currentUser = Parse.User.current();
+    if (currentUser) {
+      this.username = currentUser.getUsername()!;
+    } else {
+      this.username = '未登录';
     }
+    console.log("tab-history:" + this.username);
+    this.CheckUser();
+  }
+
+  async CheckUser() {
+    if (this.username == '未登录') {
+      this.load = false;
+      this.presentLoginAlert();
+      return;
+    } else {
+      this.load = true;
+    }
+  }
+
+  async presentLoginAlert() {
+    const alert = await this.alertController.create({
+      header: '未登录',
+      message: '请先登录以继续操作',
+      buttons: [
+        {
+          text: '取消',
+          role: 'cancel'
+        },
+        {
+          text: '去登录',
+          handler: () => {
+            this.navCtrl.navigateForward('/user/login');
+          }
+        }
+      ]
+    });
+    await alert.present();
   }
 
   async loadChatHistory() {
     try {
       const Chat = Parse.Object.extend('ai_chat');
       const query = new Parse.Query(Chat);
+      query.equalTo('username', this.username); // 只获取当前用户名的聊天记录
       query.select('chatId', 'username', 'userChatOrder', 'userChat', 'aiChat');
-      query.descending('createdAt'); // Ensure latest chat is fetched first
+      query.descending('createdAt');
       const results = await query.find();
 
-      const groupedChats: { [key: number]: ChatHistoryItem } = results.reduce((acc: { [key: number]: ChatHistoryItem }, chat: any) => {
-        const chatId = chat.get('chatId');
-        if (!acc[chatId]) {
-          acc[chatId] = {
-            chatId,
-            username: chat.get('username'),
-            userChatOrder: chat.get('userChatOrder'),
-            userChat: chat.get('userChat'),
-            aiChat: chat.get('aiChat')
-          };
-        }
-        return acc;
-      }, {});
+      const groupedChats: { [key: number]: ChatHistoryItem } = results.reduce(
+        (acc: { [key: number]: ChatHistoryItem }, chat: any) => {
+          const chatId = chat.get('chatId');
+          if (!acc[chatId]) {
+            acc[chatId] = {
+              chatId,
+              username: chat.get('username'),
+              userChatOrder: chat.get('userChatOrder'),
+              userChat: chat.get('userChat'),
+              aiChat: chat.get('aiChat'),
+            };
+          }
+          return acc;
+        },
+        {}
+      );
 
       this.chatHistory = Object.values(groupedChats).map(chat => {
-        // Filter to only keep the first message for each chatId
-        const firstMessage = results.find(item => item.get('chatId') === chat.chatId && item.get('userChatOrder') === 1);
+        const firstMessage = results.find(
+          item => item.get('chatId') === chat.chatId && item.get('userChatOrder') === 1
+        );
         return {
           chatId: chat.chatId,
           username: firstMessage?.get('username') || chat.username,
           userChatOrder: firstMessage?.get('userChatOrder') || chat.userChatOrder,
           userChat: firstMessage?.get('userChat') || chat.userChat,
-          aiChat: firstMessage?.get('aiChat') || chat.aiChat
+          aiChat: firstMessage?.get('aiChat') || chat.aiChat,
         };
       });
 
@@ -77,19 +116,23 @@ export class AiChatPage implements OnInit {
 
   goToChat(chatId: number) {
     this.navCtrl.navigateForward(`/tabs/tab2`, {
-      queryParams: { chatId: chatId.toString() } // Ensure chatId is passed as string
+      queryParams: { chatId: chatId.toString() },
     });
   }
 
   async startNewChat() {
-    const Chat = Parse.Object.extend('ai_chat');
-    const query = new Parse.Query(Chat);
-    query.descending('chatId');
-    const latestChat = await query.first();
-    const newChatId = latestChat ? latestChat.get('chatId') + 1 : 1;
+    this.loadUserData();
+    if (this.load) {
+      const Chat = Parse.Object.extend('ai_chat');
+      const query = new Parse.Query(Chat);
+      query.descending('chatId');
+      query.equalTo('username', this.username); // 确保chatId生成基于当前用户的历史记录
+      const latestChat = await query.first();
+      const newChatId = latestChat ? latestChat.get('chatId') + 1 : 1;
 
-    this.navCtrl.navigateForward(`/tabs/tab2`, {
-      queryParams: { chatId: newChatId.toString() } // Ensure chatId is passed as string
-    });
+      this.navCtrl.navigateForward(`/tabs/tab2`, {
+        queryParams: { chatId: newChatId.toString() },
+      });
+    }
   }
 }

+ 40 - 36
src/app/app-routing.module.ts

@@ -1,38 +1,42 @@
-import { NgModule } from '@angular/core';
-import { PreloadAllModules, RouterModule, Routes } from '@angular/router';
-
-const routes: Routes = [
-  {
-    path: '',
-    loadChildren: () => import('./tabs/tabs.module').then(m => m.TabsPageModule)
-  },
-  {
-    path: 'user',
-    loadChildren: () => import('../modules/user/user.module').then(m => m.UserModule)
-  },
-  {
-    path: "tree",
-    loadChildren: () => import('../modules/tab/tree/tree.module').then(m => m.TreePageModule)
-  },
-  {
-    path: 'bounty-store',
-    loadChildren: () => import('../app/bounty-store/bounty-store.module').then(mod => mod.BountyStorePageModule)
+import { NgModule } from '@angular/core';
+import { PreloadAllModules, RouterModule, Routes } from '@angular/router';
+
+const routes: Routes = [
+  {
+    path: '',
+    loadChildren: () => import('./tabs/tabs.module').then(m => m.TabsPageModule)
+  },
+  {
+    path: 'user',
+    loadChildren: () => import('../modules/user/user.module').then(m => m.UserModule)
+  },
+  {
+    path: "tree",
+    loadChildren: () => import('../modules/tab/tree/tree.module').then(m => m.TreePageModule)
+  },
+  {
+    path: 'bounty-store',
+    loadChildren: () => import('../app/bounty-store/bounty-store.module').then(mod => mod.BountyStorePageModule)
+  },
+  {
+    path: 'memo',
+    loadChildren: () => import('../app/memo/memo.module').then(m => m.MemoPageModule)
+  },
+  {
+    path: 'ai-chat',
+    loadChildren: () => import('./ai-chat/ai-chat.module').then( m => m.AiChatPageModule)
+  },
  {
+    path: 'home',
+    loadChildren: () => import('./home/home.module').then( m => m.HomePageModule)
   },
-  {
-    path: 'memo',
-    loadChildren: () => import('../app/memo/memo.module').then(m => m.MemoPageModule)
-  },
-  {
-    path: 'ai-chat',
-    loadChildren: () => import('./ai-chat/ai-chat.module').then( m => m.AiChatPageModule)
-  },
-
 
-];
-@NgModule({
-  imports: [
-    RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules })
-  ],
-  exports: [RouterModule]
-})
-export class AppRoutingModule {}
+
+
+];
+@NgModule({
+  imports: [
+    RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules })
+  ],
+  exports: [RouterModule]
+})
+export class AppRoutingModule {}

+ 17 - 0
src/app/home/home-routing.module.ts

@@ -0,0 +1,17 @@
+import { NgModule } from '@angular/core';
+import { Routes, RouterModule } from '@angular/router';
+
+import { HomePage } from './home.page';
+
+const routes: Routes = [
+  {
+    path: '',
+    component: HomePage
+  }
+];
+
+@NgModule({
+  imports: [RouterModule.forChild(routes)],
+  exports: [RouterModule],
+})
+export class HomePageRoutingModule {}

+ 20 - 0
src/app/home/home.module.ts

@@ -0,0 +1,20 @@
+import { NgModule } from '@angular/core';
+import { CommonModule } from '@angular/common';
+import { FormsModule } from '@angular/forms';
+
+import { IonicModule } from '@ionic/angular';
+
+import { HomePageRoutingModule } from './home-routing.module';
+
+import { HomePage } from './home.page';
+
+@NgModule({
+  imports: [
+    CommonModule,
+    FormsModule,
+    IonicModule,
+    HomePageRoutingModule
+  ],
+  declarations: [HomePage]
+})
+export class HomePageModule {}

+ 13 - 0
src/app/home/home.page.html

@@ -0,0 +1,13 @@
+<ion-header [translucent]="true">
+  <ion-toolbar>
+    <ion-title>home</ion-title>
+  </ion-toolbar>
+</ion-header>
+
+<ion-content [fullscreen]="true">
+  <ion-header collapse="condense">
+    <ion-toolbar>
+      <ion-title size="large">home</ion-title>
+    </ion-toolbar>
+  </ion-header>
+</ion-content>

+ 0 - 0
src/app/home/home.page.scss


+ 17 - 0
src/app/home/home.page.spec.ts

@@ -0,0 +1,17 @@
+import { ComponentFixture, TestBed } from '@angular/core/testing';
+import { HomePage } from './home.page';
+
+describe('HomePage', () => {
+  let component: HomePage;
+  let fixture: ComponentFixture<HomePage>;
+
+  beforeEach(() => {
+    fixture = TestBed.createComponent(HomePage);
+    component = fixture.componentInstance;
+    fixture.detectChanges();
+  });
+
+  it('should create', () => {
+    expect(component).toBeTruthy();
+  });
+});

+ 15 - 0
src/app/home/home.page.ts

@@ -0,0 +1,15 @@
+import { Component, OnInit } from '@angular/core';
+
+@Component({
+  selector: 'app-home',
+  templateUrl: './home.page.html',
+  styleUrls: ['./home.page.scss'],
+})
+export class HomePage implements OnInit {
+
+  constructor() { }
+
+  ngOnInit() {
+  }
+
+}

+ 20 - 27
src/app/tab1/tab1.page.html

@@ -8,64 +8,57 @@
     </ion-toolbar>
   </ion-header>
     
-   <!-- 方框 -->
-   <ion-card (click)="openEditModal()">
+  <!-- 方框 -->
+  <ion-card (click)="openEditModal()">
     <ion-card-content>
       <ion-grid>
         <ion-row>
           <ion-col size="3">
             <div class="info-box">初始</div>
-            <div class="info-value">{{ initial }}</div>
+            <div class="info-value">{{ initial }}KG</div>
           </ion-col>
           <ion-col size="3">
             <div class="info-box">当前</div>
-            <div class="info-value">{{ current }}</div>
+            <div class="info-value">{{ current }}KG</div>
           </ion-col>
           <ion-col size="3">
             <div class="info-box">目标</div>
-            <div class="info-value">{{ target }}</div>
+            <div class="info-value">{{ target }}KG</div>
           </ion-col>
           <ion-col size="3">
             <div class="info-box">赏金</div>
-            <div class="info-value">{{ reward }}</div>
+            <div class="info-value">{{ reward }}</div>
           </ion-col>
         </ion-row>
       </ion-grid>
     </ion-card-content>
   </ion-card>
   
-<!-- 3D效果的圆 -->
-<div class="wave-container" (click)="navigateToTreePage()">
-  <div class="wave-circle">
-    <div class="wave">
-      <div class="wave-inner">
-        <span class="start-self-discipline">开始自律</span>
+  <!-- 3D效果的圆 -->
+  <div class="wave-container" (click)="navigateToTreePage()">
+    <div class="wave-circle">
+      <div class="wave">
+        <div class="wave-inner">
+          <span class="start-self-discipline">开始自律</span>
+        </div>
       </div>
     </div>
   </div>
-</div>
-
-
-
 
   <!-- 每日小习惯 -->
-<div class="daily-habit">
-  <div class="daily-habit-line"></div>
-  <div class="daily-habit-text">每日小习惯</div>
-</div>
+  <div class="daily-habit">
+    <div class="daily-habit-line"></div>
+    <div class="daily-habit-text">每日小习惯</div>
+  </div>
 
-  
-   <!-- 每日小习惯按钮 -->
-   <div class="button-container">
+  <!-- 每日小习惯按钮 -->
+  <div class="button-container">
     <ion-button *ngFor="let button of buttons; let i = index" (click)="onButtonClick(i)" [color]="button.color" class="custom-button">
       <ion-icon [name]="button.icon"></ion-icon>
       <p>{{ button.text }}</p>
     </ion-button>
   </div>
   <div class="habit-text-div">
-      <p class="habit-text centered" [ngClass]="{'success-text': allButtonsSuccess, 'failure-text': anyButtonFailure}">{{ habitText }}</p>
+    <p class="habit-text centered" [ngClass]="{'success-text': allButtonsSuccess, 'failure-text': anyButtonFailure}">{{ habitText }}</p>
   </div>
-
 </ion-content>
-  
-

+ 34 - 38
src/app/tab1/tab1.page.ts

@@ -1,44 +1,34 @@
-import { Component, OnInit,OnDestroy } from '@angular/core';
+import { Component, OnInit, OnDestroy } from '@angular/core';
 import { AlertController, NavController } from '@ionic/angular';
 import { Router } from '@angular/router';
 import * as Parse from 'parse';
-import { interval, Subscription } from 'rxjs';
 
 @Component({
   selector: 'app-tab1',
   templateUrl: 'tab1.page.html',
   styleUrls: ['tab1.page.scss']
 })
-export class Tab1Page implements OnInit,OnDestroy {
-  initial: string = '0KG';
-  current: string = '0KG';
-  target: string = '0KG';
-  reward: string = '0元';
+export class Tab1Page implements OnInit, OnDestroy {
+  initial: number = 0;
+  current: number = 0;
+  target: number = 0;
+  reward: number = 0;
   username: string = ''; // 当前用户的用户名
   blueColor: boolean = false;
-  private loadUserDataSubscription: Subscription | undefined;
   
   constructor(
     private alertController: AlertController,
     private router: Router,
     private navCtrl: NavController,
-    
   ) {}
 
-  ngOnInit() {
+  ngOnInit() {}
+
+  ionViewDidEnter() {
     this.loadUserData();
-    //每隔一秒检测登录状况
-    this.loadUserDataSubscription = interval(1000).subscribe(() => {
-      this.loadUserData();
-      //console.log(this.username);
-    });
   }
 
-  ngOnDestroy() {
-    if (this.loadUserDataSubscription) {
-      this.loadUserDataSubscription.unsubscribe();
-    }
-  }
+  ngOnDestroy() {}
 
   async loadUserData() {
     const currentUser = Parse.User.current();
@@ -49,6 +39,7 @@ export class Tab1Page implements OnInit,OnDestroy {
       this.username = '未登录';
       this.loadData();
     }
+    console.log("tab1:" + this.username);
   }
 
   async loadData() {
@@ -57,16 +48,20 @@ export class Tab1Page implements OnInit,OnDestroy {
       query.equalTo('username', this.username); // 查找当前用户的数据
       const weightStatus = await query.first();
       if (weightStatus) {
-        this.initial = weightStatus.get('initial') + 'KG' || '--KG';
-        this.current = weightStatus.get('current') + 'KG' || '--KG';
-        this.target = weightStatus.get('target') + 'KG' || '--KG';
-        this.reward = weightStatus.get('reward') + '元' || '--元';
+        this.initial = weightStatus.get('initial') || 0;
+        this.current = weightStatus.get('current') || 0;
+        this.target = weightStatus.get('target') || 0;
+        this.reward = this.calculateReward(this.initial, this.target);
       }
     } catch (error) {
       console.error('Error loading data', error);
     }
   }
 
+  calculateReward(initial: number, target: number): number {
+    return (initial - target) * 10;
+  }
+
   async openEditModal() {
     if (this.username == '未登录') {
       // 如果用户未登录,则显示登录提示
@@ -76,30 +71,32 @@ export class Tab1Page implements OnInit,OnDestroy {
 
     const alert = await this.alertController.create({
       header: '编辑体重信息',
+      subHeader: '请根据您的需求编辑以下信息',
       inputs: [
         {
           name: 'initial',
-          type: 'text',
+          type: 'number',
           placeholder: '初始',
-          value: this.initial.replace('KG', '')
+          value: this.initial.toString()
         },
         {
           name: 'current',
-          type: 'text',
+          type: 'number',
           placeholder: '当前',
-          value: this.current.replace('KG', '')
+          value: this.current.toString()
         },
         {
           name: 'target',
-          type: 'text',
+          type: 'number',
           placeholder: '目标',
-          value: this.target.replace('KG', '')
+          value: this.target.toString()
         },
         {
           name: 'reward',
-          type: 'text',
+          type: 'number',
           placeholder: '赏金',
-          value: this.reward.replace('元', '')
+          value: this.reward.toString(),
+          disabled: true // 禁用输入框,显示但不能编辑
         }
       ],
       buttons: [
@@ -117,11 +114,12 @@ export class Tab1Page implements OnInit,OnDestroy {
               if (!weightStatus) {
                 weightStatus = new Parse.Object('weight_status');
               }
+              const rewardValue = this.calculateReward(Number(data.initial), Number(data.target));
               weightStatus.set('username', this.username);
-              weightStatus.set('initial', data.initial);
-              weightStatus.set('current', data.current);
-              weightStatus.set('target', data.target);
-              weightStatus.set('reward', data.reward);
+              weightStatus.set('initial', Number(data.initial));
+              weightStatus.set('current', Number(data.current));
+              weightStatus.set('target', Number(data.target));
+              weightStatus.set('reward', rewardValue);
               await weightStatus.save();
               this.loadData(); // 更新本地数据
             } catch (error) {
@@ -160,7 +158,6 @@ export class Tab1Page implements OnInit,OnDestroy {
     this.blueColor = !this.blueColor;
   }
 
-
   //每日习惯按钮颜色变化
   buttons = [
     { text: '足量饮水', color: 'light', icon: 'water' },
@@ -208,7 +205,6 @@ export class Tab1Page implements OnInit,OnDestroy {
     return this.buttons.some(btn => btn.color === 'danger');
   }
 
-
   navigateToTreePage() {
     this.router.navigate(['/tabs/tree']);
   }

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

@@ -23,7 +23,7 @@
   <ion-toolbar>
     <ion-item>
       <ion-input [(ngModel)]="userInput" placeholder="输入消息..."></ion-input>
-      <ion-button (click)="sendMessage()" class="sendutton">发送</ion-button>
+      <ion-button (click)="sendMessage()" class="sendButton">发送</ion-button>
     </ion-item>
   </ion-toolbar>
 </ion-footer>

+ 6 - 1
src/app/tab2/tab2.page.ts

@@ -25,7 +25,6 @@ export class Tab2Page implements OnInit {
   }
 
   ngOnInit() {
-    this.loadUserData(); // 加载用户名
     this.route.queryParams.subscribe(params => {
       if (params['chatId']) {
         this.chatId = +params['chatId'];
@@ -37,6 +36,11 @@ export class Tab2Page implements OnInit {
     });
   }
 
+  ionViewDidEnter() {
+    //检测登录状况
+    this.loadUserData();
+  }
+
   async loadUserData() {
     const currentUser = Parse.User.current();
     if (currentUser) {
@@ -44,6 +48,7 @@ export class Tab2Page implements OnInit {
     } else {
       this.username = '未登录';
     }
+    console.log("tab-ai:"+this.username);
   }
 
   async loadChatHistory(chatId: number | null) {

+ 1 - 1
src/app/tab3/tab3.page.ts

@@ -24,7 +24,7 @@ export class Tab3Page {
   async logout() {
     try {
       await Parse.User.logOut();
-      this.navCtrl.navigateRoot('/tabs/calendar'); // 登出后跳转到登录界面
+      this.navCtrl.navigateRoot('/tabs/go-load'); // 登出后跳转到登录界面
     } catch (error: any) {
       console.error("Logout failed:", error);
       const toast = await this.toastController.create({

+ 1 - 1
src/app/tabs/tabs-routing.module.ts

@@ -24,7 +24,7 @@ const routes: Routes = [
         loadChildren: () => import('../tab3/tab3.module').then(m => m.Tab3PageModule)
       },
       {
-        path: 'calendar',
+        path: 'go-load',
         loadChildren: () => import('../../modules/user/mine/mine.module').then(mod => mod.MinePageModule)
       },
       {

+ 1 - 1
src/app/tabs/tabs.page.ts

@@ -18,7 +18,7 @@ export class TabsPage {
       this.navCtrl.navigateForward('/tabs/tab3');
     } else {
       // 如果未登录,跳转到“登录”界面
-      this.navCtrl.navigateForward('/tabs/calendar');
+      this.navCtrl.navigateForward('/tabs/go-load');
     }
   }
 }

+ 7 - 0
src/modules/tab/tree/tree.page.ts

@@ -22,6 +22,13 @@ export class TreePage implements OnInit, OnDestroy {
     // No need to start the timer here; it starts when user interacts with it
   }
 
+  ionViewDidEnter() {
+    this.stopTimer();
+    this.minutes = 0;
+    this.seconds = 0;
+    console.log("tab-timer")
+  }
+
   startTimer() {
     this.stopTimer();
     console.log('Timer started');