import { Component } from '@angular/core';
import { NavController } from '@ionic/angular'; // 导入NavController
import { ItemsService } from '../tab4/items.service';
import Parse from "parse";
import { AlertController } from '@ionic/angular'; // 导入AlertController

@Component({
  selector: 'app-tab2',
  templateUrl: 'tab2.page.html',
  styleUrls: ['tab2.page.scss']
})
export class Tab2Page {
  formData: any = {}; // 用于存储表单数据
  selectedType: string = ''; // 选择的类型
  savedItems: Parse.Object[] = []; // 保存后的数据

  constructor(private itemsService: ItemsService, private navCtrl: NavController, private alertController: AlertController) {}

  async submitForm() {
    if (!this.selectedType || !this.formData.title) {
      const alert = await this.alertController.create({
        header: '错误',
        message: '请选择类型并填写标题后再保存数据',
        buttons: ['确定']
      });
      await alert.present();
      return; // 阻止保存数据
    }
    switch (this.selectedType) {
      case '求助':
        this.formData.category = '求助';
        break;
      case '二手交易':
        this.formData.category = '二手交易';
        break;
      case '失物招领':
        this.formData.category = '失物招领';
        break;
      case '活动':
        this.formData.category = '活动';
        break;
      default:
        break;
    }

    this.formData.amount = parseFloat(this.formData.amount); // 将 amount 字段的值转换为 Number 类型
    this.itemsService.saveItem(this.formData).then((savedItem) => {
      console.log('保存成功:', savedItem);
      // 导航到首页并传递保存的数据
      this.navCtrl.navigateRoot('/tabs/tab4', { state: { savedItems: [savedItem] } });
    }).catch((error) => {
      console.error('保存失败:', error);
    });
  }

  onFileChange(event: Event) {
    const fileInput = (event.target as HTMLInputElement);
    const file = fileInput?.files?.[0];

    if (file) {
        const parseFile = new Parse.File('image.jpg', file);

        parseFile.save().then((savedFile) => {
            this.formData.image = savedFile.url();
        }).catch((error) => {
            console.error('Error saving file: ', error);
        });
    }
  }
  
}