import { Component, OnInit } from '@angular/core';
import { FormBuilder } from '@angular/forms';
import { BsModalRef } from 'ngx-bootstrap/modal';
import { ModalService } from 'src/app/core/service/modal.service';
import { FrameDetailComponent } from '../../../../frame/core/detail/frame.detail';

declare let laydate;

@Component({
  selector: 'app-task-dist-detail-new',
  templateUrl: './task-dist-detail-new.component.html',
  styleUrls: ['./task-dist-detail-new.component.scss']
})
export class TaskDistDetailNewComponent extends FrameDetailComponent implements OnInit {
  currStep = 'init';
  exam_date: any;
  groupArr = [];
  currGroupArr = [];
  provinceArr = [];
  std_province_flag : any;
  varietyArr = []; //品种
  currGroup:any; //当前操作的分组

  constructor(bsModalRef: BsModalRef, fb: FormBuilder) { 
    super(bsModalRef);
  }

  ngOnInit(): void {
    this.initProvince();
    this.AjaxService.requestArray('ex/task/dist/total.htm', {batch_id: this.ResponseEntity.batch_id}, (array) => {
      for(const g of array) {
        if(g.nolayout_total < 200) {
          g.std_num = g.nolayout_total;
        }
      }
      this.groupArr = array;
      for(const group of this.groupArr) {
        if(group.room_total == undefined) {
          group.room_total = 1;
        }
      }
    });
  }
  //初始化省份数组
  initProvince() {
    this.provinceArr.push({province_id : '', province_name: '不限'});
    this.provinceArr.push({province_id : 'Active', province_name: '省内'});
    this.provinceArr.push({province_id : 'InActive', province_name: '省外'});
  }

  //初始化时间控件
  getDate() {
    setTimeout(() => {
      laydate.render({
        elem:'#exam_dates',
        type:'date',
        theme:'#0c6acf',
        trigger: 'click',
        done:(value, date, endDate)=>{
          this.exam_date = value;
        }
      });
    }, 10);
  }

  //确认考场数量
  confirmRoom() {
    if(!this.exam_date) {
      this.MsgService.errorToastr('请选择评分日期！');
      return;
    }
    const array = [];
    for(const gx of this.groupArr) {
       if(gx.nolayout_total < 1)  continue;
       if(gx.std_num < 1 && gx.room_total < 1) continue;
       for(let i = 1 ; i<=gx.room_total; i++) {
        const g = Object.assign({},gx);
        let rowspan = 1;
        if(i == 1) {
          rowspan = g.room_total;
        }
        g.rowspan = rowspan;
        g.room_seq = i;
        g.room_addr = `第${i}考场`;
        g.std_sex = '不限';
        g.std_province_flag = '';
        array.push(g);
       }
    }
    if(array.length == 0) {
      this.MsgService.errorToastr('至少需要一个任务！');
      return;
     }
    this.currGroupArr = array;
    this.currStep = 'room';
  }

  //添加品种
  addVariety(v) {
    this.AjaxService.requestArray('ex/task/dist/variety/stdnum.htm', {ly_group_id: v.ly_group_id}, (array) => {
      this.varietyArr = array;
      let order_num = 1;
      for(let variety of this.varietyArr) {
        if(!variety.std_sex) {
          variety.std_sex = '不限';
        }
        if(!variety.std_province_flag){
          variety.std_province_flag = '';
        }
      }
      this.currGroup = v;
      this.currStep = 'variety';
    });
  }

  //确认品种的各考生数量
  confirmVariety() {
    let arr = [];
    for(let variety of this.varietyArr) {
        if(variety.real_std_total == 0 || !variety.real_std_total) continue;
        arr.push(variety);
    }
    if(arr.length == 0) {
      this.MsgService.errorToastr('请至少设置一个品种！');
      return;
    }
    //判断考生的数量
    for(let v of arr) {
      //无限制
      if(v.std_sex == '不限' && !v.std_province_flag) {
        if(v.real_std_total > v.std_total) {
          this.MsgService.errorToastr(v.variety_name +'的考生数量大于剩余未分发的考生数量！');
          return;
        }
      }
      //只限制性别
      if(v.std_sex !== '不限' && !v.std_province_flag) {
        if(v.std_sex == '男' && v.real_std_total > v.male_total){
          this.MsgService.errorToastr(v.variety_name +'的考生数量大于剩余未分发的考生数量！');
          return;
        }
        if(v.std_sex == '女' && v.real_std_total > v.female_total){
          this.MsgService.errorToastr(v.variety_name +'的考生数量大于剩余未分发的考生数量！');
          return;
        }
      }
      //只限制省份
      if(v.std_sex == '不限' && v.std_province_flag) {
        if(v.std_province_flag == 'Active' && v.real_std_total > v.in_province_total) {
          this.MsgService.errorToastr(v.variety_name +'的考生数量大于剩余未分发的考生数量！');
          return;
        }
        if(v.std_province_flag == 'InActive' && v.real_std_total > v.out_province_total) {
          this.MsgService.errorToastr(v.variety_name +'的考生数量大于剩余未分发的考生数量！');
          return;
        }
      }
    }
    for(let group of this.currGroupArr) {
      if(group.ly_group_id === this.currGroup.ly_group_id && group.room_seq == this.currGroup.room_seq) {
        group.varietyArr = this.varietyArr;
        group.real_std_total = this.getStdNum();
      }
    }
    this.currStep = 'room';
  }

  getStdNum(): number {
    let std_num = 0;
    for(let variety of this.varietyArr) {
      std_num += (!variety.real_std_total) ? 0 : variety.real_std_total;
    }
    return std_num;
  }

  //查看设置的品种
  viewVariety(v) {
    for(let group of this.currGroupArr) {
      if(v.ly_group_id == group.ly_group_id && v.room_seq == group.room_seq) {
        this.varietyArr = group.varietyArr;
      }
    }
    //排序
    this.varietyArr.sort(this.compare('order_num'));
    this.currStep = 'variety';
    this.currGroup = v;
  }

  //排序函数
  compare (prop) {
    return function (obj1, obj2) {
        var val1 = obj1[prop];
        var val2 = obj2[prop];
        if (!isNaN(Number(val1)) && !isNaN(Number(val2))) {
            val1 = Number(val1);
            val2 = Number(val2);
        }
        if (val1 < val2) {
            return -1;
        } else if (val1 > val2) {
            return 1;
        } else {
            return 0;
        }            
    } 
  }

  resetRoom() {
    this.MsgService.confirmAlert('重新设置考场后，该页面设置的相关信息，需要重新设置。确定要重新设置考场吗？', () => {
      this.currStep = 'init';
    });
  }

  //确认分发
  confirmSendTask() {
    for(const gx of this.currGroupArr) {
      gx.real_std_total = parseInt(gx.real_std_total+'',10);
      if(!gx.real_std_total || gx.real_std_total < 1) {
        this.MsgService.errorToastr('考生数量需要大于等于1，请检查！');
        return ;
      }
    }
    //判断是否存在考场
    this.AjaxService.requestEntity('ex/task/dist/room/exists.htm', {
      exam_date: this.exam_date, 
      room_json: JSON.stringify(this.currGroupArr)}, (entity) => {
        let remark = '定要分发任务吗？';
        if(entity && entity.group_name) {
          remark = '分组【' + entity.group_name +'】已经存在考场，确定还要分发吗？';
        }
        //确定分发
        this.MsgService.confirmAlert(remark, () => {
          this.AjaxService.requestEntity('ex/task/dist/new/save.htm', {
            school_id: this.ResponseEntity.school_id,
            batch_id : this.ResponseEntity.batch_id,
            exam_date: this.exam_date,
            room_json: JSON.stringify(this.currGroupArr)
          }, (entity) => {
            ModalService.showThreadWindow(this.framePageComponent.bsService, entity, {threadTitle: '正在分发任务，请稍等'});
              this.closeWindow();
          }, {RequestWithLoading: true});
        });
      });
  }

}




