import { ChangeDetectorRef, Component, 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-checkin-group',
  templateUrl: './checkin-group.component.html',
  styleUrls: ['./checkin-group.component.scss']
})
export class CheckinGroupComponent extends FramePageComponent  implements OnInit {

  schoolArr = [];
  batchArr = [];
  dateArr = [];
  groupArr = [];
  timeArr = []; //所有的时段
  total: any;
  checkin: any;
  currentStd: any;

  private intervalId: any;
  @ViewChild('certid', {static: false}) certid;
  step = 'Init';
  printOption: any;
  printDevice: any;
  autoPrint: any = true;

  constructor(modalService: BsModalService, private cdr : ChangeDetectorRef) {
    super(modalService);
    this.goInit();
   }

  ngOnInit(): void {
  }

  //初始化
  goInit() {
    clearTimeout(this.intervalId);
    this.schoolArr = [];
    this.batchArr = [];
    this.dateArr = [];
    this.groupArr = [];
    this.timeArr = [];
    this.checkin = {start_time: '06:00', end_time: '23:00', checkin_type: 'cert_id'};
    this.getDate();
    this.AjaxService.requestArray('cf/school/list.htm',{}, (array) => {
      this.schoolArr = array;
      if(this.schoolArr && this.schoolArr.length == 1) {
        this.checkin.school_id = this.schoolArr[0].school_id;
        this.listBatch(this.schoolArr[0].school_id);
      }
      this.step = 'Init';
    });
    this.requestTime();
    //打印小票
    this.getPrint();
  }

  //时段
  requestTime() {
    var flag = false;
    this.timeArr  = this.FrameService.getFrameDictArray('ExamTimeType');
    //判断是否已经包含
    for(const time of this.timeArr) {
      if(time.dict_value == '')  {
        flag = true;
        break;
      }
    }
    if(!flag) {
      this.timeArr.unshift({dict_text: '全天', dict_value: ''});
    }
    //设置默认值
    this.checkin.time_type = '';
  }

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

  //批次
  listBatch(school_id: any) {
    this.AjaxService.requestArray('cf/school/batch/list.htm', {
      school_id : school_id
    }, (array) => {
      this.batchArr = array;
      this.cdr.detectChanges();
      if(this.batchArr && this.batchArr.length == 1) {
        this.checkin.batch_id = this.batchArr[0].batch_id;
        this.listExamDate(this.batchArr[0].batch_id);
      }
    });
  }

  //考试日期
  listExamDate(batch_id: any) {
    this.AjaxService.requestArray('ly/checkin/date/list.htm', {
      batch_id : batch_id
    }, (array) => {
      this.dateArr = [];
      //非管理员权限控制
      if (FrameService.FrameOptr.optr_id !== 0) {
        for (const d of array) {
          if (d.ly_room_id === 0) {
            const s = [];
            s.push(d);
            this.dateArr = s;
            break;
          }
        }
        if(this.dateArr ===undefined || this.dateArr.length ==0) {
          this.dateArr = array;
        }
      } else {
        this.dateArr = array;
      }
      this.cdr.detectChanges();
      if(this.dateArr && this.dateArr.length == 1) {
        this.checkin.exam_date = this.dateArr[0].exam_date;
        this.listGroup(batch_id, this.dateArr[0].exam_date);
      }
    });
  }

  //分组
  listGroup(batch_id: any, exam_date: any) {
    this.AjaxService.requestArray('ly/checkin/group/list.htm', {
      batch_id: batch_id,
      exam_date: exam_date
    }, (array) => {
      this.groupArr = array;
      this.cdr.detectChanges();
    });
  }

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

  //选取选中
  checkAllGroup() {
    for (const s of this.groupArr) {
      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.groupArr) {
    if (s.checked === true) {
      array.push(s.ly_group_id);
    }
  }
  if (array.length === 0) {
    MsgService.errorToastr('请选择需要检录的面试分组！');
    return;
  }
  this.checkin.group_ids = array;
  this.AjaxService.request('ly/checkin/start.htm', this.checkin, () => {
    this.step = 'Checking';
    this.intervalId = setInterval(this.totalCheckin.bind(this), FrameService.getParamValue('ExamCheckinTotalInterval', 5000));
  }, {RequestWithLoading: true});
}

//人数统计
totalCheckin() {
  AjaxService.requestEntity('ly/checkin/total.htm', this.checkin, (entity) => {
    this.total = entity;
  });
}

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

//更新考生检录
changeCertId() {
  if (this.checkin.cert_id === undefined || $.trim(this.checkin.cert_id).length === 0)
      return;
  this.checkin.requesting = true;
  AjaxService.requestEntity('ly/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();
    }
    this.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();
}

//打印小票
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>";
  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)
  }
};

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

  showEntryInfo() {
    return this.batchArr.find(e=>e.batch_id===this.checkin.batch_id).checkin_random==='Active';
  }

  export() {
    const url = 'ly/checkin/nohave/export.htm';
    const param = this.checkin;
    this.FuncService.fileDownload(url, param);
  }
}
