import {ChangeDetectorRef, 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 {FrameService} from '../../../../../core/service/frame.service';
import {FormBuilder, Validators} from '@angular/forms';
import {FrameDetailComponent} from '../../../../frame/core/detail/frame.detail';

declare let laydate;
declare let printUtil;

@Component({
  selector: 'app-entry',
  templateUrl: './entry.component.html',
  styleUrls: ['./entry.component.scss']
})
export class EntryComponent extends FrameDetailComponent implements OnInit, OnDestroy {

  schoolArr = [];
  batchArr = [];
  dateArr = [];
  groupArr = [];
  timeArr = []; // 所有的时段
  total: any;
  checkin: any;
  currentStd: any;
  private intervalId: any;
  @ViewChild('certid', {static: false}) certid;

  @ViewChild('printContent', {static: false}) printContent;
  step = 'Init';
  printOption: any;
  printDevice: any;
  autoPrint: any = true;
  math = Math;


  constructor(modalService: BsModalService, private cdr: ChangeDetectorRef, fb: FormBuilder) {
    super(modalService);
    this.goInit();
    this.detailForm = fb.group({
      std_height: [null, Validators.compose([Validators.required])],
      std_weight: [null, Validators.compose([Validators.required])],
      height: [null, Validators.compose([Validators.required])],
      lower_body_length: [null, Validators.compose([Validators.required])],
      shoulder_width: [null, Validators.compose([Validators.required])],
      chest_size: [null, Validators.compose([Validators.required])],
      girth_size: [null, Validators.compose([Validators.required])],
      hip_measurement: [null, Validators.compose([Validators.required])],
      upper_arm_circumference: [null, Validators.compose([Validators.required])],
      thigh_circumference: [null, Validators.compose([Validators.required])],
      calf_circumference: [null, Validators.compose([Validators.required])],
      ankle_circumference: [null, Validators.compose([Validators.required])],
      remark: [null, null],
    });
  }

  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() {
    let 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(schoolId: any) {
    this.AjaxService.requestArray('cf/school/batch/list.htm', {
      school_id: schoolId
    }, (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(batchId: any) {
    this.AjaxService.requestArray('ly/checkin/date/list.htm', {
      batch_id: batchId
    }, (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(batchId, this.dateArr[0].exam_date);
      }
    });
  }

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

  // 初始化时间控件
  getDate() {
    const _this = this;
    setTimeout(() => {
      laydate.render({
        elem: '#startTime',
        type: 'time',
        theme: '#0c6acf',
        trigger: 'click',
        format: 'HH:mm',
        done: (value) => {
          _this.checkin.start_time = value;
        }
      });
      laydate.render({
        elem: '#endTime',
        type: 'time',
        theme: '#0c6acf',
        format: 'HH:mm',
        trigger: 'click',
        done: (value) => {
          _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('ex/exStdEntryInfo/total.htm', this.checkin, (entity) => {
      this.total = entity;
    });
  }

  changeCertId() {
    if (this.checkin.cert_id === undefined || $.trim(this.checkin.cert_id).length === 0)
      return;
    this.checkin.requesting = true;
    AjaxService.requestEntity('ex/exStdEntryInfo/std.htm', this.checkin, (entity) => {

      this.currentStd = entity;
      this.currentEntity = entity;
      // this.currentEntity.remark=this.currentEntity.remark||'上下身差值为下身长减去上身长';
      this.afterCertIdRequest();
    }, {
      ErrorCallback: this.afterCertIdRequest.bind(this)
    });
  }

// 结果回调
  afterCertIdRequest() {
    this.checkin.requesting = false;
    this.certid.nativeElement.focus();
    this.certid.nativeElement.select();
  }

// 打印小票
  goPrint() {
    if (!this.currentEntity) {
      return;
    }
    const html = this.printContent.nativeElement;
    if (printUtil) {
      printUtil.startPrint(html.innerHTML, this.printDevice)
    }
  };

  beforeSubmitForm(): boolean {
    this.currentEntity.id = this.currentStd.id;
    this.currentEntity.std_id = this.currentStd.std_id;
    this.currentEntity.school_id = this.checkin.school_id;
    this.currentEntity.batch_id = this.checkin.batch_id;
    return super.beforeSubmitForm();
  }

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

}
