import { Component, Input, OnInit, ViewChild } from '@angular/core';
import {
  AlertController,
  IonicModule,
  LoadingController,
  ToastController,
} from '@ionic/angular';
import { NavComponent } from '../../../app/components/nav/nav.component';
import * as Parse from 'parse';
import { Router } from '@angular/router';
import { UploadComponent } from '../../../app/components/upload/upload.component';
import { AuthService } from '../../../services/auth.service';

@Component({
  selector: 'app-setting',
  templateUrl: './setting.component.html',
  styleUrls: ['./setting.component.scss'],
  standalone: true,
  imports: [IonicModule, NavComponent, UploadComponent],
})
export class SettingComponent implements OnInit {
  @ViewChild('upload') upload!: UploadComponent;
  profile?: Parse.Object; //身份信息
  formData: any = {
    avatar: '',
    name: '',
    nickname: '',
    sex: '',
    age: '',
    remark:''
  };
  mobile: string = '';
  loading: any;
  constructor(
    private alertController: AlertController,
    public loadingCtrl: LoadingController,
    public toastController: ToastController,
    private authServ: AuthService,
    private router: Router
  ) {}

  ngOnInit() {
    this.getProfile();
  }
  // 获取用户信息
  async getProfile() {
    this.loading = await this.loadingCtrl.create({
      message: '加载中',
    });
    this.loading.present();
    let user = Parse.User.current();
    let query = new Parse.Query('Profile');
    query.equalTo('user', user?.id);
    query.notEqualTo('isDeleted', true);
    this.profile = await query.first();
    this.formData.avatar =
      user?.get('avatar') ||
      'https://file-cloud.fmode.cn/DXNgcD6zo6/20221202/j6p8kb034039.png';
    this.formData.nickname = user?.get('nickname') || '';
    this.formData.sex = user?.get('sex') || '';
    this.formData.age = user?.get('age') || '';
    this.mobile = user?.get('mobile');
    this.formData.name = this.profile?.get('name') || '';
    this.formData.age = this.profile?.get('birthdate') || '';
    this.formData.remark = this.profile?.get('remark') || '';
    this.loading.dismiss();
  }
  onChange(e: any,type:string){
    this.formData[type] = e.detail.value;
  }

  async saveEdit(e: any) {
    this.loading = await this.loadingCtrl.create({
      message: '正在保存修改',
    });
    this.loading.present();
    console.log(e);
    console.log(this.formData);
    let urls = e?.map((item: any) => item.url);
    let user = Parse.User.current();
    if (!user?.id) {
      this.loading.dismiss();
      const alert = await this.alertController.create({
        header: '提示',
        message: '登录信息已过期，请重新登录',
        buttons: [
          {
            text: '好的',
            role: 'confirm',
            handler: () => {
              this.authServ.logout();
            },
          },
        ],
      });
      await alert.present();
      return;
    }
    user.set('avatar', urls[0]);
    user.set('nickname', this.formData.nickname);
    user.set('sex', this.formData.sex);
    // user.set('age', Number(this.formData.age));
    await user.save();
    if (!this.profile?.id) {
      let obj = Parse.Object.extend('Profile');
      this.profile = new obj();
      this.profile?.set('user', Parse.User.current()?.toPointer());
      this.profile?.set('company', {
        __type: 'Pointer',
        className: 'Company',
        objectId: this.authServ.company,
      });
    }
    this.profile?.set('mobile', Parse.User.current()?.get('mobile'));
    this.profile?.set('sex', this.formData.sex);
    this.profile?.set('birthdate', this.formData.age);
    this.profile?.set('remark', this.formData.remark);
    await this.profile?.save();
    this.loading.dismiss();
    this.getProfile();
    this.presentAlert('修改成功');
  }

  async presentToast(title: string, time: number, color: string) {
    const toast = await this.toastController.create({
      message: title,
      duration: time,
      color: color,
    });
    toast.present();
  }

  async presentAlert(msg: string) {
    const alert = await this.alertController.create({
      header: '提示',
      message: msg,
      buttons: [
        {
          text: '好的',
          role: 'confirm',
          handler: () => {},
        },
      ],
    });
    await alert.present();
  }
  // toAddress() {
  //   this.router.navigate(['/metapunk/address'])
  // }
}
