import { Component, OnInit } from '@angular/core';
import * as Parse from 'parse';
import { 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';
import { ionicStandaloneModules } from '../../ionic-standalone.modules';

@Component({
  selector: 'app-release',
  templateUrl: './release.component.html',
  styleUrls: ['./release.component.scss'],
  standalone: true,
  imports: [...ionicStandaloneModules, FormsModule, UploadComponent,NavComponent],
})
export class ReleaseComponent implements OnInit {
  fileList: any = [];
  content: string = '';
  inputNum: number = 0;
  company: string | null = '';
  constructor(
    private authServ: AuthService,
    private toastController: ToastController
  ) {
  }

  ngOnInit() {
  }
  textChange(e: any) {
    this.content = e.detail.value;
    this.inputNum = e.detail.value.length;
  }
  onFilesChange(event: any) {
    console.log(event);
    this.fileList = event?.map((item: any) => item.url);
    this.submit()
  }
  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 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('DramaPost');
    let feedback = new Feedback();
    feedback.set('user', {
      __type: 'Pointer',
      className: '_User',
      objectId: user.id,
    });
    feedback.set('company', {
      __type: 'Pointer',
      className: 'Company',
      objectId: this.authServ.company,
    });
    feedback.set('content', this.content ? this.content : undefined);
    feedback.set('images', this.fileList);
    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);
    }
  }

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