import { Injectable } from '@angular/core';
import { Observable, of } from 'rxjs';

export interface FamilyMember {
    id: string;
    name: string;
    relationship: string;
    avatar?: string; // 可选字段
  }

@Injectable({
  providedIn: 'root'
})
export class FamilyService {

    private STORAGE_KEY = 'familyMembers'; // 定义本地存储键名
  
    constructor() { }
  
    getFamilyMembers(): Observable<FamilyMember[]> {
      const members = JSON.parse(localStorage.getItem(this.STORAGE_KEY) || '[]') as FamilyMember[];
      return of(members);
    }
  
    addFamilyMember(member: Partial<FamilyMember>): Observable<FamilyMember> {
      let members = JSON.parse(localStorage.getItem(this.STORAGE_KEY) || '[]') as FamilyMember[];
      
      // Ensure required fields are provided and not undefined
      if (!member.name || !member.relationship) {
        throw new Error('Name and relationship are required.');
      }
  
      const newMember: FamilyMember = {
        id: String(new Date().getTime()), // 使用时间戳作为ID
        name: member.name!,
        relationship: member.relationship!,
        avatar: member.avatar || ''
      };
      members.push(newMember);
      localStorage.setItem(this.STORAGE_KEY, JSON.stringify(members));
      return of(newMember);
    }
  
    updateFamilyMember(memberId: string, updatedMember: Partial<FamilyMember>): Observable<FamilyMember> {
      let members = JSON.parse(localStorage.getItem(this.STORAGE_KEY) || '[]') as FamilyMember[];
      const index = members.findIndex(member => member.id === memberId);
      if (index > -1) {
        // Update only the provided fields, ensuring not to set required fields to undefined
        members[index] = {
          ...members[index],
          ...(updatedMember.name !== undefined && { name: updatedMember.name }),
          ...(updatedMember.relationship !== undefined && { relationship: updatedMember.relationship }),
          ...(updatedMember.avatar !== undefined && { avatar: updatedMember.avatar })
        };
        localStorage.setItem(this.STORAGE_KEY, JSON.stringify(members));
      }
      return of({ ...members[index], ...updatedMember });
    }
  
    removeFamilyMember(memberId: string): Observable<void> {
      let members = JSON.parse(localStorage.getItem(this.STORAGE_KEY) || '[]') as FamilyMember[];
      members = members.filter(member => member.id !== memberId);
      localStorage.setItem(this.STORAGE_KEY, JSON.stringify(members));
      return of();
    }
  }