import { Component, ElementRef, ViewChild, AfterViewInit, ChangeDetectorRef } from '@angular/core';
import { predict } from 'src/app/service/api'; // 引入 API 服务
import { ModalController } from '@ionic/angular';
import { CeramicDetailsPage } from '../ceramic-details/ceramic-details.page';
@Component({
  selector: 'app-tab3',
  templateUrl: 'tab3.page.html',
  styleUrls: ['tab3.page.scss']
})
export class Tab3Page implements AfterViewInit{
  @ViewChild('video',{ static: false }) videoElement!: ElementRef<HTMLVideoElement>;
  @ViewChild('canvas',{ static: false }) canvasElement!: ElementRef<HTMLCanvasElement>;
  @ViewChild('fileInput',{ static: false }) fileInput!: ElementRef<HTMLInputElement>;
  isCameraMode: boolean = false; // 是否为摄像头模式
  imageCaptured: boolean = false; // 是否已捕获图像
  cameraAvailable: boolean = false; // 摄像头是否可用
  imageSrc: string | null = null; // 保存图片数据
  videoStream: MediaStream | null = null; // 保存视频流
  showAlert: boolean = false; // 是否显示弹窗
  recognitionResults: { result: string; confidence: string; details: string }[] = []; // 动态识别结果
  constructor(private modalController: ModalController) {
    this.checkCameraAvailability();
  }
  checkCameraAvailability() {
    navigator.mediaDevices
      .getUserMedia({ video: true })
      .then(() => {
        this.cameraAvailable = true; // 摄像头可用
      })
      .catch(() => {
        this.cameraAvailable = false; // 摄像头不可用
      });
  }
  // 确保视图加载完成后 ViewChild 初始化
  ngAfterViewInit() {
    console.log('Video Element:', this.videoElement);
    console.log('Canvas Element:', this.canvasElement);
    console.log('File Input Element:', this.fileInput);
  }
  // 切换模式
  toggleMode() {
    this.isCameraMode = !this.isCameraMode;
    this.imageSrc = null; // 切换模式时清除图片
    if (!this.isCameraMode) {
      this.stopCamera();
    }
  }
  // 选择图片
  selectImage() {
    if (this.fileInput) {
      this.fileInput.nativeElement.click();
    } else {
      console.error('File input is not available');
    }
  }
  // 处理选择的图片
  onFileSelected(event: any) {
    const file = event.target.files[0];
    if (file) {
      const reader = new FileReader();
      reader.onload = (e: any) => {
        this.imageSrc = e.target.result;
      };
      reader.readAsDataURL(file);
    }
  }
  // 启动摄像头
  async startCamera() {
    try {
      this.isCameraMode = true;
      this.imageCaptured = false;
      this.videoStream = await navigator.mediaDevices.getUserMedia({ video: true });
      const video = this.videoElement.nativeElement;
      video.srcObject = this.videoStream;
      video.play();
      // 自动捕获图像逻辑：3秒后捕获最后一帧
      setTimeout(() => {
        if (this.isCameraMode && this.videoStream) {
          this.captureImage();
        }
      }, 3000);
    } catch (error) {
      console.error('Error accessing camera:', error);
    }
  }
  // 停止摄像头
  stopCamera() {
    if (this.videoStream) {
      const tracks = this.videoStream.getTracks();
      tracks.forEach(track => track.stop());
      this.videoStream = null;
    }
    this.isCameraMode = false;
  }
  // 捕获图像
  captureImage() {
    if (!this.videoElement || !this.canvasElement) {
      console.error('Video or Canvas element is not available');
      return;
    }
    const video = this.videoElement.nativeElement;
    const canvas = this.canvasElement.nativeElement;
    const context = canvas.getContext('2d');
    if (context) {
      // 设置 Canvas 大小与视频相同
      canvas.width = video.videoWidth;
      canvas.height = video.videoHeight;
      // 绘制当前视频帧到 Canvas
      context.drawImage(video, 0, 0, canvas.width, canvas.height);
      // 获取图片数据并保存到 imageSrc
      this.imageSrc = canvas.toDataURL('image/png');
      this.imageCaptured = true;
      // 停止摄像头
      this.stopCamera();
    }
  }
  //开始检测
  async startDetection() {
    if (!this.imageSrc) {
      console.error('No image available for detection');
      alert('请先捕获或选择图像！');
      return;
    }
    console.log('开始检测事件触发，调用后端接口');
    //调用Flask API进行检测
    try {
      predict(this.imageSrc)
        .then(async (response) => {
          console.log('检测结果:', response);
          // 假设后端返回的数据格式为 { prediction: string, confidence: string, details: string }
          const newResult = {
            result: response.prediction.predicted_label || '未知结果',
            confidence: response.prediction.confidence
            ? response.prediction.confidence.toFixed(3) 
            : '未知置信度',
            details: response.prediction.details || '未知详情',
          };
          // 将新结果添加到识别结果数组
        this.recognitionResults.push(newResult);
        // 显示陶瓷详情页面
        await this.openCeramicDetails(newResult.result);
      })
    }
    catch(error) {
      console.error('检测失败:', error);
      alert('检测失败，请检查网络或后端服务！');
    };
  }
  // 显示陶瓷详情模态框
  async openCeramicDetails(ceramicName: string) {
    // 定义陶瓷信息映射表
    const ceramicInfo: { [key: string]: { description: string; imageUrl: string } } = {
      '兔毫盏': {
        description: '兔毫盏是一种经典的陶瓷器具，以其细长如兔毫的纹路闻名。',
        imageUrl: 'assets/images/tuhazhan.jpg',
      },
      '凤纹盏': {
        description: '凤纹盏是一种以凤纹为装饰的陶瓷，展现高贵的文化气息。',
        imageUrl: 'assets/images/fengwenzhan.jpg',
      },
      '剪纸贴花盏': {
        description: '剪纸贴花盏以独特的剪纸贴花艺术装饰，工艺精美。',
        imageUrl: 'assets/images/jianzhitiehuazhan.jpg',
      },
      // 添加其他陶瓷信息...
    };
    const ceramicDetails = ceramicInfo[ceramicName] || {
      description: '暂无详细信息。',
      imageUrl: 'assets/images/default.jpg',
    };
    const modal = await this.modalController.create({
      component: CeramicDetailsPage,
      componentProps: {
        title: ceramicName,
        description: ceramicDetails.description,
        imageUrl: ceramicDetails.imageUrl,
      },
      cssClass: 'custom-modal', 
    });
    await modal.present();
  }
  // 查看详情事件
  viewDetails(item: { result: string; confidence: string; details: string }) {
    console.log('查看详情:', item);
    // 在此实现查看详情的逻辑
    alert(`结果: ${item.result}\n置信度: ${item.confidence}\n详情: ${item.details}`);
  }
}