import { Component, OnInit, TemplateRef, ViewChild } from "@angular/core";
import { FormBuilder, Validators } from '@angular/forms';
import { CustomValidators } from 'ng2-validation';
import { BsModalService } from "ngx-bootstrap/modal";
import { FlexTableComponent } from "../../../../shared/common/FlexTable.component";
import { AppComponent } from "../../../../app.component";
import { FrameRequest } from "../../../../shared/frame/frame-request";
import { FramePagerComponent } from "../../../../core/pager/pager.component";
import { FrameValidator } from "../../../../shared/frame/Frame-validator";
import { FrameUploaderComponent } from '../../../../core/uploader/uploader.component';
import { ActivatedRoute,Params } from "@angular/router";

@Component({
  selector: "app-std-std_enrol-course_volume",
  templateUrl: "./std-enrol-course-volume.component.html",
  styleUrls: ["./std-enrol-course-volume.component.scss"]
})


export class StdEnrolCourseVolumeComponent extends FlexTableComponent
  implements OnInit {

    @ViewChild('coursePager')
    coursePager: FramePagerComponent;

  public query = {
    query:"",
    year_code: "",
    enrol_agent_id: "",
    exam_batch:""
  };
 
  QUERY_URL = "std/stdEnrolCourseVolume/page.htm";
  EDIT_URL = "std/stdEnrolCourseVolume/edit.htm";
  GET_URL = "std/stdEnrolCourseVolume/get.htm";
  ADD_URL = "std/stdEnrolVolume/add.htm";

  TIME_URL = "pl/plExamTime/listtime.htm";
 

  CURR_YEAR_CODE_URL = "pl/plExamTime/getCurrentYearCode.htm";
  YEAR_CODE_URL = "pl/plExamTime/list.htm";
  AREA_LIST_URL = "cf/cfOrganization/list.htm?org_type=4&status=1"; //考区列表
  GET_DEPT_URL = "frame/optr/getDeptType.htm"; //登录用户所属机构类型

  COURSE_PAGE_URL = "pl/plCourse/pagePlMergePublishPlan.htm";
  
  examAgentArray = [];
  yearCodeArray = [];
  logOrgType = "-1";

  yesCourses: any;
  flag: boolean = false;


  constructor(
    public bsModalService: BsModalService,
	fb: FormBuilder,
	private activeInfo:ActivatedRoute
  ) {
    super();
    
    this.formModel = fb.group({
      id: [null],
     // 'year_code': [null, Validators.required],
      'enrol_agent_id': [null, Validators.required],
      'exam_batch': [null, Validators.required],
      'max_volume': [null, Validators.required],
      //'exam_batch_name': [null, Validators.required],
     // 'year_code_name':[null, Validators.required],
    });
  }

  search(param) {
    if (!this.query.enrol_agent_id) {
      this.query.enrol_agent_id = "";
    }
    if (!this.query.year_code) {
      this.query.year_code = "";
    }

    if (!this.query.exam_batch) {
      this.query.exam_batch = "";
    }

    
    param.year_code = this.query.year_code;
    param.enrol_agent_id = this.query.enrol_agent_id;
    param.exam_batch = this.query.exam_batch;

   
   
  }

 
  search2(param) {
    param.query = this.query.query;
    param.year_code = this.item.year_code;
    param.exam_batch = this.item.exam_batch;
   
   
  }

  searchData() {
    if (!this.query.query) {
      this.query.query = "";
    }

    
    if(!this.item.year_code){
      AppComponent.alert({ 'title': '提示', text: '请选择批次！' });
      return false;
    }

    if(!this.item.exam_batch){
      AppComponent.alert({ 'title': '提示', text: '请选择场次！' });
      return false;
    }

     this.coursePager.reload();
   
   
  }

  ngOnInit() {
    
    FrameRequest.requestArray(this.YEAR_CODE_URL,{}, async (array) => {
      this.yearCodeArray = array;
    });

    FrameRequest.requestEntity(this.GET_DEPT_URL, {}, (entity) => {
      this.logOrgType = entity;
      // 考试院账号，则展示 所有考区
      if(this.logOrgType == '0'){
        FrameRequest.requestArray(this.AREA_LIST_URL,{}, async (array) => {
          this.examAgentArray = array;
        });
      }else{
        // 非考试院账号，只展示当前考区
        FrameRequest.requestEntity("cf/cfOrganization/queryExamArea.htm",{}, async (entity) => {
          this.examAgentArray = [entity];
          
        });
      }

    });

    FrameRequest.requestEntity(this.CURR_YEAR_CODE_URL, {}, (entity) => {
      this.query.year_code = entity;
      this.framePager.reload();
    });

  }

  async preSaveEvent(){
    if(!this.item.year_code){
      AppComponent.alert({ 'title': '提示', text: '请选择批次！' });
      return false;
    }

    if(null == this.yesCourses || this.yesCourses.length==0){
      AppComponent.alert({ 'title': '提示', text: '请添加课程！' });
      return false;
    }

    if (this.yesCourses.length>0) {
      let course_id=[];
      this.yesCourses.forEach(y => {
        course_id.push(y.course_id);
      });

      this.item.course_ids=course_id.join();
    }
    
    return true;
  }

  async preGoEditEvent(item){
    
    //  if(!item){
    //    if(!this.query.year_code){
    //      AppComponent.alert({ 'title': '提示', text: '请选择批次！' });
    //      return false;
    //    }

   //     if(!this.query.exam_batch){
    //      AppComponent.alert({ 'title': '提示', text: '请选择场次！' });
    //      return false;
   //     }
   //   }
     
      this.yesCourses = [];
      this.flag = false;
    
	  return true;
  }

  async aftGoEditEvent(){
    
    if(!this.item||!this.item.id){
      this.item.year_code = parseInt(this.query.year_code) ;
      this.item.exam_batch = this.query.exam_batch ;
      
    }
    
   // this.doExamBatch();

    
    if(this.item && this.item.id){
       this.flag = true;

        FrameRequest.requestArray("std/stdEnrolCourseVolume/queryStdEnrolCourseVolumeDetailByVolumeId.htm", { volume_id: this.item.id }, (array) => {
        this.yesCourses = array;
      });
    }
   
  }

  courseChange(event){
    let exam_batch = event.currentTarget.value;
   
    if(exam_batch&&this.yesCourses && this.yesCourses.length>0){
      this.yesCourses = [];
      if(this.coursePager){
        this.coursePager.reload();
      }

     }else if(exam_batch){
      if(this.coursePager){
        this.coursePager.reload();
      }
     }
  }
   
    
  courseChangeForYearCode(year_code){
    if(year_code&&this.yesCourses && this.yesCourses.length>0){
        this.yesCourses = [];
        if(this.coursePager){
          this.coursePager.reload();
        }

     }else if(year_code){
      if(this.coursePager){
        this.coursePager.reload();
      }
     }

    
  }


  deleteCourse(course) {
    
    if (course.course_id) {
      for (var i = 0;i < this.yesCourses.length; i++){
        
        if (this.yesCourses[i].course_id==course.course_id){
          this.yesCourses.splice(i,1);
        }
       }
    }
  
  
    }

    saveCourseRealate(volume_id) {
    
      let checkedArray = this.coursePager.getCheckedArray();

      if(checkedArray.length == 0){
        AppComponent.alert({ 'title': '提示', text: '请选择课程！' });
        return false;
      }
     
      for (var i = 0;i < checkedArray.length; i++){
        let is_exit = false;
        let temp = checkedArray[i];
        for (var j = 0;j < this.yesCourses.length; j++){
          if (this.yesCourses[j].course_id==temp.id){
            is_exit = true;  
           break;
          }
        }

        if(!is_exit){
          let detail = {volume_id:volume_id,course_id:temp.id,course_code:temp.course_code,course_name:temp.course_name};

          this.yesCourses.push(detail);
        }
      }

  
    }



  deleteOne(volume) {
    if(null == volume){
      AppComponent.alert({ 'title': '提示', text: '请选择等待删除的记录！' });
      return;
    }

    AppComponent.confirm("确定删除选中的考位限制记录吗？", () => {
      FrameRequest.request("std/stdEnrolCourseVolume/delete.htm", { ids: volume.id}, () => {
        AppComponent.GobalComponent.successMsg("删除成功");
        this.framePager.reload();
      });
    });
  }


  carouselContentFilter(str) {
    
    if(str){
        var carContent ='';
        if(str.length >= 40){
           
            carContent = str.substring(0,40) + '...';
        }
        else {
            carContent = str
        }
        return carContent;
    }else{
      return str;
    }
}

}