import { Component, OnDestroy, OnInit, ViewChild } from '@angular/core';
import { BsModalService } from 'ngx-bootstrap/modal';
import { FramePageComponent } from '../../../../frame/core/page/frame.page';

declare var Quagga: any;
@Component({
  selector: 'app-inroom-std',
  templateUrl: './inroom-std.component.html',
  styleUrls: ['./inroom-std.component.scss']
})
export class InroomStdComponent  extends FramePageComponent implements OnInit,OnDestroy {

  currentStep = 'Init';
  inroom: any;
  currentRoom: any;
  room_key:any;
  timeArr= [];
  judgeArr = [];
  initRoom : any;
  ishttps=false;
  currentStd: any;
  infoStdArray= [];
  totalRoom: any;
  cert_id: any;
  tracksArr = [];

  deviceId: any;
  devices: any;
  lastCode="";

  private intervalId: any;
  @ViewChild('certid', { static: false }) certid;


  constructor(modalService: BsModalService) { 
    super(modalService);
    this.inroom = {};
  }
 

  ngOnInit(): void {
  }


  //初始化
  goInit() {
    this.room_key='';
    this.inroom = {};
    this.initRoom = {};
    this.judgeArr = [];
    this.timeArr = [];
    this.infoStdArray = [];
    this.currentRoom = {};
    this.currentStd = {};
    this.totalRoom = {};
    this.currentStep = 'Init';
    clearTimeout(this.intervalId);
  }

  //根据密钥-查找考场相关信息
  changeRoomKey() {
    if (this['room_key'] === undefined || $.trim(this['room_key']).length === 0)
      return;
    this.AjaxService.requestEntity('ly/room/interview/find.htm', { room_key: this.room_key }, (entity) => {
      this.initRoom = entity;
      this.currentRoom = entity.room;
      this.inroom.ly_room_id = this.currentRoom.ly_room_id;
      this.timeArr = entity.timeArr;
      this.currentStep = 'Confirm';
      this.checkRoomStatus();
    }, {
      MsgType: 'Swal'
    });
  }

  //检测考场评委的状态
  checkRoomStatus() {
    if (this.currentRoom.exam_status === 'Judge') {
      this.checkJudgeLogin();
      // 等待评委登陆
      this.intervalId = setInterval(this.checkJudgeLogin.bind(this), 5000);
    }
  }

  //检查评委是否登录
  checkJudgeLogin() {
    this.AjaxService.requestEntity('ly/room/interview/judge/list.htm', { ly_room_id: this.currentRoom.ly_room_id }, (entity) => {
      this.currentRoom = entity.room;
      this.judgeArr = entity.judgeArr;
      if (this.currentRoom.exam_status !== 'Judge') {
        clearTimeout(this.intervalId);
      }

      this.checkRommStatusByJudges(this.judgeArr);
    });
  }

  //检查所有评委登陆状态 更新考场状态
  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';
    }
}

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


//考生确认
changeCertId() {
  if ($("#certid")) {
    this.inroom.cert_id = $("#certid").val();
  }
  if (this.inroom.cert_id === undefined || $.trim(this.inroom.cert_id).length === 0)
    return;
  // 提交
  this.inroom.requesting = true;
  this.AjaxService.requestMap('ly/room/interview/std/info.htm', this.inroom, (map) => {

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

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


//考生进场
stdInRoom(std_id?) {
  // 判断
  const fn = () => {
    this.inroom.requesting = true;
    this.AjaxService.requestArray('ly/room/interview/std/inroom.htm', 
    { ly_room_id: this.currentRoom.ly_room_id, std_id: std_id }, (array) => {
      if (std_id !== undefined) {
        this.MsgService.successToastr(`考生【${this.infoStdArray[0].std_name}】已进场！`);
      } else {
        this.MsgService.successToastr(`本组供【${this.infoStdArray.length}】考生，已完成进场！`);
      }
      this.infoStdArray = array;
      this.afertCertIdRequest();
    }, {
      ErrorCallback: this.afertCertIdRequest.bind(this)
    });
  };
  if (this.initRoom.group.pack_flag !== 'Active') {
    if (std_id === undefined)
      return;
    fn.call(this);
  } else {
    if (this.infoStdArray.length !== this.initRoom.group.pack_std_num) {
      this.MsgService.confirmAlert(`该类型考试默认每组【${this.initRoom.group.pack_std_num}】个考生，该组目前有【${this.infoStdArray.length}】个考生，确定本组按照此数量进场考试吗？`, fn);
    } else
      fn.call(this);
  }
}

//考生的数量
requestTotal() {
  this.AjaxService.requestEntity('ly/room/interview/std/total.htm', this.inroom, (entity) => {
    this.totalRoom = entity;
  });
}

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

//取消排队
removeInfoStd(std) {
  const fn = () => {
    this.inroom.requesting = true;
    this.AjaxService.requestArray('ly/room/interview/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.initRoom.group.pack_flag !== 'Active') {
    msg = `确定要将考生【${std.std_name}】移除排队队列吗？移除该考生，该考生后面的组内排序将往前移，请注意及时更换号牌！`;
  }
  this.MsgService.confirmAlert(msg, fn);

}

inRoom() {
  if (this.timeArr !== undefined && this.timeArr.length > 0 && this.inroom.time_type === undefined) {
    this.MsgService.errorToastr('请选择面试时段！');
    return;
  }
  // 进入考场，获取之前排队的考生
  this.AjaxService.requestArray('ly/room/interview/inroom/std/list.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);
  });
}

//曲目查询
searchTracks() {
  this.AjaxService.requestArray('ly/room/interview/tracks/search.htm', 
  {
    cert_id: this.cert_id,
    school_id: this.currentRoom.school_id,
    ly_room_id: this.currentRoom.ly_room_id
  }, 
  (array) => {
    this.tracksArr = array;
  });
}

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.inroom.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
  }
}

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) {
      this.MsgService.errorToastr("图片中没有条形码！");
      return false;
    }
    //识别结果
    console.log(result)
    if (result.codeResult) {
      that.inroom.cert_id = result.codeResult.code;
      $("#certid").val(result.codeResult.code);
      that.changeCertId();
      this.MsgService.successToastr("图片中的条形码为：" + result.codeResult.code);
    } else {
      this.MsgService.errorToastr("未识别到图片中的条形码！");
    }
  });
}

setCertIdFunc() {
  //套壳调用
  // window.webkit.messageHandlers.callCamera.postMessage("callCamera");
  //浏览器调用
  var that = this;
  var cameraInput = document.createElement('input')
  cameraInput.addEventListener("change", function (e: Event) {
    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();

}


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