import {Component, OnInit} from '@angular/core';
import {FormBuilder, Validators} from '@angular/forms';
import { BsModalRef } from 'ngx-bootstrap/modal';
import { FuncService } from '../../../../../core/service/func.service';
import { AjaxService } from '../../../../../core/service/ajax.service';
import { MsgService } from '../../../../../core/service/msg.service';
import { FrameDetailComponent } from '../../../../frame/core/detail/frame.detail';

declare let laydate;

@Component({
  selector: 'app-layout-interview-arrange',
  templateUrl: './layout-interview-arrange.component.html',
  styleUrls: ['./layout-interview-arrange.component.scss']
})
export class LayoutInterviewArrangeComponent extends FrameDetailComponent implements OnInit {
  curStep: any;
  timeGroupArray: any;
  roomArray: any;
  timeArray: any;
  timeFlag = false;
  timeMap;


  constructor(bsModalRef: BsModalRef, fb: FormBuilder) {
    super(bsModalRef);
    AjaxService.requestArray('layout/plan/time/group/list.htm', {}, (array) => {
      this.curStep = 'time';
      this.timeGroupArray = array;
    });
  }


  ngOnInit() {
    this.getDate();
  }

  initDefautEntity() {
    this.currentEntity.time_retain = 'InActive';
    this.currentEntity.focus_flag = 'InActive';
  }

  /***************
   * 修改考场数量
   */
  changeRoomTotal() {
    const array = [];
    if (this.currentEntity.room_total !== undefined) {
      this.currentEntity.room_total = parseInt(this.currentEntity.room_total, 10);
    }
    if (this.currentEntity.room_total >= 0) {
      if (this.roomArray === undefined) {
        this.roomArray = [];
      }
      for (let i = 1; i <= this.currentEntity.room_total; i++) {
        if (this.roomArray.length >= i) {
          array.push(this.roomArray[i - 1]);
        } else {
          array.push({
            room_order: i
          });
        }
      }
    }
    this.roomArray = array;
  }


  /*****************
   * 更改时段分组
   */
  changeTimeGroup() {
    if (this.currentEntity.time_group === undefined || this.currentEntity.time_group === '') {
      this.timeArray = [];
      return;
    }

    if (this.currentEntity.group_end_date === '')
      this.currentEntity.group_end_date = undefined;
    AjaxService.requestArray('layout/group/time/cal.htm', this.currentEntity, (array) => {
      this.timeArray = array;
    }, {ReqeustWithLoading: true});
  }


  /*****************
   * 增加一个时段
   */
  addTime() {
    if (this.currentEntity === undefined) {
      MsgService.errorToastr('请填写考试时间信息！');
      return;
    }
    if (this.currentEntity.exam_start_time === undefined || $.trim(this.currentEntity.exam_start_time).length === 0) {
      MsgService.errorToastr('请填写考试开始时间！');
      return;
    }
    if (this.currentEntity.exam_end_time === undefined || $.trim(this.currentEntity.exam_end_time).length === 0) {
      MsgService.errorToastr('请填写考试结束时间！');
      return;
    }
    if (this.currentEntity.time_type === undefined) {
      MsgService.errorToastr('请选择属于哪个大时段！');
      return;
    }

    this.currentEntity.time_json = JSON.stringify(this.timeArray);

    AjaxService.requestArray('layout/group/time/add.htm', this.currentEntity, (array) => {
      FuncService.sortArray(array, 'exam_start_time');
      this.timeArray = array;
      this.currentEntity.exam_start_time = this.currentEntity.exam_end_time;
      this.currentEntity.exam_end_time = undefined;
      this.currentEntity.time_type = undefined;
    }, {ReqeustWithLoading: true});

  }

  /*****************
   * 删除某个时段
   */
  deleteTime(time) {
    const array = [];
    for (const t of this.timeArray) {
      if (t.time_seq !== time.time_seq) {
        array.push(t);
      }
    }
    this.timeArray = array;
  }

  /*****************
   * 确认时段信息
   */
  confirmTime() {
    if (this.roomArray === undefined || this.roomArray.length < 1) {
      return;
    }
    for (let i = 0; i < this.roomArray.length; i++) {
      const room = this.roomArray[i];
      if (room.room_addr === undefined || room.room_addr.length === '') {
        MsgService.errorToastr(`请输入第【${i + 1}】考场的考场地址！`);
        return;
      }
    }
    FuncService.sortArray(this.timeArray, 'exam_start_time');
    this.currentEntity.time_json = JSON.stringify(this.timeArray);
    this.currentEntity.room_json = JSON.stringify(this.roomArray);
    this.currentEntity.app_json = undefined;
    // 提交到后台，计算结束时间等
    AjaxService.requestMap('layout/group/time/confirm.htm', this.currentEntity, (map) => {
      this.timeMap = map;
      this.calArrangeTotal();
      this.curStep = 'detail';
    }, {ReqeustWithLoading: true});

  }


  changeTimeStdTotal(time) {
    this.calArrangeTotal();
  }

  /*******************
   * 计算已编排的数量
   */
  calArrangeTotal() {
    let country_total = 0, province_total = 0, outside_total = 0;
    for (const date of this.timeMap['DateArray']) {
      for (const time of this.timeMap['TimeMap'][date]) {
        if (time.country_total !== undefined) {
          country_total += time.country_total;
        }
        if (time.province_total !== undefined) {
          province_total += time.province_total;
        }
        if (time.outside_total !== undefined) {
          outside_total += time.outside_total;
        }
      }
    }
    this.timeMap['CountryTotal'] = country_total;
    this.timeMap['ProvinceTotal'] = province_total;
    this.timeMap['OutsideTotal'] = outside_total;
  }

  deleteDateTime(date, time) {
    const array = [];
    for (const t of this.timeMap['TimeMap'][date]) {
      if (t.exam_start_time === time.exam_start_time && t.exam_end_time === time.exam_end_time) {
      } else {
        array.push(t);
      }
    }
    this.timeMap['TimeMap'][date] = array;
    this.calArrangeTotal();
  }

  // 编排
  arrangeGroup() {
    // 判断
    if (this.currentEntity.province_flag === 'Active') {
      if (this.currentEntity.province_std_total > 0 && (this.timeMap['ProvinceTotal'] === undefined || this.timeMap['ProvinceTotal'] < this.currentEntity.province_std_total)) {
        MsgService.errorToastr('省内编排容量小于参加考试人数，请检查！');
        return;
      }
      if (this.currentEntity.outside_std_total > 0 && (this.timeMap['OutsideTotal'] === undefined || this.timeMap['OutsideTotal'] < this.currentEntity.outside_std_total)) {
        MsgService.errorToastr('外省编排容量小于参加考试人数，请检查！');
        return;
      }
    } else {
      if (this.timeMap['CountryTotal'] === undefined || this.timeMap['CountryTotal'] < this.currentEntity.group_std_total) {
        MsgService.errorToastr('编排容量小于参加考试人数，请检查！');
        return;
      }
    }

    // 设置属性,
    const rArray = [], tArray = [];
    for (const date  of this.timeMap['DateArray']) {
      for (const t of this.timeMap['TimeMap'][date]) {
        t.ly_exam_date = date;
        t.appointment_id = t.time_seq;
        tArray.push(t);
      }

      for (const t of this.timeMap['RoomMap'][date]) {
        t.exam_date = date;
        rArray.push(t);
      }
    }
    this.currentEntity.time_json = JSON.stringify(this.timeArray);
    this.currentEntity.room_json = JSON.stringify(rArray);
    this.currentEntity.app_json = JSON.stringify(tArray);

    MsgService.confirmAlert('确定要保存编排信息吗？', () => {
      AjaxService.request('layout/group/interview/arrange.htm', {
        ly_group_id: this.currentEntity.ly_group_id,
        room_total: this.currentEntity.room_total,
        time_retain:this.currentEntity.time_retain,
        time_json: JSON.stringify(this.timeMap.TimeArray),
        room_json: JSON.stringify(rArray),
        app_json: JSON.stringify(tArray)
      }, () => {
          MsgService.successAlert('编排信息已保存！', () => {
            this.closeWindow();
          });
      }, {RequestWithLoading: true});
    });
  }


  //初始化时间控件
  getDate(index?) {
    setTimeout(() => {
      laydate.render({
        elem:'#group_start_date',
        type:'date',
        theme:'#0c6acf',
        trigger: 'click',
        done:(value, date, endDate)=>{
          this.currentEntity.group_start_date = value;
        }
      });
      laydate.render({
        elem:'#group_end_date',
        type:'date',
        theme:'#0c6acf',
        trigger: 'click',
        done:(value, date, endDate)=>{
          this.currentEntity.group_end_date = value;
        }
      });
      laydate.render({
        elem:'#exam_start_time',
        type:'time',
        theme:'#0c6acf',
        trigger: 'click',
        format: 'HH:mm',
        done:(value, date, endDate)=>{
          this.currentEntity.exam_start_time = value;
        }
      });
      laydate.render({
        elem:'#exam_end_time',
        type:'time',
        theme:'#0c6acf',
        trigger: 'click',
        format: 'HH:mm',
        done:(value, date, endDate)=>{
          this.currentEntity.exam_end_time = value;
        }
      });
    laydate.render({
      elem:'#exam_start_time1',
      type:'time',
      theme:'#0c6acf',
      trigger: 'click',
      format: 'HH:mm',
      done:(value, date, endDate)=>{
        this.timeArray[0].exam_start_time = value;
      }
    });
    laydate.render({
      elem:'#exam_start_time2',
      type:'time',
      theme:'#0c6acf',
      trigger: 'click',
      format: 'HH:mm',
      done:(value, date, endDate)=>{
        this.timeArray[1].exam_start_time = value;
      }
    });
    laydate.render({
      elem:'#exam_start_time3',
      type:'time',
      theme:'#0c6acf',
      trigger: 'click',
      format: 'HH:mm',
      done:(value, date, endDate)=>{
        this.timeArray[2].exam_start_time = value;
      }
    });
    laydate.render({
      elem:'#exam_start_time4',
      type:'time',
      theme:'#0c6acf',
      trigger: 'click',
      format: 'HH:mm',
      done:(value, date, endDate)=>{
        this.timeArray[3].exam_start_time = value;
      }
    });
    laydate.render({
      elem:'#exam_start_time5',
      type:'time',
      theme:'#0c6acf',
      trigger: 'click',
      format: 'HH:mm',
      done:(value, date, endDate)=>{
        this.timeArray[4].exam_start_time = value;
      }
    });
    laydate.render({
      elem:'#exam_end_time1',
      type:'time',
      theme:'#0c6acf',
      trigger: 'click',
      format: 'HH:mm',
      done:(value, date, endDate)=>{
        this.timeArray[0].exam_end_time = value;
      }
    });
    laydate.render({
      elem:'#exam_end_time2',
      type:'time',
      theme:'#0c6acf',
      trigger: 'click',
      format: 'HH:mm',
      done:(value, date, endDate)=>{
        this.timeArray[1].exam_end_time = value;
      }
    });
    laydate.render({
      elem:'#exam_end_time3',
      type:'time',
      theme:'#0c6acf',
      trigger: 'click',
      format: 'HH:mm',
      done:(value, date, endDate)=>{
        this.timeArray[2].exam_end_time = value;
      }
    });
    laydate.render({
      elem:'#exam_end_time4',
      type:'time',
      theme:'#0c6acf',
      trigger: 'click',
      format: 'HH:mm',
      done:(value, date, endDate)=>{
        this.timeArray[3].exam_end_time = value;
      }
    });
    laydate.render({
      elem:'#exam_end_time5',
      type:'time',
      theme:'#0c6acf',
      trigger: 'click',
      format: 'HH:mm',
      done:(value, date, endDate)=>{
        this.timeArray[4].exam_end_time = value;
      }
    });
    }, 500);
  }
}
