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 { ModalService } from 'src/app/core/service/modal.service';
import { MsgService } from 'src/app/core/service/msg.service';
import { FramePageComponent } from 'src/app/routes/frame/core/page/frame.page';
import { ExamBatchRoomDetailComponent } from '../exam-batch-room-detail/exam-batch-room-detail.component';

declare let laydate;
declare let printUtil;

@Component({
  selector: 'app-exam-batch-room',
  templateUrl: './exam-batch-room.component.html',
  styleUrls: ['./exam-batch-room.component.scss']
})
export class ExamBatchRoomComponent extends FramePageComponent  implements OnInit, OnDestroy {

  currentStep : any;
  dateArray = [];
  groupArray = [];
  agentArray = [];
  roomArray = [];
  extract: any;
  groupName: any;
  currentStd: any;
  @ViewChild('certid', {static: false}) certid;

  //打印所用参数
  printOption: any;
  printDevice: any;
  autoPrint: any = true;
  roomTempArr = []; //选中的
  allStdArr = [];
  timeArr = []; //时段

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

  ngOnDestroy(): void {

  }

  ngOnInit(): void {

  }

  //初始化
  goInit() {
    this.agentArray = [];
    this.dateArray = [];
    this.groupArray = [];
    this.roomArray = [];
    this.extract = {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.extract.agent_id = this.agentArray[0].ly_agent_id;
        this.requestDateArray();
      }
      this.currentStep = 'Init';
    });
    //打印小票-初始化
    this.getPrint();
  }

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

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

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

  //小票打印
  goPrint() {
    if (!this.currentStd) {
      return;
    }
    var html = "";
      html += "</img><div style='top:15px;font-size:22px;font-weight:bold;text-align:center;'>北京外国语大学</div>";
      html += "<div style='top:5px;font-size:16px;font-weight:bold;text-align:center;'>2023年综合评价招生</div>";
      if(this.currentStd.subjectArray && this.currentStd.subjectArray.length >0) {
        var face = this.currentStd.subjectArray[0];
        html += "<div style='top:5px;font-size:20px;text-align:center;'>"+face.group_name+"抽签结果</div>";
        html += "<div style='top:15px;font-size:19px;'>考生姓名：" + this.currentStd.std_name+"&nbsp;</div>";
        html += "<div style='font-size:19px;'>备考室:四楼" + face.ly_room_waiting_addr + "</div>"
        html += "<div style='font-size:19px;'>考场号:" +  "第" + face.ly_room_index + "考场（"+face.ly_room_addr+"）</div>" 
      }
      html += "<div style='font-size:19px;font-weight:bold;'>序号:" + this.currentStd.queue_num + '</div>';
    if (printUtil) {
      printUtil.startPrint(html, this.printDevice)
    }
  };

  //开始抽取考场
  startExtract() {
    if(!this.extract.time_range) {
      MsgService.errorToastr('请输入开考时间段！');
      return;
    }
    let arr = this.extract.time_range.split('~');
    this.extract.start_time = arr[0];
    this.extract.end_time = arr[1];
    if (this.extract.ly_group_id === undefined) {
      MsgService.errorToastr('请选择需要进行考场抽取的面试分组！');
      return;
    }
    this.getGroupName();
    this.listRoom(true);
  }

  listRoom(flag) {
    this.roomTempArr = this.roomArray;
    AjaxService.requestArray('exam/extract/all/total.htm', this.extract, (array) => {
      this.roomArray  = array;
      this.currentStep = 'Extracting';
      if(flag) {
        for(const room of this.roomArray) {
          if (room.room_status=='Active')
            room.choose_flag = true;
        }
      } else {
        for(const room of this.roomArray) {
          for(const temp of this.roomTempArr) {
            if(parseInt(room.ly_room_id,10) == parseInt(temp.ly_room_id,10))  {
              room.choose_flag = temp.choose_flag;
            }
          }
        }
      }
    });
  }

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

 /***********
   * 修改了身份证号
   */
 changeCertId() {
  if (this.extract.cert_id === undefined || $.trim(this.extract.cert_id).length === 0)
    return;
  const roomIdsArr = new Array();
  for(const room of this.roomArray) {
    if(room.choose_flag) {
      roomIdsArr.push(room.ly_room_id);
    }
  }
  if(roomIdsArr.length == 0) {
    MsgService.successAlert('请至少选中一个考场');
    return;
  }
  //全选的情况
  var flag = false;
  if(this.roomArray.length == roomIdsArr.length) {
    for(const room of this.roomArray) {
      if(room.real_queue_total < room.pack_std_num) {
        flag = true;
        break;
      }
    }
    if(!flag) {
      MsgService.errorAlert('每个考场最多排队【' + this.roomArray[0].pack_std_num +"】人！请先将排队的考生入场。");
      return;
    }
  }
  // 提交
  this.extract.requesting = true;
  AjaxService.requestEntity('exam/extract/all/std/info.htm', {
    'room_ids[]': roomIdsArr,
    cert_id: this.extract.cert_id,
    exam_date: this.extract.exam_date,
    start_time: this.extract.start_time,
    end_time: this.extract.end_time
  }, (entity) => {
    this.currentStd = entity;
    this.allStdArr.push(this.currentStd);
    this.afertCertIdRequest();
    MsgService.successToastr(`【${entity.std_name}】【${entity.cert_id}】考场已抽取！`);
    this.listRoom(false);
    //打印小票
    if(this.autoPrint==true){
      this.goPrint();
    }
  }, {
    ErrorCallback: this.afertCertIdRequest.bind(this)
  });
}

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

  //单个考场入场
  startInRoom(ly_room_id, num) {
    const roomIdsArr = new Array();
    roomIdsArr.push(ly_room_id);
    if(num == 0) {
      MsgService.errorToastr('没有待进场的考生！');
      return;
    }
    this.MsgService.confirmAlert('确定要进场这' +  num +'个考生吗？', () => {
      AjaxService.request('exam/extract/all/batch/inroom.htm', {
        'room_ids[]': roomIdsArr,
      }, () => {
        MsgService.successToastr('进场成功！');
      this.listRoom(false);
      }, {RequestWithLoading: true});
    });

  }
  //批次入场
  allInroom() {
    MsgService.confirmAlert('确定要批量进场选中的考场吗？', () => {
      const roomIdsArr = new Array();
      for(const room of this.roomArray) {
        if(room.choose_flag) {
          roomIdsArr.push(room.ly_room_id);
        }
      }
      if(roomIdsArr.length == 0) {
        MsgService.errorAlert('请至少选中一个考场！');
        return;
      }
      this.requestWithThread('exam/extract/all/batch/inroom.htm',  {'room_ids[]': roomIdsArr}, {confirmMsg:''}, () => {
        this.listRoom(false);
      } );
    });
  }
  
  //排队所有考生
  allCheckin() {
    MsgService.confirmAlert('将所有考生排队选中的考场吗？', () => {
      const roomIdsArr = new Array();
      for(const room of this.roomArray) {
        if(room.choose_flag) {
          roomIdsArr.push(room.ly_room_id);
        }
      }
      if(roomIdsArr.length == 0) {
        MsgService.errorAlert('请至少选中一个考场！');
        return;
      }
      AjaxService.request('exam/extract/all/std/info/all.htm', {
        'room_ids[]': roomIdsArr,
      }, () => {
        MsgService.successToastr('排队成功！');
      this.listRoom(false);
      }, {RequestWithLoading: true});
    });
  }

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

  //所有可用的时段
  requestGroupTime() {
    this.extract.time_range = '';
    this.AjaxService.requestArray('layout/group/appointment/list/time.htm', this.extract, (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;
      }
    });
  }

  //显示详情窗口
  showModal(room) {
    this.onModalClose = () => {
      this.listRoom(false);
    };
    this.showComponentModal(ExamBatchRoomDetailComponent, {ResponseEntity: room});
  }

}
