import { Component, ElementRef, ViewChild, AfterViewInit, ChangeDetectorRef } from '@angular/core';

@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() {
    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();
      // 自动捕获图像逻辑：5秒后捕获最后一帧
      setTimeout(() => {
        if (this.isCameraMode && this.videoStream) {
          this.captureImage();
        }
      }, 5000);
    } 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();
    }
  }
  startDetection() {
    console.log('开始检测事件触发');
    // 模拟数据
    const newResult = {
      result: '识别结果 ' + (this.recognitionResults.length + 1),
      confidence: (Math.random() * 100).toFixed(2) + '%',
      details: '详情内容 ' + (this.recognitionResults.length + 1),
    };
    // 将数据添加到识别结果中
    this.recognitionResults.push(newResult);
  }
  // 查看详情事件
  viewDetails(item: { result: string; confidence: string; details: string }) {
    console.log('查看详情:', item);
    // 在此实现查看详情的逻辑
    alert(`结果: ${item.result}\n置信度: ${item.confidence}\n详情: ${item.details}`);
  }
}