import { Component, OnInit } from '@angular/core';
import { DomSanitizer, SafeResourceUrl } from '@angular/platform-browser';
import { Router } from '@angular/router';
import { FaceApiService } from '../face-api.service';
import { CommonModule } from '@angular/common';
    
import { IonContent,IonButton,IonSegment,IonSegmentButton,IonLabel } from "@ionic/angular/standalone";
import { CloudObject, CloudQuery } from 'src/lib/ncloud';

@Component({
  selector: 'app-page-feat68',
  templateUrl: './page-feat68.component.html',
  styleUrls: ['./page-feat68.component.scss'],
  standalone: true,
  imports:[
    CommonModule,
    IonContent,IonButton,
    IonSegment,IonSegmentButton,IonLabel
    
  ]
})
export class PageFeat68Component  implements OnInit {

  tab:string = "models"
  tabChange(ev:any){
    this.tab = ev.detail.value
  }
  constructor(private faceServ:FaceApiService,private dom:DomSanitizer,
    private router: Router,
    ) { }

  ngOnInit() {
    this.doTest();
  }
  
  back(){
    this.router.navigate(["/mirror/login"])
  }


  /**
   * 特征提取：测试人脸面部68特征向量
   */
  faceList:Array<any> = [
    {title:"lyf1",photo:"assets/face/lyf1.jpg"},
    {title:"lyf2",photo:"assets/face/lyf2.jpg"},
    {title:"ym11",photo:"assets/face/ym1.jpg"},
    {title:"ym2",photo:"assets/face/ym2.jpg"},
    {title:"gtl1",photo:"assets/face/gtl1.jpg"},
    {title:"gtl2",photo:"assets/face/gtl2.jpg"},
    {title:"gtl3",photo:"assets/face/gtl3.jpg"},
  ]
  async getFeat68(face:any,faceimg:HTMLImageElement){
    let detections = await this.faceServ.getFaceDetections(face?.photo,faceimg)
    if(detections){
      face.detect = detections?.[0];
      face.feat68 = detections?.[0].descriptor;
      let query = new CloudQuery("FaceReport");
      query.equalTo("title",face.title);
      query.equalTo("photo",face.photo);
      let report = await query.first();
      if(!report?.id){
        report =  new CloudObject("FaceReport");
      }

      if(report){
        if(report.get("feat68")?.length){
          return
        }else{
          report.set({
            "photo":face.photo,
            "title":face.title,
            "feat68":Object.values(face.feat68)
          })
          report.save();
        }
      }
      console.log(face.feat68)
    }
  }
  faceListSelect:Array<any> = []
  selectFace(face:any){
    let idx = this.faceListSelect.findIndex(item=>item.photo == face.photo)
    if(idx>-1){
      this.faceListSelect.splice(idx,1);
    }else{
      this.faceListSelect.push(face);
    }
  }
  matchFaces(){
    let first = this.faceListSelect[0];
    if(first){
      this.faceListSelect.forEach(face=>{
        let matchRes = this.faceServ.mathFace(first.detect,face.detect)
        face.distance = matchRes.distance
        face.score = matchRes.score
      })
    }
  }

  /**
   * 模型加载：测试加载模型效率
   */
  async doTest(){
    await this.loadFaceApi()
    // await this.loadFaceApi('faceloadall')
    await this.detectFace()
  }
  timeMap:any = {
    faceload:null
  }
  async loadFaceApi(type='faceload') {
    let start = new Date();
    this.timeMap[type] = null;
    this.faceServ.isLoaded = false;
    this.faceServ.isLoading = false;
    if(type=="faceloadall"){
      await this.faceServ.loadFaceModule(true);
    }else{
      await this.faceServ.loadFaceModule();
    }
    this.timeMap[type] = ((new Date()).getTime() - start.getTime())/1000;
  }
  detectTimeout = false;
  async detectFace(onlyimg:boolean=false){
    this.detectTimeout = false;
    this.wait(5000).then(()=>{
      this.detectTimeout = true;
    })
    return new Promise(async (resolve,reject)=>{
      let startImg = new Date();
      let img = document.createElement("img");
      // (img as any).src = this.dom.bypassSecurityTrustResourceUrl("https://file-cloud.fmode.cn/khgbeQmvYZ/20230522/crv61q070604117.png")
      img.crossOrigin = '*';
      img.src = "https://file-cloud.fmode.cn/khgbeQmvYZ/20230522/crv61q070604117.png"
      // img.src = await this.getBase64("https://file-cloud.fmode.cn/khgbeQmvYZ/20230522/crv61q070604117.png")
      img.onload = async (data)=>{
        try{
          let startDetect = new Date();
          this.timeMap['imgload'] = ((new Date()).getTime() - startImg.getTime())/1000;
          if(onlyimg) resolve(true)
          let detections: any = await this.faceServ.detectAllFaces(img)
          console.log(detections[0]?._score)
          this.timeMap['detect'] = ((new Date()).getTime() - startDetect.getTime())/1000;
          resolve(true)
        }catch(err){
          console.log(err)
          reject(err)
        }
      }
      img.onerror = (err)=>{
        console.log(err)
        reject(err)
      }
    })
  }

  async getBase64(imageUrl:string):Promise<string>{
    console.log("fetchres")
    let response = await fetch(imageUrl)
    let blob = await response.blob()
    return new Promise((resolve)=>{
      let oFileReader = new FileReader();
      console.log("loadfile")
      oFileReader.onabort = e=>{
        console.log(e)
      }
      oFileReader.onloadend = (e:any)=>{
        console.log("loaded")
        let base64 = e.target.result;
        //项目用的是react，这里的this.canvasImage是定义在组件内的
        resolve(base64)
      };
      oFileReader.onerror = (err)=>{
        console.log("error")
        console.log(err)
      }
      oFileReader.readAsDataURL(blob);
    })
  };
  wait(timeout:number){
    return new Promise((resolve,reject)=>{
      setTimeout(() => {
        resolve(true);
      }, timeout);
    })
  }
}
