import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable, of } from 'rxjs';
import { HttpClient } from '@angular/common/http';
import { map } from 'rxjs/operators';

interface User {
  username: string;
  phone: string;
  avatar: string;
  password: string;
}

@Injectable({
  providedIn: 'root'
})
export class UserService {
  private isLoggedInSubject = new BehaviorSubject<boolean>(false);
  private currentUserSubject = new BehaviorSubject<User | null>(null);
  
  isLoggedIn$ = this.isLoggedInSubject.asObservable();
  currentUser$ = this.currentUserSubject.asObservable();

  // 模拟用户数据存储
  private users: { [key: string]: User } = {};

  constructor(private http: HttpClient) {
    this.checkLoginStatus();
  }

  checkLoginStatus() {
    const token = localStorage.getItem('userToken');
    const userData = localStorage.getItem('userData');
    if (token && userData) {
      this.isLoggedInSubject.next(true);
      this.currentUserSubject.next(JSON.parse(userData));
    }
  }

  login(credentials: {phone: string, password: string}): Observable<any> {
    // 模拟验证逻辑
    const user = this.users[credentials.phone];
    if (user && user.password === credentials.password) {
      localStorage.setItem('userToken', 'dummy-token');
      localStorage.setItem('userData', JSON.stringify(user));
      this.isLoggedInSubject.next(true);
      this.currentUserSubject.next(user);
      return of({ success: true, user });
    }
    return of({ success: false });
  }

  register(userData: any): Observable<any> {
    if (this.users[userData.phone]) {
      return of({ success: false, message: '该手机号已被注册' });
    }
    const newUser: User = {
      username: userData.username,
      phone: userData.phone,
      password: userData.password,
      avatar: userData.avatar || 'assets/default-avatar.png'
    };
    this.users[userData.phone] = newUser;
    return of({ success: true, user: newUser });
  }

  logout() {
    localStorage.removeItem('userToken');
    this.isLoggedInSubject.next(false);
  }

  updateAvatar(imageData: string): Observable<{success: boolean}> {
    const currentUser = this.currentUserSubject.value;
    if (currentUser) {
      try {
        // 更新用户数据
        currentUser.avatar = imageData;
        this.users[currentUser.phone].avatar = imageData;
        
        // 保存到本地存储
        localStorage.setItem('userData', JSON.stringify(currentUser));
        
        // 更新当前用户状态
        this.currentUserSubject.next({...currentUser});
        
        return of({ success: true });
      } catch (error) {
        console.error('Error updating avatar:', error);
        return of({ success: false });
      }
    }
    return of({ success: false });
  }

  getCurrentUser(): Observable<any> {
    return this.currentUser$;
  }

  changePassword(oldPassword: string, newPassword: string): Observable<any> {
    const currentUser = this.currentUserSubject.value;
    if (currentUser && this.users[currentUser.phone].password === oldPassword) {
      this.users[currentUser.phone].password = newPassword;
      return of({ success: true });
    }
    return of({ success: false, message: '原密码错误' });
  }

  switchAccount(credentials: {phone: string, password: string}): Observable<any> {
    return this.login(credentials);
  }

  deleteAccount(): Observable<any> {
    const currentUser = this.currentUserSubject.value;
    if (currentUser) {
      delete this.users[currentUser.phone];
      return of({ success: true });
    }
    return of({ success: false });
  }
} 