import { Component, OnInit } from '@angular/core';
import { BsModalService } from 'ngx-bootstrap/modal';
import { AjaxService } from 'src/app/core/service/ajax.service';
import { MsgService } from '../../../../core/service/msg.service';
import { FramePageComponent } from '../../../frame/core/page/frame.page';
import { WishPlanGroupComponent } from '../wish-plan-group/wish-plan-group.component';

@Component({
  selector: 'app-wish-plan',
  templateUrl: './wish-plan.component.html',
  styleUrls: ['./wish-plan.component.scss']
})
export class WishPlanComponent extends FramePageComponent implements OnInit {

  constructor(private modalService: BsModalService) {
    super(modalService);
   }

  ngOnInit(): void {
  }


  uploadCallback() {
    MsgService.successAlert('专业计划导入成功！');
  }

  mergeGroup() {
    let arr = [];
   let records =  this.pager.getRecords();
   for(const r of records ) {
     if(r.checked) {
       arr.push(r);
     }
   }
   if(arr.length < 2) {
    MsgService.warningToastr('请至少选择2个专业');
    return;
   }
   for(const r of arr) {
     if(r.wish_group) {
       MsgService.warningAlert('不能选择已经分组的专业');
       return;
     }
   }
   this.showComponentModal(WishPlanGroupComponent, {
    ResponseArray: arr,
    closeCallback: this.pager.reload()
    });
  }

  breakGroup() {
    let arr = [];
    let records =  this.pager.getRecords();
    for(const r of records ) {
      if(r.checked) {
        arr.push(r);
      }
    }
    if(arr.length < 2) {
      MsgService.warningToastr('请至少选择2个专业');
      return;
     }
     let wish_ids = [];
     let group_arr = [];
     for(const r of arr) {
      if(!r.wish_group) {
        MsgService.warningAlert('需选择已合并的分组');
        return;
      }
      wish_ids.push(r.wish_id);
      group_arr.push(r.wish_group);
    }
    if(group_arr.length>0) {
      let num = this.findArrNum(group_arr, group_arr[0]);
      if(num != wish_ids.length) {
        MsgService.errorAlert('请选择同样的分组！');
        return;
      }
    }
    MsgService.confirmAlert('确定要打算专业分组吗？', () => {
      AjaxService.request('wish/plan/break.htm', {
        wish_ids: wish_ids
      }, () => {
        MsgService.successToastr('打散分组成功');
        this.pager.reload();
      });
    });
  }

  findArrNum(arr, wish_group) {
    let num = 0;
    if(!arr || arr.length == 0) {
      MsgService.errorAlert('数组为空');
      return;
    }
    for(const r of  arr) {
      if(r == wish_group) {
        num ++;
      }
    }
    return num;
  }
}
