import { Component, OnInit, OnDestroy } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { NavController } from '@ionic/angular';
import { Subscription } from 'rxjs';
import { UserService, UserInfo } from '../services/user.service';

// 定义接口
export interface HealthReport {
  id?: string; // 唯一标识符
  title: string;
  date: Date;
  details: string;
  type: 'annual' | 'eye'; // 添加类型字段
}

@Component({
  selector: 'app-health-record',
  templateUrl: './health-record.page.html',
  styleUrls: ['./health-record.page.scss'],
})
export class HealthRecordPage implements OnInit, OnDestroy {
  healthRecord = {
    name: '',
    gender: '',
    age: null as number | null,
    contact: '',
    medicalHistory: '',
    reports: [] as HealthReport[]
  };

  private userSubscription: Subscription | null = null;

  constructor(
    private route: ActivatedRoute,
    private router: Router,
    private navCtrl: NavController,
    private userService: UserService
  ) {}

  ngOnInit() {
    this.userSubscription = this.userService.userInfo$.subscribe(userInfo => {
      if (userInfo) {
        this.updateHealthRecordFromUserInfo(userInfo);
      }
    });
    this.loadHealthRecord();
  }

  ngOnDestroy() {
    if (this.userSubscription) {
      this.userSubscription.unsubscribe();
    }
  }

  loadHealthRecord() {
    console.log('Loading health record...');
    
    const userInfo = this.userService.userInfoSubject.value;
    console.log('Current user info:', userInfo); // 新增日志
    
    if (userInfo) {
      this.updateHealthRecordFromUserInfo(userInfo);
      console.log('Updated health record from user info:', this.healthRecord);
    } else {
      // 如果没有用户信息，则加载默认数据或等待用户信息加载
      if (!this.healthRecord.reports || this.healthRecord.reports.length === 0) {
        this.healthRecord = {
          name: '张三',
          gender: 'male',
          age: 30,
          contact: '12345678901',
          medicalHistory: '高血压',
          reports: [
            { title: '年度体检', date: new Date(), details: '血压正常，血糖略高', type: 'annual' },
            { title: '眼科检查', date: new Date('2024-01-01'), details: '视力良好，无异常', type: 'eye' }
          ]
        };
        console.log('Loaded default health record:', this.healthRecord);
      }
    }
  }

  updateHealthRecordFromUserInfo(userInfo: UserInfo) {
    this.healthRecord.name = userInfo.username || this.healthRecord.name || '';
    this.healthRecord.gender = userInfo.gender || this.healthRecord.gender || '';
    this.healthRecord.contact = userInfo.phone || this.healthRecord.contact || '';
  
    // 计算年龄（假设 birthday 是 ISO 8601 格式的字符串）
    if (userInfo.birthday) {
      const birthDate = new Date(userInfo.birthday);
      const today = new Date();
      let age = today.getFullYear() - birthDate.getFullYear();
      const m = today.getMonth() - birthDate.getMonth();
      if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
        age--;
      }
      this.healthRecord.age = age;
    } else {
      this.healthRecord.age = this.healthRecord.age || null;
    }
  
    // 更新其他相关字段...
    this.healthRecord.medicalHistory = userInfo.medicalHistory || this.healthRecord.medicalHistory || '';
  
    // 如果 userInfo 包含 reports，则合并新旧报告，但避免重复
    if (userInfo.reports && Array.isArray(userInfo.reports)) {
      this.healthRecord.reports = [
        ...this.healthRecord.reports,
        ...userInfo.reports.filter(newReport => 
          !this.healthRecord.reports.some(oldReport => oldReport.title === newReport.title)
        )
      ];
    }
  }

  doRefresh(event: any) {
    console.log('Begin async operation');
    setTimeout(() => {
      console.log('Async operations have ended');
      event.target.complete();
    }, 1000);
  }

  editBasicInfo() {
    // 导航到编辑基本信息页面
    this.navCtrl.navigateForward('/edit-profile');
  }

  addNewReport() {
    // 导航到添加新体检报告页面
    this.navCtrl.navigateForward('/add-checkup');
  }

  viewReport(index: number) {
    // 查看具体的体检报告
    const report = this.healthRecord.reports[index];
    console.log('Viewing report:', report);

    // 根据报告类型导航到相应的页面
    if (report.type === 'annual') {
      this.navCtrl.navigateForward(`/annual-checkup/${index}`);
    } else if (report.type === 'eye') {
      this.navCtrl.navigateForward(`/eye-exam/${index}`);
    } else {
      console.error('Unknown report type:', report.type);
    }
  }
}