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: new Date().toISOString() // 设置默认值为当前日期
  };
  currentUser: Parse.User | undefined;
  //currentUser!: Parse.User;

  constructor(private navController: NavController) {}

  ngOnInit() {
    this.currentUser = Parse.User.current();
    if (this.currentUser) {
      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().toISOString();
      if (!this.isValidDate(this.userInfo.birthday)) {
        console.error('无效的日期格式');
        // 可以在界面上给用户反馈
        return;
      }
      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(() => {
        console.log('用户信息保存成功');
        this.navController.back(); // 返回上一页或者进行其他导航操作
      }).catch((error) => {
        console.error('保存用户信息时出错: ', error);
        // 可以在界面上给用户反馈保存失败的原因
      });
    } else {
      console.error('未能获取当前用户');
      // 可以在界面上给用户反馈需要登录才能保存信息
    }
  }

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

  isValidDate(dateString: string): boolean {
    const date = new Date(dateString);
    return !isNaN(date.getTime());
  }

}
