import {Component, OnDestroy, OnInit, ViewChild} from '@angular/core';
import { BsModalService } from 'ngx-bootstrap/modal';
import { AjaxService } from 'src/app/core/service/ajax.service';
import { FrameService } from 'src/app/core/service/frame.service';
import { MsgService } from 'src/app/core/service/msg.service';
import { FramePageComponent } from 'src/app/routes/frame/core/page/frame.page';

declare let laydate;
declare let printUtil;

/******************
 * 抽取考场
 */
@Component({
  selector: 'app-exam-room-extract',
  templateUrl: './exam-room-extract.component.html',
  styleUrls: ['./exam-room-extract.component.scss']
})
export class ExamRoomExtractComponent extends FramePageComponent implements OnInit, OnDestroy {

  checkin: any;
  agentArray = [];
  dateArray = [];
  groupArray = [];
  roomArray = [];
  currentStd;
  groupName: any;
  private intervalId: any;
  currentStep : any;
  @ViewChild('certid', {static: false}) certid;
  timeArr = []; //时段

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

  // 获取考试日期
  requestDateArray() {
    AjaxService.requestArray('exam/checkin/init/date.htm', this.checkin, (array) => {
      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;
    });
  }

  /*********************
   * 开始检录
   */
  startExtract() {
    // if (this.checkin.start_time === undefined || this.checkin.end_time === undefined) {
    //   MsgService.errorToastr('请输入开考时间段！');
    //   return;
    // }
    if(!this.checkin.time_range) {
      MsgService.errorToastr('请输入开考时间段！');
      return;
    }
    let arr = this.checkin.time_range.split('~');
    this.checkin.start_time = arr[0];
    this.checkin.end_time = arr[1];
    
    if (this.checkin.ly_group_id === undefined) {
      MsgService.errorToastr('请选择需要进行考场抽取的面试分组！');
      return;
    }
    this.getGroupName();
    AjaxService.request('exam/extract/start.htm', this.checkin, () => {
      this.currentStep = 'Extracting';
      this.intervalId = setInterval(this.totalCheckin.bind(this), FrameService.getParamValue('ExamCheckinTotalInterval', 10000));
    }, {RequestWithLoading: true});
  }

  //选择的分组名称
  getGroupName() {
    for(const group of this.groupArray) {
      if(group.ly_group_id === this.checkin.ly_group_id) {
        this.groupName = group.group_name;
      }
    }
  }

  goInit() {
    clearTimeout(this.intervalId);
    this.agentArray = [];
    this.dateArray = [];
    this.groupArray = [];
    this.roomArray = [];
    this.checkin = {start_time: '06:00', end_time: '23:00', checkin_type: 'cert_id'};
    this.groupName = "";
    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();
  }


  /***********
   * 修改了身份证号
   */
  changeCertId() {
    if (this.checkin.cert_id === undefined || $.trim(this.checkin.cert_id).length === 0)
      return;
    // 提交
    this.checkin.requesting = true;
    AjaxService.requestEntity('exam/extract/std.htm', this.checkin, (entity) => {
      this.currentStd = entity;
      this.afertCertIdRequest();
      MsgService.successToastr(`【${entity.std_name}】【${entity.cert_id}】考场已抽取！`);
      //打印小票
      if(this.autoPrint==true){
        this.goPrint();
      }
    }, {
      ErrorCallback: this.afertCertIdRequest.bind(this)
    });
  }

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

  }


  totalCheckin() {
    AjaxService.requestArray('exam/extract/total.htm', this.checkin, (array) => {
      this.roomArray = array;
    });
  }

  ngOnInit() {

  }

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

  /**
   * 一键抽取
   */
  allExtract() {
    let msg = "一键抽取会将分组内的所有考生抽取，确认要抽取吗？";
    this.requestWithThread('./exam/extract/stdAll.htm', this.checkin, {confirmMsg:msg});
  }

   //初始化时间控件
   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);
  }

  printOption: any;
  printDevice: any;
  autoPrint: any = true;

  //小票打印
  goPrint() {
    if (!this.currentStd) {
      return;
    }
    var html = "";
    html = "<div style='font-size:19px;'>&nbsp&nbsp" + this.currentStd.std_name + "&nbsp;</div><div style='font-size:16px;'>" + this.currentStd.cert_id + "</div>";
    if(this.currentStd.subjectArray && this.currentStd.subjectArray.length >0) {
      var face = this.currentStd.subjectArray[0];
      html = html + "<div style='font-size:11px;font-weight:bold;'>" + face.group_name + "：" + face.ly_room_addr + "(第" + face.ly_room_index + "考场)</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>";
    //     }
    //   }
    // });
   
    if (printUtil) {
      printUtil.startPrint(html, this.printDevice)
    }
  };

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

//所有可用的时段
requestGroupTime() {
  this.checkin.time_range = '';
  this.AjaxService.requestArray('layout/group/appointment/list/time.htm', this.checkin, (array) => {
    this.timeArr = array;
    for(let time of this.timeArr) {
      time.time_name = FrameService.getFrameDictText('ExamTimeType', time.time_type) +' ' + time.group_time.exam_start_time +"~" + time.group_time.exam_end_time;
      time.time_value = time.group_time.exam_start_time +'~' + time.group_time.exam_end_time;
    }
  });
}

}

