import { Component, OnInit } from '@angular/core';
import { ModalController, NavParams } from '@ionic/angular';
import { DiaryService } from 'src/app/services/diary.service';
import { Diary } from 'src/app/modals/diary.modal';

@Component({
  selector: 'app-edit',
  templateUrl: './edit.page.html',
  styleUrls: ['./edit.page.scss'],
  standalone:false,
})
export class EditPage implements OnInit {
  diary: Diary = {
    id: 0,
    date: '',
    weekday: '',
    time: '',
    content: '',
    weather: '',
    mood: ''
  };
  
  mode: 'create' | 'edit' = 'create';

  constructor(
    private modalCtrl: ModalController,
    private navParams: NavParams,
    private diaryService: DiaryService
  ) {}

  ngOnInit() {
    const currentDate = new Date();
    const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
    
    // Set default values
    this.diary.date = currentDate.getDate().toString();
    this.diary.weekday = weekdays[currentDate.getDay()];
    this.diary.time = `${currentDate.getHours()}:${currentDate.getMinutes().toString().padStart(2, '0')}`;
    
    // Check if we're editing an existing diary
    const diaryToEdit = this.navParams.get('diary');
    if (diaryToEdit) {
      this.diary = { ...diaryToEdit };
      this.mode = 'edit';
    }
  }

  async save() {
    if (this.mode === 'create') {
      // Generate a new ID (in a real app, this would be handled by a backend)
      const diaries = await this.diaryService.getDiaries();
      this.diary.id = diaries.length > 0 ? Math.max(...diaries.map((d: { id: any; }) => d.id)) + 1 : 1;
      
      await this.diaryService.addDiary(this.diary);
    } else {
      await this.diaryService.updateDiary(this.diary);
    }
    
    this.modalCtrl.dismiss({ saved: true });
    console.log("保存成功")
  }

  cancel() {
    this.modalCtrl.dismiss({ saved: false });
  }
}