import { Component, OnDestroy, OnInit } from '@angular/core';
import { FileItem, FileUploader, ParsedResponseHeaders } from 'ng2-file-upload';
import { BsModalService } from 'ngx-bootstrap/modal';
import { FramePageComponent } from '../../../../frame/core/page/frame.page';
import { environment } from '../../../../../../environments/environment';

@Component({
  selector: 'app-room-interview-photo-graph',
  templateUrl: './room-interview-photo-graph.component.html',
  styleUrls: ['./room-interview-photo-graph.component.scss']
})
export class RoomInterviewPhotoGraphComponent extends FramePageComponent implements OnInit, OnDestroy {

  currentStep: any;
  room_key: any;
  currentRoom: any;
  currentStd: any;
  group: any;
  currentPhoto: File;
  currentPhotoUrl: any;

  private intervalId: any;
  private statusIntervalId: any;
  uploader: FileUploader;

  constructor(modalService: BsModalService) { 
    super(modalService);
  }
 
  ngOnInit(): void {
    clearTimeout(this.intervalId);
    clearTimeout(this.statusIntervalId);
    this.currentStep = 'Init';
    this.uploader = new FileUploader({
      url: environment.uploadRoot + "ex/photo/graph/upload.htm", 
      itemAlias: "file",
      isHTML5: true,
      autoUpload: false,
      removeAfterUpload: true,
    });
  }

  goInit() {
    this.currentRoom = undefined;
    this.currentStd = undefined;
    this.group = undefined;
    this.room_key= undefined;
    clearTimeout(this.intervalId);
    clearTimeout(this.statusIntervalId);
    this.currentStep = 'Init';
  }

 //根据考场密钥-查找考场
 requestRoom() {
    if(!this.room_key) return;
    this.AjaxService.requestEntity('ly/room/interview/find.htm', {room_key: this.room_key}, (entity) => {
      this.currentRoom = entity.room;
      this.currentRoom.group = entity.group;
      this.currentStep = 'Confirm';
    }, { MsgType: 'Swal'});
 }

  //轮询考场
  getRoomStatus() {
    this.requestRoom();
    this.statusIntervalId = setInterval(this.requestRoom.bind(this), 5000);
  }

  //准备拍照
  preparePhoto() {
    clearTimeout(this.statusIntervalId);
    this.currentStep = 'Examing';
    this.getNextStd();
  }

  //查找考生
  getNextStd() {
    this.AjaxService.requestEntity('ex/photo/graph/next.htm', {room_key: this.room_key, ly_room_id: this.currentRoom.ly_room_id}, (entity) => {
      clearTimeout(this.intervalId);
      if(entity) {
        this.currentStd = entity;
      } else {
        this.intervalId = setTimeout( () => this.getNextStd(), 10000);
        this.MsgService.errorToastr('没有待拍照考生！');
      }
    }, {RequestWithLoading: true});
  }
  
  //拍照
  takePhoto() {
    //浏览器调用
    var that = this;
    var cameraInput = document.createElement('input')
    cameraInput.addEventListener("change", function (e: Event) {
      that.currentPhoto = (<HTMLInputElement>e.target).files[0];
      var reader = new FileReader();
      reader.readAsDataURL(that.currentPhoto);
      reader.onload = function (e) {
        that.currentPhotoUrl = this.result;
      }

      document.body.removeChild(cameraInput);
    })
    //cameraInput.setAttribute('id', 'input_upload_ID');
    cameraInput.setAttribute('type', 'file');
    // 添加这个属性，就可以唤起相机的功能
    cameraInput.setAttribute('capture', 'camera');
    // 这里如果不加属性 accept 是 "image/*" 或者 "video/*"，就默认打开摄像头，既可以拍照也可以录像
    cameraInput.setAttribute('accept', 'image/*');
    cameraInput.setAttribute("style", 'visibility:hidden');
    // 这里将创建的隐式input控件拼接到body的最后面，会增加页面的长度，所以要在适当的时候，移除掉这个隐式创建的input控件
    document.body.appendChild(cameraInput);
    // 这里是模拟点击了input控件
    cameraInput.click();
  }

   //拍照
  uploadPhoto() {
    if(!this.currentPhoto) return;
    this.uploader.clearQueue();
    this.uploader.addToQueue([this.currentPhoto]);
    this.uploader.onBuildItemForm = (fileItem: FileItem, form: any) => {
      form.append("room_key", this.room_key);
      form.append("ly_room_id", this.currentRoom.ly_room_id);
      form.append("real_exam_seq", this.currentStd.real_exam_seq);
      form.append("std_id", this.currentStd.std_id);
    }
    this.uploader.onSuccessItem = (item: FileItem, response: string, status: number, headers: ParsedResponseHeaders) => {
      let respObj = JSON.parse(response);
      if (respObj.errorCode==0){
        this.MsgService.successToastr("上传成功");
        this.currentStd = undefined;
        this.currentPhoto = undefined;
        this.currentPhotoUrl= undefined;
        this.getNextStd();
      }else{
        this.MsgService.errorToastr(respObj.errorMsg);
      }
    }
    this.uploader.queue[0].upload();
  }

  ngOnDestroy(): void {
    clearTimeout(this.intervalId);
    clearTimeout(this.statusIntervalId);
  }

  //上一个考生
  getPreStd() {
    if(this.currentStd.real_exam_seq == 1) {
      this.MsgService.errorToastr('已无上一个考生!');
      return;
    }
    this.AjaxService.requestEntity('ex/photo/graph/next.htm', {
      room_key: this.room_key, 
      ly_room_id: this.currentRoom.ly_room_id, 
      real_exam_seq: this.currentStd.real_exam_seq-1
    },  (entity) => {
      clearTimeout(this.intervalId);
      if(entity) {
        this.currentStd = entity;
      }
    }, {RequestWithLoading: true});
  }


}
