import { Component, ElementRef, ViewChild, AfterViewInit, ChangeDetectorRef } from '@angular/core';
import { predict,saveCeramicDetectionRecord,getCeramicDetectionRecords} 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; // 是否显示弹窗
  isDestroyed: boolean = false; // 管理背景和相关元素的状态
  recognitionResults: { result: string; confidence: string}[] = []; // 动态识别结果
  constructor(private modalController: ModalController) {
    this.checkCameraAvailability();
  }
  ngOnInit() {
    // 页面初始化时加载用户记录
    const storedUserData = localStorage.getItem('user'); // 从 localStorage 获取登录用户数据
    if (storedUserData) {
      const user = JSON.parse(storedUserData);
      if (user.username) {
        console.log('当前登录用户:', user.username);
        this.fetchUserRecords(user.username); // 调用获取当前用户记录的方法
      } else {
        console.error('未找到用户名，请检查登录状态！');
      }
    } else {
      console.error('用户未登录或用户数据未找到');
    }
  }
  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);
  }
  // 卷轴卷起/放下
  toggleBackground() {
    this.isDestroyed = !this.isDestroyed;
    if (this.isDestroyed) {
       // 销毁视频流
       if (this.videoStream) {
        const tracks = this.videoStream.getTracks();
        tracks.forEach((track) => track.stop());
        this.videoStream = null;
      }
      this.imageSrc = null; // 清除图片数据
      this.isCameraMode = false; // 停止摄像头模式
    } else {
      // 恢复摄像头功能
      this.checkCameraAvailability();
    }
  }
  // 切换模式
  toggleMode() {
    this.isCameraMode = !this.isCameraMode;
    this.imageSrc = null; // 切换模式时清除图片
    if (!this.isCameraMode) {
      this.stopCamera();
    }
  }
  // 选择图片
  selectImage() {
    if (this.isDestroyed) {
      alert('当前功能已禁用，请先恢复背景！');
      return;
    }
    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() {
    if (this.isDestroyed) {
      alert('当前功能已禁用，请先恢复背景！');
      return;
    }
    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('开始检测事件触发，调用后端接口');
    // 检查是否为游客登录
    const guestFlag = localStorage.getItem('guest');
    const isGuest = guestFlag === 'true'; // 判断是否为游客
    // 调用 Flask API 进行检测
    try {
      const response = await predict(this.imageSrc); // 调用后端预测接口
      console.log('检测结果:', response);
      // 假设后端返回的数据格式为 { prediction: { predicted_label: string, confidence: number } }
      const newResult = {
        result: response.prediction?.predicted_label || '未知结果',
        confidence: response.prediction?.confidence
          ? response.prediction.confidence.toFixed(3) // 保留 3 位小数
          : '未知置信度',
      };
      // 将新结果添加到识别结果数组
      this.recognitionResults.push(newResult);
      // 判断是否为游客
      if (!isGuest) {
        console.log('用户已登录，准备保存检测记录...');
        const storedUserData = localStorage.getItem('user');
        const user = storedUserData ? JSON.parse(storedUserData) : { nickname: '未知用户' };
        const record = {
          nickname: user.username || '匿名用户', // 从用户数据中获取昵称
          detection_time: new Date().toISOString(), // 当前时间，ISO 格式
          result: newResult.result, // 识别结果
          confidence: newResult.confidence, // 置信度
        };
        // 打印 record 对象
        console.log('保存的检测记录:', record);
        try {
          const saveResponse = await saveCeramicDetectionRecord(record); // 调用保存接口
          console.log('识别记录保存成功:', saveResponse);
        } catch (saveError) {
          console.error('识别记录保存失败:', saveError);
          alert('识别记录保存失败，请检查网络或后端服务！');
        }
      } else {
        console.log('游客登录，跳过保存检测记录');
      }
  
      // 显示陶瓷详情页面
      await this.openCeramicDetails(newResult.result, newResult.confidence); // 传递两个参数
    } catch (error) {
      console.error('检测失败:', error);
      alert('检测失败，请检查网络或后端服务！');
    }
  }
  // 获取当前登录用户的识别记录 
  async fetchUserRecords(username: string) {
    try {
      const records = await getCeramicDetectionRecords(username); // 调用后端接口获取所有记录
      console.log('获取到的所有识别记录:', records);
      // 更新表格数据
      this.recognitionResults = records.map((record: any) => ({
        result: record.result,
        confidence: record.confidence,
      }));
    } catch (error) {
      console.error('获取用户检测记录时发生错误:', error);
      alert('获取用户检测记录失败，请检查网络或后端服务！');
    }
  }
  // 显示陶瓷详情模态框
  async openCeramicDetails(ceramicName: string, confidence: string) {
    // 定义陶瓷信息映射表
    let ceramicInfo: { [key: string]: { description: string; imageUrl: string } } = {};
    try {
      const response = await fetch('assets/json/ceramic.json'); // 加载 JSON 文件
      if (!response.ok) {
        throw new Error('无法加载 JSON 文件');
      }
      ceramicInfo = await response.json(); // 解析 JSON 数据
    } catch (error) {
      console.error('加载陶瓷信息失败:', error);
    }
    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();
  }
  // 查看详情事件
  async viewDetails(item: { result: string; confidence: string }) {
    console.log('查看详情:', item);
    // 跳转到陶瓷详情模态框
    await this.openCeramicDetails(item.result, item.confidence);
  }
}