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

@Component({
  selector: 'app-feedback',
  templateUrl: './feedback.component.html',
  styleUrls: ['./feedback.component.scss'],
  standalone: true,
  imports: [IonicModule, FormsModule, UploadComponent,NavComponent],
})
export class FeedbackComponent implements OnInit {
  fileList: any = [];
  content: string = '';
  inputNum: number = 0;
  company: string | null = '';
  constructor(
    private authServ: AuthService,
    public toastController: ToastController
  ) {
    this.company = authServ.company;
  }
  textChange(e: any) {
    this.content = e.detail.value;
    this.inputNum = e.detail.value.length;
  }
  ngOnInit() {}
  async presentToast(title: string, time: number, color: string) {
    const toast = await this.toastController.create({
      message: title,
      duration: time,
      color: color,
    });
    toast.present();
  }
  onFilesChange(event: any) {
    console.log(event);
    this.fileList = event;
  }
  async submit() {
    let user = Parse.User.current();
    if (!user) {
      this.authServ.logout();
      return;
    }
    console.log(this.fileList);
    if (
      (this.content == '' || this.content.trim() == '') &&
      this.fileList.length < 1
    ) {
      await this.presentToast('请填写内容', 1500, 'danger');
      return;
    }
    let images = [];
    for (let i = 0; i < this.fileList.length; i++) {
      let item = this.fileList[i];
      images.push({
        url: item,
      });
    }
    let mobile = user.get('mobile');
    let Profile = new Parse.Query('Profile');
    Profile.equalTo('user', user.id);
    Profile.notEqualTo('isDeleted',true)
    let profile = await Profile.first();
    let Feedback = Parse.Object.extend('Feedback');
    let feedback = new Feedback();
    feedback.set('user', {
      __type: 'Pointer',
      className: '_User',
      objectId: user.id,
    });
    feedback.set('company', {
      __type: 'Pointer',
      className: 'Company',
      objectId: this.company,
    });

    if (profile) {
      feedback.set('profile', {
        __type: 'Pointer',
        className: 'Profile',
        objectId: profile.id,
      });
    }

    feedback.set('content', this.content ? this.content : undefined);
    feedback.set('images', images);
    feedback.set('mobile', mobile);
    let result = await feedback.save();
    if (result && result.id) {
      await this.presentToast('提交成功', 1500, 'success');
      history.go(-1);
    } else {
      await this.presentToast('提交失败', 1500, 'danger');
      setTimeout(() => {
        history.go(-1);
      }, 1500);
    }
  }
}
