import { Component, OnDestroy, OnInit, ViewChild } from '@angular/core';
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';
declare var Quagga: any;

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

  currentStep;
  currentRoom;
  initMap;
  totalRoom;
  timeArray;
  judgeArray;
  checkin;
  currentStd;
  infoStdArray;
  qrcode;
  room_key = '';
  @ViewChild('certid', { static: false }) certid;

  private intervalId: any;
  deviceId: any;
  devices: any;
  lastCode="";
  ishttps=false;
  tracksArr = [];
  cert_id: any;

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

  }


  ngOnInit() {


  }



  goInit() {
    this.currentRoom = undefined;
    this.timeArray = undefined;
    this['room_key'] = undefined;
    this.judgeArray = undefined;
    this.totalRoom = undefined;
    this.infoStdArray = undefined;
    this.checkin = {};
    clearTimeout(this.intervalId);
    this.currentStep = 'Init';
  }

  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';
      this.checkRoomStatus();
    }, {
      MsgType: 'Swal'
    });
  }

  /**************
   * 开启考场
   */
  startRoom() {
    if (this.timeArray !== undefined && this.timeArray.length > 0 && this.checkin.ly_time_id === undefined) {
      MsgService.errorToastr('请选择面试时段！');
      return;
    }
    AjaxService.requestEntity('exam/interview/room/start.htm', { ly_room_id: this.currentRoom.ly_room_id }, (entity) => {
      this.currentRoom = entity;
      console.log(this.currentRoom);
      this.checkRoomStatus();
    }, {
      RequestWithLoading: true
    });
  }

  inRoom() {
    if (this.timeArray !== undefined && this.timeArray.length > 0 && this.checkin.ly_time_id === undefined) {
      MsgService.errorToastr('请选择面试时段！');
      return;
    }
    // 进入考场，获取之前排队的考生
    AjaxService.requestArray('exam/interview/room/inroom.htm', { ly_room_id: this.currentRoom.ly_room_id }, (array) => {
      this.infoStdArray = array;
      this.currentStep = 'Examing';
      this.initCameraSelection();
      this.intervalId = setInterval(this.requestTotal.bind(this), 5000);
    });
  }

  checkRoomStatus() {
    if (this.currentRoom.exam_status === 'Judge') {
      this.checkJudgeLogin();
      // 等待评委登陆
      this.intervalId = setInterval(this.checkJudgeLogin.bind(this), 5000);
    }
  }

  /**************
   * 检查评委登陆
   */
  checkJudgeLogin() {
    AjaxService.requestMap('exam/interview/room/judge/list.htm', { ly_room_id: this.currentRoom.ly_room_id }, (map) => {
      this.currentRoom = map.Room;
      this.judgeArray = map.JudgeArray;

      if (this.currentRoom.exam_status !== 'Judge') {
        clearTimeout(this.intervalId);
      }

      this.checkRommStatusByJudges(map.JudgeArray);
    });
  }

  //检查所有评委登陆状态 更新考场状态
  checkRommStatusByJudges(judgeArray) {
    let isJudgesAllLogin = true;
    for (let i = 0; i < judgeArray.length; i++) {
      const item = judgeArray[i];
      //未登陆
      if (item.judge_status === 'Init') {
        isJudgesAllLogin = false;
      }
    }

    if (isJudgesAllLogin == true) {
      this.currentRoom.exam_status = 'Examing';
    }
  }

  /***********
   * 修改了身份证号
   */
  changeCertId() {
    if ($("#certid")) {
      this.checkin.cert_id = $("#certid").val();
    }
    if (this.checkin.cert_id === undefined || $.trim(this.checkin.cert_id).length === 0)
      return;
    // 提交
    this.checkin.requesting = true;
    AjaxService.requestMap('exam/interview/room/std/info.htm', this.checkin, (map) => {

      this.currentStd = map.StdReg;
      this.currentStd.TracksArray = map.TracksArray;
      this.infoStdArray = map.StdArray;
      this.afertCertIdRequest();
    }, {
      ErrorCallback: this.afertCertIdRequest.bind(this)
    });
  }

  afertCertIdRequest() {
    this.checkin.requesting = false;
    this.certid.nativeElement.focus();
    this.certid.nativeElement.select();
  }

  goStd(std) {
    this.checkin.cert_id = std.cert_id;
    this.changeCertId();
  }

  /****************
   * 考生入场，单个考生
   */
  stdInRoom(std_id?) {
    // 判断
    const fn = () => {
      this.checkin.requesting = true;
      AjaxService.requestArray('exam/interview/room/std/inroom.htm', { ly_room_id: this.currentRoom.ly_room_id, std_id: std_id }, (array) => {
        if (std_id !== undefined) {
          MsgService.successToastr(`考生【${this.infoStdArray[0].std_name}】已进场！`);
        } else {
          MsgService.successToastr(`本组供【${this.infoStdArray.length}】考生，已完成进场！`);
        }
        this.infoStdArray = array;

        this.afertCertIdRequest();
      }, {
        ErrorCallback: this.afertCertIdRequest.bind(this)
      });
    };
    if (this.currentRoom.group.pack_flag !== 'Active') {
      if (std_id === undefined)
        return;
      fn.call(this);
    } else {
      if (this.infoStdArray.length !== this.currentRoom.group.pack_std_num) {
        MsgService.confirmAlert(`该类型考试默认每组【${this.currentRoom.group.pack_std_num}】个考生，该组目前有【${this.infoStdArray.length}】个考生，确定本组按照此数量进场考试吗？`, fn);
      } else
        fn.call(this);
    }
  }

  requestTotal() {
    AjaxService.requestEntity('exam/interview/room/total.htm', this.checkin, (entity) => {
      this.totalRoom = entity;
    }, {});
  }

  removeInfoStd(std) {
    const fn = () => {
      this.checkin.requesting = true;
      AjaxService.requestArray('exam/interview/room/std/info/cancel.htm', {
        ly_room_id: this.currentRoom.ly_room_id,
        std_id: std.std_id
      }, (array) => {
        this.infoStdArray = array;
        this.afertCertIdRequest();
      }, {
        ErrorCallback: this.afertCertIdRequest.bind(this)
      });
    };
    let msg = `确定要将考生【${std.std_name}】移除排队队列吗？`;
    if (this.currentRoom.group.pack_flag !== 'Active') {
      msg = `确定要将考生【${std.std_name}】移除排队队列吗？移除该考生，该考生后面的组内排序将往前移，请注意及时更换号牌！`;
    }
    MsgService.confirmAlert(msg, fn);

  }

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


  /***************
   * 创建视频考场
   */
  createVideoRoom() {
    this.qrcode = environment.webRoot + 'exam/interview/room/video/qrcode.htm?ly_room_id=' + this.currentRoom.ly_room_id;
  }

  noticeInRoom(std) {
    // 通知进场
    MsgService.confirmAlert(`确定通知考生${std.std_name}进场候考吗？`, () => {
      AjaxService.request('exam/interview/room/video/notice.htm', {
        std_id: std.std_id,
        ly_room_id: this.currentRoom.ly_room_id,
        ly_group_id: this.currentRoom.ly_group_id
      }, () => {
        MsgService.successToastr('已向该考生发送微信通知！');
      });
    });
  }

  decode(src) {
    var config = {
      inputStream: {
        size: 800,
        singleChannel: false
      },
      locator: {
        patchSize: "medium",
        halfSample: true
      },
      decoder: {
        readers: [{
          format: "code_128_reader",
          config: {}
        }]
      },
      locate: true,
      src: src
    }
    var that = this;
    Quagga.decodeSingle(config, function (result) {
      if (!result) {
        MsgService.errorToastr("图片中没有条形码！");
        return false;
      }
      //识别结果
      console.log(result)
      if (result.codeResult) {
        that.checkin.cert_id = result.codeResult.code;
        $("#certid").val(result.codeResult.code);
        that.changeCertId();
        MsgService.successToastr("图片中的条形码为：" + result.codeResult.code);
      } else {
        MsgService.errorToastr("未识别到图片中的条形码！");
      }
    });
  }

  setCertIdFunc() {
    //套壳调用
    // window.webkit.messageHandlers.callCamera.postMessage("callCamera");
    //浏览器调用
    var that = this;
    var cameraInput = document.createElement('input')
    cameraInput.addEventListener("change", function (e: Event) {
      console.log(e)
      that.decode(URL.createObjectURL((<HTMLInputElement>e.target).files[0]));
    })
    //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();

  }


  initCameraSelection() {
    this.ishttps = 'https:' == document.location.protocol ? true : false;
     if(this.ishttps) {
      const self = this
      return Quagga.CameraAccess.enumerateVideoDevices()
        .then(function (devices) {
          if (devices!=null&&devices.length>1) {
            self.deviceId = devices[1].deviceId
          } else {
            self.deviceId = devices[0].deviceId
          }
          self.devices = devices
          self.init()
        });
    } else{
    }


  }

  init() {
    const self = this
    Quagga.init(this.states(), function (err) {
      if (err) {
        console.log(err);
      }
      Quagga.onDetected(function (data) {
        var code = data.codeResult.code;
        if (self.lastCode!=code) {
          self.lastCode=code
          self.checkin.cert_id = code;
          $("#certid").val(code);
          self.changeCertId();
        }
      });
      Quagga.start();
    });
  }
  states() {
    return {
      inputStream: {
        type: "LiveStream",
        target: document.getElementById('LiveStream'),
        constraints: {
          // width: { min: 350 },
          height: { min: 140 },
          facingMode: "environment",
          deviceId: this.deviceId,
          aspectRatio: { min: 1, max: 2 }
        }
      },
      locator: {
        patchSize: "medium",
        debug: {
          showCanvas: false,
          showPatches: false,
          showFoundPatches: false,
          showSkeleton: false,
          showLabels: false,
          showPatchLabels: false,
          showRemainingPatchLabels: false,
          boxFromPatches: {
            showTransformed: false,
            showTransformedBox: false,
            showBB: false
          }
        },
        halfSample: true
      },
      numOfWorkers: 1,
      multiple: false,
      frequency: 10,
      decoder: {
        readers: [{
          format: "code_128_reader",
          config: {}
        }]
      },
      locate: true
    }
  }


  searchTracks() {
    AjaxService.requestArray('exam/interview/room/tracks/search.htm', {cert_id: this.cert_id}, (array) => {
      this.tracksArr = array;
    });
  }

  //下载手账
  downloadHand() {
    AjaxService.requestMap('exam/inroom/hand/print.htm', {
      ly_room_id : this.currentRoom.ly_room_id
    }, (map) => {
      this.FuncService.ajaxDownload('frame/temporary/download.htm', {file_name: map['result']});
    });
  }

  downloadHandSimple() {
    AjaxService.requestMap('exam/inroom/hand/simple/print.htm', {
      ly_room_id : this.currentRoom.ly_room_id
    }, (map) => {
      this.FuncService.ajaxDownload('frame/temporary/download.htm', {file_name: map['result']});
    });
  }

}

