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

/**********************
 * 考生进场
 */
@Component({
  selector: 'app-exam-interview-photo-graph',
  templateUrl: './exam-interview-photo-graph.component.html',
  styleUrls: ['./exam-interview-photo-graph.component.scss']
})
export class ExamInterviewPhotoGraphComponent extends FramePageComponent implements OnInit, OnDestroy {

  currentStep: string;
  currentRoom: any;
  timeArray: any;
  currentStd: any;
  room_key: string;
  currentPhoto: File;
  currentPhotoUrl: any;


  private intervalId: any;
  private statusIntervalId: any;

  uploader: FileUploader;

  constructor(modalService: BsModalService) {
    super(modalService);
    this.currentStep = 'Init';
  }


  ngOnInit() {
    clearTimeout(this.intervalId);
    clearTimeout(this.statusIntervalId);
    this.uploader = new FileUploader({
      url: environment.uploadRoot + "exam/photo/interview/upload.htm",
      itemAlias: "file",
      isHTML5: true,
      autoUpload: false,
      removeAfterUpload: true,
    });
  }

  goInit() {
    this.currentRoom = undefined;
    this.currentStd = undefined;
    this.timeArray = undefined;
    this['room_key'] = undefined;
    clearTimeout(this.intervalId);
    clearTimeout(this.statusIntervalId);
    this.currentStep = 'Init';
  }
  getNextStd() {
    // if (this.timeArray !== undefined && this.timeArray.length > 0 && this.checkin.ly_time_id === undefined) {
    //   MsgService.errorToaster('请选择面试时段！');
    //   return;
    // }
    AjaxService.requestEntity('exam/photo/interview/next.htm', { room_pass: this['room_key'], room_id: this.currentRoom.ly_room_id }, (entity) => {
     clearTimeout(this.intervalId);
      if (entity) {
        this.currentStd = entity;
      } else {
        this.intervalId = setTimeout(() => this.getNextStd(), 10000);
        MsgService.errorToastr('暂时没有待拍照考生！');
      }
    }, {
      RequestWithLoading: true
    });
  }

  changePassword() {
    if (this['room_key'] === undefined || $.trim(this['room_key']).length === 0)
      return;
    AjaxService.requestMap('exam/interview/room/find.htm', { room_key: this['room_key'] }, (map) => {
      this.currentRoom = map.Room;
      //this.initMap = map;
      this.timeArray = map.TimeArray;
      //this.checkin.ly_room_id = this.currentRoom.ly_room_id;
      this.currentStep = 'Confirm';
    }, {
      MsgType: 'Swal'
    });
  }

  inRoom() {
    clearTimeout(this.statusIntervalId);
    this.currentStep = 'Examing';
    this.getNextStd();
    this.intervalId = setTimeout(() => this.getNextStd(), 10000);
  }


  getRoomStatus() {
    this.changePassword();
    this.statusIntervalId =  setInterval(this.changePassword.bind(this), 5000);
  }




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


  takePhoto() {
    //浏览器调用
    var that = this;
    var cameraInput = document.createElement('input')
    cameraInput.addEventListener("change", function (e: Event) {
      console.log(e)
      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();

  }
  confirmUpload(){
    MsgService.confirmAlert("确认上传第"+this.currentStd.real_exam_echo+"号考生"+this.currentStd.std_name+"的照片？",()=>{this.uploadPhoto()});
  }

  uploadPhoto() {


    if (!this.currentPhoto) {
      return;
    }
    this.uploader.clearQueue();
    this.uploader.addToQueue([this.currentPhoto]);
    this.uploader.onBuildItemForm = (fileItem: FileItem, form: any) => {
      form.append("room_pass", this['room_key']);
      form.append("room_id", this.currentRoom.ly_room_id);
      form.append("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){
        MsgService.successToastr("上传成功");
        this.currentStd = undefined;
        this.currentPhoto = undefined;
        this.currentPhotoUrl= undefined;
        this.getNextStd();
      }else{
        MsgService.errorToastr(respObj.errorMsg)
      }

    }
    this.uploader.queue[0].upload();
  }

}
