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;


@Component({
  selector: 'app-check-in-ym',
  templateUrl: './check-in-ym.component.html',
  styleUrls: ['./check-in-ym.component.scss']
})
export class CheckInYmComponent extends FramePageComponent implements OnInit {

  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();
  }

  downloaddata() {
    let entity = {
      report_name:'CheckYmReport',
      report_title :'朝阳区第十七届人大代表补选望京地区第120选区投票情况明细'
    };
    this.FuncService.ajaxDownload('frame/report/download.htm', entity);
  }

  // 获取考试日期
  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';
    });
  }


  //初始化时间控件
  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/checkinym/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(entity.std_province==='1')
        MsgService.warningAlert('首次检录时间：'+entity.real_checkin_time);
      else
        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);
  }
 
}
