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

declare let laydate;

@Component({
  selector: 'app-exam-video-dist-new',
  templateUrl: './exam-video-dist-new.component.html',
  styleUrls: ['./exam-video-dist-new.component.scss']
})
export class ExamVideoDistNewComponent extends FrameDetailComponent implements OnInit {

  groupArray;
  currStep = 'init';
  currGroupArray;
  exam_date;
  provinceArr = [];
  varietyArr = [];
  currGroup: any;

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

   ngOnInit() {
    this.initProvince();
    AjaxService.requestArray('exam/video/dist/total.htm', {ly_agent_id: this.ResponseEntity}, (array) => {
      for (const g of array) {
        if (g.nolayout_total <= 100)
          g.ly_std_total = g.nolayout_total;
        else 
          g.ly_std_total =  100;  
      }
      this.groupArray = array;
      for(const group of this.groupArray) {
        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: '省外'});
  }

  // 确认考场数量
  confirmTotal() {
    if(!this.exam_date) {
      this.MsgService.errorToastr('请选择评分日期！');
      return;
    }
    const array = [];
    for (const gx of this.groupArray) {
      if (gx.room_total < 1) {
        continue;
      }
      let room_std = Math.floor(gx.exam_seconds / gx.room_total);
      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 = '';
        array.push(g);
      }
    }
    if (array.length === 0) {
      MsgService.errorToastr('至少需要一个任务！');
      return;
    }
    this.currGroupArray = array;
    this.currStep = 'room';
  }

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

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

  //查看设置的品种
  viewVariety(v) {
    for(let group of this.currGroupArray) {
      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;
        }            
    } 
  }

 //确认品种的各考生数量
 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) {
      if(v.real_std_total > v.std_total) {
        this.MsgService.errorToastr(v.variety_name +'的考生数量大于剩余未分发的考生数量！');
        return;
      }
    }
    //只限制性别
    if(v.std_sex !== '不限' && !v.std_province) {
      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) {
      if(v.std_province == 'Active' && v.real_std_total > v.in_province_total) {
        this.MsgService.errorToastr(v.variety_name +'的考生数量大于剩余未分发的考生数量！');
        return;
      }
      if(v.std_province == 'InActive' && v.real_std_total > v.out_province_total) {
        this.MsgService.errorToastr(v.variety_name +'的考生数量大于剩余未分发的考生数量！');
        return;
      }
    }
  }
  for(let group of this.currGroupArray) {
    if(group.ly_group_id === this.currGroup.ly_group_id && group.room_seq == this.currGroup.room_seq) {
      group.varietyArr = this.varietyArr;
      group.ly_std_total = this.getStdNum();
    }
  }
  this.currStep = 'room';
}

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

confirmRoom() {
  if (this.exam_date === undefined) {
    MsgService.errorToastr('请输入视频评分日期！');
    return;
  }
  for (const gx of this.currGroupArray) {
    gx.ly_std_total = parseInt(gx.ly_std_total + '', 10);
    if (isNaN(gx.ly_std_total) || gx.ly_std_total < 1) {
      MsgService.errorToastr( '【' + gx.group_name + '】第【' + gx.room_seq+ '】考场，考生数量错误，请检查！');
      return;
    }
  }
  MsgService.confirmAlert('确定保存考场配置并分发任务吗？', () => {
    AjaxService.requestEntity('exam/video/dist/new/save.htm', {
      ly_agent_id: this.ResponseEntity,
      exam_date: this.exam_date,
      room_json: JSON.stringify(this.currGroupArray)
    }, (entity) => {
      ModalService.showThreadWindow(this.framePageComponent.bsService, entity, {threadTitle: '正在整理数据，请稍候'});
      this.closeWindow();
    }, {RequestWithLoading: true});
  });
}

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

}
