// src/app/edit-profile/edit-profile.page.ts
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { NavController } from '@ionic/angular';
import { UserService } from '../services/user.service';

@Component({
  selector: 'app-edit-profile',
  templateUrl: './edit-profile.page.html',
  styleUrls: ['./edit-profile.page.scss'],
})
export class EditProfilePage implements OnInit {
  // 在声明时初始化 profileForm
  profileForm: FormGroup = new FormGroup({});

  constructor(private fb: FormBuilder, private navCtrl: NavController,private userService: UserService) {}

  ngOnInit() {
    this.profileForm = this.fb.group({
      username: ['', [Validators.required]],
      email: ['', [Validators.required, Validators.email]],
      phone: ['', [Validators.required, Validators.pattern('^[0-9]*$')]],
      gender: ['', [Validators.required]],
      birthday: ['', [Validators.required]]
    });
  }

  onFileSelected(event: Event) {
    const input = event.target as HTMLInputElement;
    if (input.files && input.files[0]) {
      // 这里可以添加处理文件的逻辑，例如上传到服务器
      console.log('Selected file:', input.files[0]);
    }
  }

  saveProfile() {
    if (this.profileForm.valid) {
      const updatedUserInfo = this.profileForm.value;
      console.log('Profile saved:', updatedUserInfo);
      
      // 更新全局用户信息
      this.userService.updateUserInfo(updatedUserInfo);

      this.navCtrl.pop(); // 保存成功后返回上一页
    }
  }
}