import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable, of, throwError } from 'rxjs';
import { tap, catchError } from 'rxjs/operators';
import { HealthReport } from '../health-record/health-record.page';
import { environment } from 'src/environments/environment';
import { HttpClient, HttpHeaders } from '@angular/common/http';

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

export interface User {
  username: string;
  password: string;
  // 可以根据需要添加更多的用户属性
}

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

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

  async updateUserInfo(userInfo: Partial<UserInfo>): Promise<void> {
    try {
      const currentUserInfo = this.userInfoSubject.value || {}; // 如果为空则提供一个空对象
      const updatedUserInfo: UserInfo = {
        id: userInfo.id ?? (currentUserInfo as UserInfo).id,
        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.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,
          id: parsedUserInfo.id, // 确保 id 被正确传递
          username: parsedUserInfo.username || '',
          userAvatar: parsedUserInfo.userAvatar || '../../assets/images/user.png',
          userType: parsedUserInfo.userType || '普通用户',
          gender: parsedUserInfo.gender || '',
          phone: parsedUserInfo.phone || '',
          birthday: parsedUserInfo.birthday ?? null,
          email: parsedUserInfo.email || '',
          reports: parsedUserInfo.reports || [],
          medicalHistory: parsedUserInfo.medicalHistory || ''
        });
      }
      // else {
      //   // 如果没有本地用户信息，尝试从服务器获取（假设有一个获取用户信息的API）
      //   const userInfoResponse = await this.http.get<UserInfo>(`${environment.apiUrl}/getUserInfo`).toPromise();
      //   this.saveUserInfoToLocalStorage(userInfoResponse);
      //   this.userInfoSubject.next(userInfoResponse);
      // }
    } catch (error) {
      console.error('Failed to parse userInfo from localStorage:', error);
      this.userInfoSubject.next(null);
    }
  }

  loginUser(username: string, password: string): Observable<any> {
    const loginUrl = `${environment.apiUrl}/api/login`;
    return this.http.post(loginUrl, { username, password }, {
      withCredentials: true,
      headers: new HttpHeaders({
        'Content-Type': 'application/json'
      })
    }).pipe(
      tap(async (response: any) => {
        await this.saveUserInfoToLocalStorage(response);
        this.userInfoSubject.next(response);
      }),
      catchError(error => {
        let errorMessage = '登录失败';
        if (error.error instanceof ErrorEvent) {
          errorMessage = `Error: ${error.error.message}`;
        } else {
          errorMessage = `Service returned code: ${error.status}, body was: ${error.message || error.statusText}`;
        }
        console.error('登录请求出错:', errorMessage);
        return throwError(() => new Error(errorMessage));
      })
    );
  }

  registerNewUser(user: User): Observable<any> {
    const registerUrl = `${environment.apiUrl}/api/register`;
    return this.http.post(registerUrl, user).pipe(
      tap(async (response: any) => {
        await this.saveUserInfoToLocalStorage(response);
        this.userInfoSubject.next(response);
      }),
      catchError(error => {
        console.error('Registration failed:', error);
        return throwError(() => new Error('Registration failed'));
      })
    );
  }
}