// src/app/tab5/tab5.page.ts
import { Component, OnDestroy } from '@angular/core';
import { Geolocation } from '@capacitor/geolocation';
import { AlertController } from '@ionic/angular';

@Component({
  selector: 'app-tab5',
  templateUrl: 'tab5.page.html',
  styleUrls: ['tab5.page.scss'],
  standalone: false,
})
export class Tab5Page implements OnDestroy {
  isRunning: boolean = false;  // 新增运行状态
  isPaused: boolean = false;   // 新增暂停状态
  
  getTotalProgress(): number {
    const total = this.exercises.reduce((sum, ex) => sum + ex.progress, 0);
    return Math.round(total / this.exercises.length);
  }
  currentTime = '00:00';  // 确保时间格式初始化正确
  totalTime = '45:00';
  heartRate = 120;
  activeCalorie = 0;
  basalCalorie = 72;
  currentLocation = '定位中...';
  showAlert = false;
  alertMessage = '';
  timer: any;
  
  exercises = [
    { name: '标准深蹲', duration: '3组×15次', progress: 65, muscle: '下肢综合' },
    { name: '杠铃卧推', duration: '4组×12次', progress: 40, muscle: '胸部' },
    { name: '引体向上', duration: '3组×8次', progress: 25, muscle: '背部' }
  ];

  constructor(private alertCtrl: AlertController) {
    this.startWorkout();
    this.getLocation();
  }

  async getLocation() {
    try {
      const coordinates = await Geolocation.getCurrentPosition();
      this.currentLocation = 
        `纬度: ${coordinates.coords.latitude.toFixed(4)}, 经度: ${coordinates.coords.longitude.toFixed(4)}`;
    } catch (error) {
      this.currentLocation = '定位服务不可用';
    }
  }

  // 新增控制方法
  pauseWorkout() {
    this.isPaused = true;
    clearInterval(this.timer);
  }

  resumeWorkout() {
    this.isPaused = false;
    this.startWorkout();
  }

  endWorkout() {
    this.isRunning = false;
    this.isPaused = false;
    clearInterval(this.timer);
    this.currentTime = '00:00';
    this.activeCalorie = 0;
  }

  startWorkout() {
    this.isRunning = true;  // 添加运行状态标记
    let seconds = 0;
    this.timer = setInterval(() => {
      if (!this.isPaused) {  // 添加暂停判断
        seconds++;
        this.currentTime = 
          `${Math.floor(seconds/60).toString().padStart(2,'0')}:${(seconds%60).toString().padStart(2,'0')}`;
        this.activeCalorie = Math.round(seconds * 0.15);
      }
    }, 1000);
  }

  async triggerAlert(title: string, message: string) {
    this.showAlert = true;
    const alert = await this.alertCtrl.create({
      header: 'AI管家警告',
      subHeader: title,
      message: message,
      cssClass: 'risk-alert',
      buttons: ['知道了']
    });
    await alert.present();
  }

  ngOnDestroy() {
    clearInterval(this.timer);
  }
}