import { Component, OnInit } from '@angular/core';
import { AlertController } from '@ionic/angular';
import Parse from 'parse';

@Component({
  selector: 'app-feedback',
  templateUrl: './feedback.page.html',
  styleUrls: ['./feedback.page.scss'],
})
export class FeedbackPage implements OnInit {
  feedbackRecords: any[] = [];

  constructor(private alertController: AlertController) { }

  ngOnInit() {
  }

  async submitForm(form: { valid: any; value: any; }) {
    if (form.valid) {
      try {
        const Feedback = Parse.Object.extend('Feedback');
        const feedback = new Feedback();
        feedback.set('username', form.value.username);
        feedback.set('age', form.value.age);
        feedback.set('gender', form.value.gender);
        feedback.set('question', form.value.question);
        feedback.set('suggestion', form.value.suggestion);
        feedback.set('email', form.value.email);
        await feedback.save();

        this.showAlert('提交成功', '感谢您的反馈！');
        console.log('表单提交成功');
        console.log('表单数据:', form.value);
      } catch (error) {
        console.error('Error saving feedback:', error);
        this.showAlert('提交失败', '请稍后再试。');
      }
    } else {
      console.log('表单验证失败，请检查输入');
      this.showAlert('提交失败', '表单验证失败，请检查输入。');
    }
  }

  async showAlert(header: string, message: string) {
    const alert = await this.alertController.create({
      header,
      message,
      buttons: ['确定']
    });

    await alert.present();
  }

  async fetchFeedbackRecords() {
    try {
      const Feedback = Parse.Object.extend('Feedback');
      const query = new Parse.Query(Feedback);
      const results = await query.find();

      this.feedbackRecords = results.map(record => ({
        username: record.get('username'),
        age: record.get('age'),
        gender: record.get('gender'),
        question: record.get('question'),
        suggestion: record.get('suggestion'),
        email: record.get('email'),
        createdAt: record.get('createdAt')
      }));
    } catch (error) {
      console.error('Error fetching feedback records:', error);
      this.showAlert('获取反馈记录失败', '请稍后再试。');
    }
  }
}