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 { FrameService } from '../../../../../core/service/frame.service';

declare let laydate;
declare let printUtil;

/*****************
 * 分组检录
 */
@Component({
  selector: 'app-exam-checkin-group',
  templateUrl: './exam-checkin-group.component.html',
  styleUrls: ['./exam-checkin-group.component.scss']
})
export class ExamCheckinGroupComponent extends FramePageComponent implements OnInit, OnDestroy {

  checkin: any;
  agentArray = [];
  dateArray = [];
  groupArray = [];
  totalMap = {};
  stdArray;
  currentStd;
  private intervalId: any;
  @ViewChild('certid', {static: false}) certid;
  currentStep:any;


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

  // 获取考试日期
  requestDateArray() {
    AjaxService.requestArray('exam/checkin/init/date.htm', this.checkin, (array) => {
      this.dateArray = [];
      if (FrameService.FrameOptr.optr_id !== 0) {
        for (const d of array) {
          if (d.ly_room_id === 0) {
            const s = [];
            s.push(d);
            this.dateArray = s;
            break;
          }
        }
        if(this.dateArray ===undefined || this.dateArray.length ==0) {
          this.dateArray = array;
        }
      } else {
        this.dateArray = array;
      }
      if (this.dateArray.length === 1) {
        this.checkin.exam_date = this.dateArray[0].exam_date;
        this.requestGroupArray();
      }
    });
  }

  // 获取分组
  requestGroupArray() {
    AjaxService.requestArray('exam/checkin/init/group.htm', this.checkin, (array) => {
      this.groupArray = array;
    });
  }

  checkAllGroup() {
    for (const s of this.groupArray) {
      s.checked = this.checkin.checked;
    }
  }

  /*********************
   * 开始检录
   */
  startCheckin() {
    if (this.checkin.start_time === undefined || this.checkin.end_time === undefined) {
      MsgService.errorToastr('请输入开考时间段！');
      return;
    }
    const array = [];
    for (const s of this.groupArray) {
      if (s.checked === true) {
        array.push(s.ly_group_id);
      }
    }
    if (array.length === 0) {
      MsgService.errorToastr('请选择需要检录的面试分组！');
      return;
    }
    this.checkin.group_ids = array;
    AjaxService.request('exam/checkin/start.htm', this.checkin, () => {
      this.currentStep = 'Checking';
      this.intervalId = setInterval(this.totalCheckin.bind(this), FrameService.getParamValue('ExamCheckinTotalInterval', 5000));
    }, {RequestWithLoading: true});
  }

  goInit() {
    clearTimeout(this.intervalId);
    this.agentArray = [];
    this.dateArray = [];
    this.groupArray = [];
    this.totalMap = {};
    this.stdArray = [];
    this.checkin = {start_time: '06:00', end_time: '23:00', checkin_type: 'cert_id'};
    this.getDate();

    // 获取所有考点
    AjaxService.requestArray('exam/checkin/init/agent.htm', {}, (array) => {
      this.agentArray = array;
      if (this.agentArray.length === 1) {
        this.checkin.agent_id = this.agentArray[0].ly_agent_id;
        this.requestDateArray();
      }
      this.currentStep = 'Init';
    });
    this.getPrint();
  }


  //初始化时间控件
  getDate() {
    let _this = this;
    setTimeout(() => {
      laydate.render({
        elem:'#startTime',
        type:'time',
        theme:'#0c6acf',
        trigger: 'click',
        format: 'HH:mm',
        done:(value, date, endDate)=>{
          _this.checkin.start_time = value;
        }
      });
      laydate.render({
        elem:'#endTime',
        type:'time',
        theme:'#0c6acf',
        format: 'HH:mm',
        trigger: 'click',
        done:(value, date, endDate)=>{
          _this.checkin.end_time = value;
        }
      });  
    }, 500);
  }


  /***********
   * 修改了身份证号
   */
  changeCertId() {
    if (this.checkin.cert_id === undefined || $.trim(this.checkin.cert_id).length === 0)
      return;
    // 提交
    this.checkin.requesting = true;
    AjaxService.requestEntity('exam/checkin/std.htm', this.checkin, (entity) => {
      const array = [];
      for (const sb of entity.subjectArray) {
        let flag = true;
        for (const a of array) {
          if (a.ly_group_id === sb.ly_group_id) {
            flag = false;
            break;
          }
        }
        if (flag) {
          array.push(sb);
        }
      }
      entity.GroupArray = array;
      this.currentStd = entity;
      if(this.autoPrint==true){
        this.goPrint();
      }
      MsgService.successToastr(`考生【${entity.cert_id}】检录成功`);
      this.afertCertIdRequest();
    }, {
      ErrorCallback: this.afertCertIdRequest.bind(this)
    });
  }

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

  }


  totalCheckin() {
    AjaxService.requestMap('exam/checkin/total.htm', this.checkin, (map) => {
      this.totalMap = map;
    });
  }

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

  ngOnInit() {
   
  }

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

  /*****************
   * 一键检录
   */
  allCheckIn() {
    if(this.checkin.start_time === undefined || this.checkin.end_time === undefined) {
      MsgService.errorToastr('请输入开考时间段！');
      return ;
    }
    const array = [];
    for(const s of this.groupArray) {
      if(s.checked === true) {
        array.push(s.ly_group_id);
      }
    }
    if(array.length === 0) {
      MsgService.errorToastr('请选择需要检录的面试分组！');
      return ;
    }
    this.checkin.group_ids = array;
    let msg = "一键检录会将分组内的所有考生检录，确认要检录吗？";
    this.requestWithThread('./exam/checkin/all.htm', this.checkin, {confirmMsg:msg});
  }
  
  printOption: any;
  printDevice: any;
  autoPrint: any = true;

  goPrint() {
    if (!this.currentStd) {
      return;
    }
    var html = "";
   // if($scope.printType == 'room'){
    html = "<div style='font-size:19px;'>&nbsp&nbsp" + this.currentStd.std_name + "&nbsp;</div><div style='font-size:16px;'>" + this.currentStd.cert_id + "</div>";
    this.currentStd.GroupArray.forEach(face => {
      if (face.subject_id == 24) {//subject_id==24 试唱
        html = html + "<div style='font-size:12px;font-weight:bold;'>" + face.subject_name + "</div>";
      } else {
        if (face.ly_room_addr) {
          html = html + "<div style='font-size:11px;font-weight:bold;'>" + face.group_name + "：" + face.ly_room_addr + "(" + face.ly_room_index + "号考场)</div>";
        }
      }
    });
    // }else{
    //  html = "<div style='font-size:20px;'>&nbsp&nbsp" + $scope.currentStdMap.StdReg.std_name + "</div>";
    //  html = html + "<div>&nbsp&nbsp<span style='font-size:20px;'>" + $scope.currentStdMap.StdReg.cert_id.substr(0,17) + "</span><span style='margin-left:5px;font-size:35px;font-weight:bold'>" + $scope.currentStdMap.StdReg.cert_id.charAt(17) + "</span></div>";
    //  html = html + "<div style='font-size:20px;'>&nbsp&nbsp代为保管 遗失不负</div>";
    // }
    if (printUtil) {
      printUtil.startPrint(html, this.printDevice)
    }
  };

  getPrint() {
    if (printUtil) {
      printUtil.getPrint((data) => {
        this.printOption = data;
        this.printDevice = data[0].name;
      })
    }
  }
  
  takePhoto() {
    
  }

}

