import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { AlertController, NavController, LoadingController } from '@ionic/angular';
import { HttpClient } from '@angular/common/http';
import { environment } from 'src/environments/environment';

@Component({
  selector: 'app-feedback',
  templateUrl: './feedback.page.html',
  styleUrls: ['./feedback.page.scss'],
})
export class FeedbackPage implements OnInit {
  feedbackForm!: FormGroup; // 使用非空断言操作符

  private apiUrl = environment.apiUrl + '/feedback'; // 假设这是您的API端点

  constructor(
    private formBuilder: FormBuilder,
    private alertController: AlertController,
    private navCtrl: NavController,
    private loadingController: LoadingController,
    private http: HttpClient
  ) {}

  ngOnInit() {
    this.feedbackForm = this.formBuilder.group({
      name: ['', [Validators.required]],
      email: ['', [Validators.required, Validators.email]],
      message: ['', [Validators.required]]
    });
  }

  async submitFeedback() {
    const loading = await this.loadingController.create({
      message: '正在提交...'
    });
    await loading.present();

    if (this.feedbackForm.valid) {
      const { name, email, message } = this.feedbackForm.value;

      try {
        // 发送POST请求到服务器
        const response = await this.http.post(this.apiUrl, {
          name,
          email,
          message
        }).toPromise();

        // 显示成功消息
        const alert = await this.alertController.create({
          header: '提交成功',
          message: '感谢您的反馈！我们会尽快处理。',
          buttons: ['确定']
        });

        await alert.present();
        this.feedbackForm.reset(); // 清空表单
        this.navCtrl.back(); // 返回上一个页面

      } catch (error) {
        console.error('提交失败:', error);

        // 显示错误消息
        const errorAlert = await this.alertController.create({
          header: '提交失败',
          message: '很遗憾，我们无法提交您的反馈。请稍后再试或联系支持团队。',
          buttons: ['确定']
        });

        await errorAlert.present();
      } finally {
        loading.dismiss();
      }
    }
  }
}