import { Component, OnInit } from '@angular/core';
import { ModalController } from '@ionic/angular';
import { CaseDetailPage } from '../case-detail/case-detail.page';

@Component({
  selector: 'app-case',
  templateUrl: './case.page.html',
  styleUrls: ['./case.page.scss'],
})
export class CasePage implements OnInit {

  cases: any[] = [
    { title: '高血压', date: new Date('2024-01-15') },
    { title: '糖尿病', date: new Date('2024-02-20') }
    // 更多初始病例...
  ];

  constructor(private modalCtrl: ModalController) {}

  ngOnInit() {
    this.loadCases();
  }

  // 加载病例数据
  loadCases() {
    const storedCases = localStorage.getItem('cases');
    if (storedCases) {
      this.cases = JSON.parse(storedCases);
    }
  }

  // 保存病例数据
  saveCases() {
    localStorage.setItem('cases', JSON.stringify(this.cases));
  }

  addNewCase() {
    this.openCaseDetailModal(null);
  }

  viewCaseDetails(index: number) {
    this.openCaseDetailModal(this.cases[index], index);
  }

  deleteCase(index: number) {
    this.cases.splice(index, 1);
    this.saveCases(); // 删除病例后立即保存更改
  }

  private async openCaseDetailModal(caseData?: any, index?: number) {
    const modal = await this.modalCtrl.create({
      component: CaseDetailPage,
      componentProps: { case: caseData, index: index }
    });

    modal.onDidDismiss().then((data) => {
      if (data.data && data.data.case) {
        if (data.data.index !== undefined) {
          this.cases[data.data.index] = data.data.case;
        } else {
          this.cases.push(data.data.case);
        }
        this.saveCases(); // 更新或添加病例后保存更改
      }
    });

    return await modal.present();
  }
}