import { Component } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
import { Camera, CameraOptions } from '@awesome-cordova-plugins/camera/ngx';
import { NavController } from '@ionic/angular';
import { Tab3Page } from '../tab3/tab3.page'; // 根据实际路径调整

@Component({
  selector: 'app-tab2',
  templateUrl: 'tab2.page.html',
  styleUrls: ['tab2.page.scss']
})
export class Tab2Page {
  recognitionForm: FormGroup;
  imageSrc: string | null = null;
  private camera: Camera;
  // 用于存储提交的数据
  submittedData: any = {};

  constructor(private cameraService: Camera,public navCtrl: NavController) {//添加了新的navCtrl
    this.camera = cameraService;
    this.recognitionForm = new FormGroup({
      itemInfo: new FormControl(''),
      itemCategory: new FormControl(''),
      // 添加发送地址和收货地址的FormControl
      sendAddress: new FormControl(''),
      receiveAddress: new FormControl('')
    });
  }
  
  takePhoto() {
    const options: CameraOptions = {
      quality: 100,
      destinationType: this.camera.DestinationType.DATA_URL,
      encodingType: this.camera.EncodingType.JPEG,
      mediaType: this.camera.MediaType.PICTURE,
    };

    this.camera.getPicture(options).then(
      (imageData) => {
        this.imageSrc = 'data:image/jpeg;base64,' + imageData;
      },
      (err) => {
        console.log("拍照错误: ", err);
      }
    );
  }

  selectFromAlbum() {
    // 这里添加从相册选择图片的逻辑
    const options: CameraOptions = {
      quality: 100,
      destinationType: this.camera.DestinationType.DATA_URL,
      encodingType: this.camera.EncodingType.JPEG,
      mediaType: this.camera.MediaType.PICTURE,
      sourceType: this.camera.PictureSourceType.PHOTOLIBRARY,
      saveToPhotoAlbum: false
    };
    
    this.camera.getPicture(options).then(
      (imageData) => {
        this.imageSrc = 'data:image/jpeg;base64,' + imageData;
      },
      (err) => {
        console.log("从相册选择图片错误: ", err);
      }
    );
  }

  
  submitForm() {
    if (this.recognitionForm.valid) {
      this.submittedData = this.recognitionForm.value;
      // 这里添加提交表单的逻辑
      // 序列化数据
    const serializedData = JSON.stringify(this.submittedData);
    // 使用 queryParams 导航到 Tab3Page
    this.navCtrl.navigateForward('/tabs/tab3?submittedData=' + encodeURIComponent(serializedData));
   }
  }
  hasData(obj: any): boolean {
    return Object.keys(obj).length > 0;
  }
}
