import { Component, OnInit } from '@angular/core';
import { NavController } from '@ionic/angular';
import * as 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: '',
    mobile: '',
    gender: '',
    birthday: ''
  };
  currentUser:Parse.User|undefined
  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)
  }

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

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

}