import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable, of } from 'rxjs';
import { tap, catchError } from 'rxjs/operators';
import { HealthReport } from '../health-record/health-record.page';

// 定义用户信息接口
export interface UserInfo {
  username: string;
  email?: string;
  phone?: string;
  gender?: string;
  birthday?: string | null;
  userAvatar?: string; // 头像的Base64编码字符串
  userType?: string;
  reports?: HealthReport[];
  medicalHistory?: string; // 添加 medicalHistory 字段 // 添加 reports 字段
}

@Injectable({
  providedIn: 'root'
})
export class UserService {
         userInfoSubject = new BehaviorSubject<UserInfo | null>(null);
  public userInfo$ = this.userInfoSubject.asObservable();

  constructor() {
    this.loadUserInfo(); // 应用启动时加载本地存储的用户信息
  }

  async updateUserInfo(userInfo: Partial<UserInfo>): Promise<void> {
    try {
      const currentUserInfo = this.userInfoSubject.value || {}; // 如果为空则提供一个空对象
      const updatedUserInfo: UserInfo = {
        username: userInfo.username ?? (currentUserInfo as UserInfo).username ?? '', // 确保 username 不会是 undefined
        email: userInfo.email ?? (currentUserInfo as UserInfo).email,
        phone: userInfo.phone ?? (currentUserInfo as UserInfo).phone,
        gender: userInfo.gender ?? (currentUserInfo as UserInfo).gender,
        birthday: userInfo.birthday ?? (currentUserInfo as UserInfo).birthday,
        userAvatar: userInfo.userAvatar ?? (currentUserInfo as UserInfo).userAvatar ?? '../../assets/images/user-avatar.png',
        userType: userInfo.userType ?? (currentUserInfo as UserInfo).userType ?? '普通用户'
      };

      console.log('Updating userInfo:', updatedUserInfo);

      await this.saveUserInfoToLocalStorage(updatedUserInfo);
      this.userInfoSubject.next(updatedUserInfo);
    } catch (error) {
      console.error('Failed to update user info:', error);
      throw error;
    }
  }

  getUserInfo(): Observable<UserInfo | null> {
    return this.userInfo$.pipe(
      tap(userInfo => {
        if (!userInfo) {
          this.loadUserInfo(); // 如果没有用户信息，则尝试加载
        }
      }),
      catchError(error => {
        console.error('Error fetching user info:', error);
        return of(null); // 返回 null 或者你可以选择返回一个默认用户对象
      })
    );
  }

  private async saveUserInfoToLocalStorage(userInfo: UserInfo): Promise<void> {
    console.log('Saving userInfo to localStorage:', userInfo);
    try {
      localStorage.setItem('userInfo', JSON.stringify(userInfo));
    } catch (error) {
      console.error('Failed to save userInfo to localStorage:', error);
      throw error;
    }
  }
  
  private async loadUserInfo(): Promise<void> {
    try {
      const storedUserInfo = localStorage.getItem('userInfo');
      if (storedUserInfo) {
        const parsedUserInfo: UserInfo = JSON.parse(storedUserInfo);
  
        // 确保所有字段都有默认值
        this.userInfoSubject.next({
          ...parsedUserInfo,
          username: parsedUserInfo.username || '',
          userAvatar: parsedUserInfo.userAvatar || '../../assets/images/user-avatar.png',
          userType: parsedUserInfo.userType || '普通用户',
          gender: parsedUserInfo.gender || '',
          phone: parsedUserInfo.phone || '',
          birthday: parsedUserInfo.birthday ?? null,
          email: parsedUserInfo.email || '',
          reports: parsedUserInfo.reports || [] // 确保 reports 字段存在
        });
      } else {
        // 设置默认用户信息，确保所有字段都有值
        this.userInfoSubject.next({
          username: '张三',
          userAvatar: '../../assets/images/user-avatar.png',
          userType: '普通用户',
          gender: 'male',
          phone: '123456789',
          birthday: '2003-03-06',
          email: '33333@333',
          medicalHistory: '高血压',
          reports: [ // 默认报告
            { title: '年度体检', date: new Date(), details: '血压正常，血糖略高', type: 'annual' },
            { title: '眼科检查', date: new Date('2024-01-01'), details: '视力良好，无异常', type: 'eye' }
          ]
        });
      }
    } catch (error) {
      console.error('Failed to parse userInfo from localStorage:', error);
      this.userInfoSubject.next(null);
    }
  }
}