import { Component, OnInit } from '@angular/core';
import { NavController } from '@ionic/angular';
import Parse from "parse";
@Component({
  selector: 'app-edit-info',
  templateUrl: './edit-info.page.html',
  styleUrls: ['./edit-info.page.scss'],
})
export class EditInfoPage implements OnInit {
  userInfo:any = {
    name: '',
    avatarUrl: 'assets/美津未.jpg',
    campus: '',
    building: '',
    gender: ''
  };
  editedUser = { ...this.userInfo }; // Clone of user for editing
  editing = false;
  currentUser:Parse.User|undefined
  // navController: any;
  constructor(private navController: NavController) {}

  ngOnInit() {
    this.currentUser = Parse.User.current();
    if (this.currentUser) {
      // 修改uesrInfo赋值逻辑，仅加载被编辑的字段属性值
      let json = this.currentUser.toJSON();
      for (const key in json) {
        if (this.userInfo.hasOwnProperty(key)) {
          this.userInfo[key] = json[key]
        }
      }
    }
    console.log(this.userInfo)
  }
  onFileSelected(event: any) {
    const file: File = event.target.files[0];
    const reader = new FileReader();
    reader.onload = () => {
      this.editedUser.avatarUrl = reader.result as string;
    };
    reader.readAsDataURL(file);
  }

  startEditing() {
    this.editing = true;
  }
  save() {
    this.currentUser = Parse.User.current();
    if (this.currentUser) {
      console.log(this.editedUser);
      this.editedUser.birthday = this.editedUser.birthday || new Date();
      this.editedUser.birthday = new Date(this.editedUser.birthday);
      for (const key in this.editedUser) {
        if (this.editedUser.hasOwnProperty(key)) {
          this.currentUser.set(key, this.editedUser[key]);
        }
      }
      this.currentUser.save().then(() => {
        this.navController.back();
      }).catch((error) => {
        console.error('Error saving user data: ', error);
      });
    }
    console.log(this.editedUser);
}

  cancelEditing() {
    this.navController.back();
  }

}
