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-kw-examunit",
  templateUrl: "./special-examunitcourse.component.html",
  styleUrls: ["./special-examunitcourse.component.scss"]
})
export class SpecialExamUnitCourseComponent extends FlexTableComponent
  implements OnInit {

  public query = {
    query: "",
    priority: "",
    exPointId: "",
    exam_time_id: "",
    aloneFlag: ""
  };

  public impQuery = {
    exam_time_id: "",
	exam_point_id: "",
	aloneFlag: ""
  }
  @ViewChild('uploader')
  uploader: FrameUploaderComponent;
  filePath : String;
  //TODO
  QUERY_URL = "kw/kwSpecialExamUnit/page.htm";
  DELETE_URL = "kw/kwSpecialExamUnit/deleteSpecialExamUniAndCourse.htm";
  GET_URL = "kw/kwSpecialExamUnit/get.htm";
  ADD_URL = "kw/kwSpecialExamUnit/addSpecialExamUniAndCourse.htm";
  EDIT_URL = "kw/kwSpecialExamUnit/editSpecialExamUniAndCourse.htm";
  TIME_URL = "pl/plExamTime/listtime.htm";

  UPLOAD_URL = "pl/kwSpecialExamUnit/examUnitCourseUpload.htm";

  CURR_YEAR_CODE_URL = "pl/plExamTime/getCurrentYearCode.htm";
  TASK_YEAR_CODE_URL = "pl/kwSpecialExamUnit/listYearcode.htm";
  YEAR_CODE_URL = "pl/plExamTime/list.htm";
  SPECIAL_COURSE_URL = "kw/kwSpecialCourseRoom/querySpecialCourse.htm";
  
  examPointList = [];
  unitList = [];

  modalWin: any;
  yearCode: any;
  historyYearcode: any;
  courseList: any;
  

  constructor(
    public bsModalService: BsModalService,
	fb: FormBuilder,
	private activeInfo:ActivatedRoute
  ) {
    super();
    // CustomValidators.rangeLength([1, 6])
    this.formModel = fb.group({
      id: [null],
      'unit_name': [null, Validators.compose([Validators.required])],
     
      'short_name': [null],
      'unit_code': [null, Validators.compose([Validators.required,Validators.pattern(FrameValidator.pattern_en_number)])],
      'priority': [null, Validators.compose([Validators.required])],
      'adress': [null],
      'room_num': [null, Validators.compose([Validators.required])],
      'room_capacity': [null],
      'remark': [null],
      'exam_point_id': [null, Validators.compose([Validators.required])],
      'alone_flag': [null],
      'course_id': [null, Validators.compose([Validators.required])]
    });
  }

  search(param) {
    if (!this.query.exam_time_id) {
      this.query.exam_time_id = "";
    }
    if (!this.query.exPointId) {
      this.query.exPointId = "";
    }
    if (!this.query.priority) {
      this.query.priority = "";
    }
    if (!this.query.aloneFlag) {
      this.query.aloneFlag = "";
    }
    param.query = this.query.query;
    param.exam_time_id = this.query.exam_time_id;
    param.exam_point_id=this.query.exPointId;
    param.priotity=this.query.priority;
    param.aloneFlag = this.query.aloneFlag;
  }

  ngOnInit() {
    this.query.aloneFlag="1";
	//this.query.aloneFlag=this.activeInfo.snapshot.params['aloneFlag'];
	//this.activeInfo.params.subscribe((data:any)=>{
	//	this.query.aloneFlag=data.aloneFlag;
	//	this.framePager.reload();});

    var parm = {exam_time_id: ""};
    FrameRequest.requestArray("kw/kwExamPoint/listpoint.htm", parm, (arrary) => {
	  this.examPointList = arrary;
    });
    FrameRequest.requestMap("kw/kwExamPoint/initdata.htm", {}, (map)=>{
      if (map["exam_time_id"]) {
          this.query.exam_time_id = map["exam_time_id"];
		  this.framePager.reload();
      }
  });
  
  FrameRequest.requestArray("kw/kwExamPoint/queryBzUnit.htm", {}, (arrary)=>{
    
    this.unitList = arrary;
  });

  FrameRequest.requestArray(this.SPECIAL_COURSE_URL, {}, (array) => {
    this.courseList = array;
  });
	
  }

  selectUnit(unit_code_bz) {
    
    if(null == unit_code_bz){
      return;
    }

    for (let i=0;i<this.unitList.length;i++) {
      if (this.unitList[i].unit_code_bz == unit_code_bz) {
        this.item.unit_name_bz=this.unitList[i].unit_name_bz;
        this.item.adress=this.unitList[i].adress;
        this.item.short_name=this.unitList[i].unit_name_bz;
        this.item.unit_name=this.unitList[i].unit_name_bz;
        break;
      }
    }
  }

  hideCouseWindow() {
    if (this.bsModalWin) this.bsModalWin.hide();
    this.query.query = "";
    this.resetPage();
  }

  //导入
  importFunc() {
    if (!this.impQuery.exam_time_id) {
      AppComponent.alert({title: "信息提示", text: "请选择时间批次!"});
      return;
    }
    if (!this.impQuery.exam_point_id) {
      AppComponent.alert({title: "信息提示", text: "请选择时间批次!"});
      return;
    }
    let param = {
      exam_time_id: this.impQuery.exam_time_id,
	  exam_point_id: this.impQuery.exam_point_id,
	  aloneFlag: this.impQuery.aloneFlag,
      title_rows: 1
    };
    this.uploader.choooseFileAndUpload(param, ((ret) => {
      if (ret.errorCode > 0) {
        AppComponent.alert({title:"信息提示", text: ret.errorMsg});
      }
      else if (ret.errorCode == -1) {
        this.filePath = ret.url;
        this.hideModal();
        this.editShowType = "showMainList";
        AppComponent.alert({ 'title': '提示', 'text': '有错误数据，请修正后，再上传' });
      } else if (ret.errorCode == 0) {
        this.hideModal();
        this.framePager.reload();
        this.editShowType = "showMainList";
        AppComponent.alert({title:"信息提示", text:"上报成功!"});
      }
    }));
  }

  downTemplate() {
    FrameRequest.download("pl/kwSpecialExamUnit/template/download.htm",{templateName:"special_exam_unit_course_upload.xlsx"});
  }

  //错误数据下载
  downloadErrFile() {
    FrameRequest.download("pl/kwSpecialExamUnit/error/download.htm",  { filePath: this.filePath });
  }

  examTimeChange(exam_time_id_arg) {
    if (!exam_time_id_arg) {
      exam_time_id_arg = "";
    }
    this.examPointList=[];
    let param = {
      start: 0,
      limit: 100,
      exam_time_id: exam_time_id_arg,
      RequestLoading: true
    }
    FrameRequest.requestPage("kw/kwExamPoint/page.htm", param, (page)=>{
        this.examPointList = page.records;
        //默认选中第一个考点
        if (this.examPointList.length > 0) {
			this.query.exPointId = this.examPointList[0].id;
            this.framePager.reload();
        }
    });
  }

  async preSaveEvent() {
   
    if (!this.item.unit_code_bz) {
      AppComponent.alert({title:"信息提示", text:"请选择标准考点!"});
      return false;
    }
   
    return true;
  }

  async preGoEditEvent(entity?) {
    if(!this.examPointList || this.examPointList.length == 0){
      AppComponent.alert({title:"信息提示", text:"考务编排时间未设置，不允许配置考点!"});
      return;
    }

    return true;
  }


  async aftGoEditEvent() {
    if(!this.item || this.item.id === undefined) {
    this.item = {};
    this.item.exam_point_id=this.examPointList[0].id;
	  
      this.item.room_capacity = 30;
      this.item.priority = 1;
      this.item.alone_flag = this.query.aloneFlag;
    }
  }
  async preShowModalWin(){
	this.impQuery.aloneFlag=this.query.aloneFlag;
    return true
  }

  //选择考点后获取当前考点编码
  freshUnitCode(exPointId) {
	if(!exPointId){return}
	if(this.item.unit_code){return}
    FrameRequest.requestMap("kw/kwSpecialExamUnit/getcode.htm", {exam_point_id: exPointId}, (map)=>{
      if (map["code"]) {
        this.item.unit_code = map["code"];
      }
    });
  }

   //同步
   sync() {
    if (!this.yearCode) {
      AppComponent.alert({ 'title': '提示', 'text': '请选择本批次' });
      return;
    }
    if (!this.historyYearcode) {
      AppComponent.alert({ 'title': '提示', 'text': '请选择历史批次' });
      return;
    }
    AppComponent.GobalComponent.setLoading(true);
    FrameRequest.request("pl/kwSpecialExamUnit/syncExamUnitAndCourse.htm", { yearCode: this.yearCode, historyYearcode: this.historyYearcode,aloneFlag:this.query.aloneFlag }, (ajax) => {
      AppComponent.GobalComponent.setLoading(false);
      if (ajax.errorCode === -1) {
        AppComponent.alert({ 'title': '提示', 'text': ajax.errorMsg });
      } else {
        AppComponent.GobalComponent.successMsg("特殊考场和课程配置同步成功");
        this.hideModalWin();
        this.yearCode = "";
        this.historyYearcode = "";
        this.framePager.reload();
      }
    });
  }

  syncTask(template: TemplateRef<any>, modalcss?) {
    FrameRequest.requestEntity(this.CURR_YEAR_CODE_URL, {}, (entity) => {
      this.yearCode = entity;
    });

    let css = modalcss ? modalcss : "modal-lg";
    this.modalWin = this.bsModalService.show(template, { class: css });
  }

  hideModalWin() {
    if (this.modalWin) {
      this.modalWin.hide();
    }
  }
}