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 { FrameUploaderComponent } from "../../../../core/uploader/uploader.component";

@Component({
  selector: "app-pl-textbook-pre",
  templateUrl: "./pl-textbook-pre.component.html",
  styleUrls: ["./pl-textbook-pre.component.scss"]
})
export class PlTextbookPreComponent extends FlexTableComponent
  implements OnInit {

  public query = {
    "query": "",
    "status": "",
    "exam_time_id":""
  };

  public syn = {
    "old_exam_time_id": null,
    "exam_time_id":null
  };

  courseShowType: boolean = false;
  yesCourses = [];
  noCourses = [];
  yearCodeList = [];
  course: any;
  exam_time_id: any;
  
  @ViewChild('framePager2')
  framePager2: FramePagerComponent;

  //TODO
  QUERY_URL = "pl/plTextbookPre/page.htm";
  DELETE_URL = "pl/plTextbookPre/deleteBatch.htm";
  GET_URL = "pl/plTextbookPre/find.htm";
  ADD_URL = "pl/plTextbookPre/add.htm";
  EDIT_URL = "pl/plTextbookPre/edit.htm";
  COURSE_URL = "pl/plTextbookPre/get.htm";
  ADD_COURSE_URL = "pl/plTextbookPre/addCourse.htm";
  COURSE_PAGE_URL = "pl/plCoursePre/page.htm";
  DELETE_COURSE_URL = "pl/plTextbookPre/deleteCourse.htm";
  UPLOAD_URL = "pl/plTextbookPre/upload.htm";
  DOWNLOAD_URL = "pl/plTextbookPre/download.htm";
  ERROR_DOWNLOAD_URL = "pl/plTextbookPre/downloadError.htm";
  YEAR_CODE_URL = "pl/plExamTime/list.htm";
  UPDATE_BATCH_URL = "pl/plTextbookPre/updateBatch.htm";
  TEXTBOOK_SYNC_URL = "pl/plTextbookPre/synTextBook.htm";

  filePath: any;//错误文件路径
  @ViewChild('uploader')
  uploader: FrameUploaderComponent;

  constructor(
    public bsModalService: BsModalService,
    fb: FormBuilder
  ) {
    super();
    // CustomValidators.rangeLength([1, 6])
    this.formModel = fb.group({
      id: [null],
      'textbook_name': [null, Validators.compose([Validators.required])],
      'textbook_code': [null, Validators.compose([Validators.required, Validators.pattern("^[a-zA-Z0-9]+$")])],
      'textbook_writer': [null],
      'price': [null],
      'textbook_publisher': [null],
      'textbook_revision': [null],
      'textbook_outline': [null],
	  'status': [null]
    });
  }

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

  async delete(item?){
		if(!  this.preDeleteEvent()) return;
		//批量操作
		if(!item){
		  let checkedArray = this.framePager.getCheckedArray();
		  if(checkedArray.length === 0){
			AppComponent.alert({title:"信息提示",text:"请选择数据!"})
			return;
		  }
		}
		AppComponent.confirm("确定要删除教材记录吗？将同步删除课程关联信息,此操作不可恢复！",()=>{
		  let checkedArray = [];
		  item ? checkedArray[0] = item.id: 
				 checkedArray = this.framePager.getCheckedArray((item)=>item.id)
		  
		  // if(checkedArray.length === 0){
		  //   AppComponent.alert({title:"信息提示",text:"请选择数据!"})
		  //   return;
		  // }
		  FrameRequest.requestMap(this.DELETE_URL, {ids:checkedArray.join()}, () => {
			AppComponent.GobalComponent.successMsg('数据删除成功');
			this.aftDeleteEvent();
			this.framePager.reload();
		  });
	});
    


  }

  async preGoEditEvent(item){
	  this.yesCourses = [];
	  if (item) {
		this.reload(item.id);
	  }
	  return true;
  }
  async preSaveEvent(){
	if (this.yesCourses.length>0) {
		let course_id=[];
		let exam_time_id=[];
		this.yesCourses.forEach(y => {
			course_id.push(y.id);
			exam_time_id.push(y.exam_time_id);
		});
		this.item.course_ids=course_id.join();
		this.item.course_exam_times=exam_time_id.join();
	}
	return true;
  }

  // 教材关联课程
  courseRelate(template: TemplateRef<any>, modalcss: string, item?) {
    if (!item) {
      let checkArray = this.framePager.getCheckedArray();
      if (checkArray.length === 0 || checkArray.length > 1) {
        AppComponent.alert({ title: '信息提示', text: '请选择一条数据！' });
        return;
      }
      item = checkArray[0];
      this.item = item;
    }
    FrameRequest.requestArray(this.COURSE_URL, { id: item.id }, (array) => {
      this.yesCourses = array;
    });
    //以模态窗口显示
    this.shouModalWin(template, modalcss);
  }

  hideCouseWindow() {
    this.courseShowType = null;
    this.yesCourses = [];
    if (this.bsModalWin) this.bsModalWin.hide();
    this.query.query = "";
    this.framePager.reload();
    this.resetPage();
  }
  //保存课程关联信息
  saveCourseRealate(textbook_id: number, item?) {
    
    let checkedArray = this.framePager2.getCheckedArray();
    if (!this.course) {
      if (checkedArray.length === 0 || checkedArray.length > 1) {
        AppComponent.alert({ title: "信息提示", text: "请选择一条数据!" })
        return;
      }
    }

    if(!this.exam_time_id) {
      AppComponent.alert({ 'title': '提示', 'text': '请选择启用批次' });
      return;
    } 
   
   
	if (textbook_id) {
		item ? checkedArray[0] = item.id :
		checkedArray = this.framePager2.getCheckedArray((item) => item.id);
		FrameRequest.request(this.ADD_COURSE_URL, { course_id: checkedArray[0], textbook_id: textbook_id, exam_time_id: this.exam_time_id}, () => {
			AppComponent.GobalComponent.successMsg('课程关联成功');
			this.reload(textbook_id);
			
		  });
	}else{
		for (var i = 0;i < this.yesCourses.length; i++){
      
			if (this.yesCourses[i].id==checkedArray[0].id){
				this.yesCourses.splice(i,1);
			}
		 }
		 for (var i = 0;i < this.yearCodeList.length; i++){
			if (this.yearCodeList[i].id==this.exam_time_id){
				checkedArray[0]['exam_time_id']=this.yearCodeList[i].id;
        checkedArray[0]['year_code']=this.yearCodeList[i].year_code;
        checkedArray[0]['exam_year_month']=this.yearCodeList[i].examyearmonth;
			}
		 }
		this.yesCourses.push(checkedArray[0]);
	}
	this.exam_time_id=null;

  }

  //删除关联课程
  deleteCourse(course) {
	if (!course.textbook_id) {
		for (var i = 0;i < this.yesCourses.length; i++){
			if (this.yesCourses[i].id==course.id){
				this.yesCourses.splice(i,1);
			}
		 }
	} else {
		FrameRequest.request(this.DELETE_COURSE_URL, { id: course.id }, () => {
			AppComponent.alert({ title: "信息提示", text: "删除成功!" });
			this.reload(course.textbook_id);
		  })
	}


  }
  //重新加载
  reload(textbook_id) {
    FrameRequest.requestArray(this.COURSE_URL, { id: textbook_id }, (array) => {
      this.yesCourses = array;
    });
  }

  //模板下载
  download() {
    FrameRequest.download(this.DOWNLOAD_URL);
  }

  //错误数据下载
  downloadErrFile() {
    FrameRequest.download(this.ERROR_DOWNLOAD_URL, { filePath: this.filePath });
  }

  /**
 * 批量导入
 */
upload(item?: any) {
  this.uploader.choooseFileAndUpload({}, ((ajax) => {
    if (ajax.errorCode === -1) {
      this.filePath = ajax.url;
      AppComponent.alert({ 'title': '提示', 'text': '有错误数据，请修正后，在重新上传' });
    } else {
      AppComponent.GobalComponent.successMsg('批量导入成功');
      this.filePath = '';
      this.hideModal();
      this.framePager.reload();
    }
  }).bind(this));
}

updateBatch(exam_time_id:any,id:any) {
  if(!exam_time_id) {
    AppComponent.alert({ 'title': '提示', 'text': '请选择启用批次' });
  }
  FrameRequest.request(this.UPDATE_BATCH_URL, {
    exam_time_id: exam_time_id,
    id: id
  },() => {
    AppComponent.GobalComponent.successMsg('启用批次设置成功');
  });
}

setyearcode(exam_time_id:any,id:any) {
  if(exam_time_id) {
    this.exam_time_id = exam_time_id;
  }

 
}

      //教材同步
      textbookSync() {
     
      if(!this.syn.old_exam_time_id) {
        AppComponent.alert({ 'title': '提示', text: '请选择教材来源批次' });
        return;
      }

      if(!this.syn.exam_time_id) {
        AppComponent.alert({ 'title': '提示', text: '请选择待同步批次' });
        return;
      }
  
      AppComponent.confirm("确定同步教材同步吗?",()=>{
  
        AppComponent.GobalComponent.setLoading(true);
        FrameRequest.request(this.TEXTBOOK_SYNC_URL, { exam_time_id: this.syn.exam_time_id,old_exam_time_id: this.syn.old_exam_time_id }, () => {
          AppComponent.GobalComponent.setLoading(false);
          AppComponent.GobalComponent.successMsg("同步成功");
          this.hideImpWin();
          this.framePager.reload();
        });
  
      });
  
      
    }    
    
   

    
  hideImpWin() {
    if(this.bsModalWin) 
      this.bsModalWin.hide();
   
  }
    

}