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

@Component({
  selector: 'app-album',
  templateUrl: './album.component.html',
  styleUrls: ['./album.component.scss'],
  standalone: true,
  imports: [IonicModule, UploadComponent, NavComponent],
})
export class AlbumComponent implements OnInit {
  files: any = [];
  profile?: Parse.Object;
  loading: boolean = false;
  constructor(
    public loadCtrl: LoadingController,
    public toastController: ToastController,
    private authServ: AuthService
  ) {}
  ngOnInit() {
    console.log(Parse.User.current()?.toPointer());
    this.getProfile();
  }
  async getProfile() {
    let query = new Parse.Query('Profile');
    query.equalTo('user', Parse.User.current()?.id);
    query.notEqualTo('isDeleted', true);
    query.select('attachment');
    let p = await query.first();
    this.profile = p;
    this.files = p?.get('attachment')?.map((item: String) => {
      return { url: item };
    });
    this.loading = true;
  }
  async onSave(e: any) {
    console.log(e);
    let urls = e?.map((item: any) => item.url);
    if (!this.profile?.id) {
      let obj = Parse.Object.extend('Profile');
      this.profile = new obj();
      this.profile?.set('mobile', Parse.User.current()?.get('mobile'));
      this.profile?.set('user', Parse.User.current()?.toPointer());
      this.profile?.set('company', {
        __type: 'Pointer',
        className: 'Company',
        objectId: this.authServ.company,
      });
    }
    this.profile?.set('attachment', urls);
    await this.profile?.save();
    const toast = await this.toastController.create({
      message: '保存成功',
      color: 'success',
      duration: 1000,
    });
    toast.present();
  }
}
