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",
  templateUrl: "./pl-textbook.component.html",
  styleUrls: ["./pl-textbook.component.scss"]
})
export class PlTextbookComponent extends FlexTableComponent
  implements OnInit {

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

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

  courseShowType: boolean = false;
  yesCourses = [];
  noCourses = [];
  yearCodeList = [];
  course: any;
  exam_time_id: any;

  courseList = [];
  
  @ViewChild('framePager2')
  framePager2: FramePagerComponent;

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

  COURSE_LIST_URL = "pl/plCourse/listCourseByExamTimeId.htm";

  filePath: any;//错误文件路径
  @ViewChild('uploader')
  uploader: FrameUploaderComponent;
  @ViewChild('uploaderFile')
  uploaderFile: 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],
      'exam_time_id': [null, Validators.required],
      'course_id': [null, Validators.required],
      'file_path': [null],
      'status': [null]
    });
  }

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

    FrameRequest.requestArray("pl/plCourse/listAll.htm",{}, async (array) => {
      this.courseList = 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)
		  
		  FrameRequest.requestMap(this.DELETE_URL, {ids:checkedArray.join()}, () => {
			AppComponent.GobalComponent.successMsg('数据删除成功');
			this.aftDeleteEvent();
			this.framePager.reload();
		  });
	});
    


  }

  async preGoEditEvent(item){
 
    if (!item) {
        this.item = {};
        this.item.status='0';
        this.item.course_id="";

        if(this.query.exam_time_id){
          this.item.exam_time_id = this.query.exam_time_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(item) {
    
    if(this.yesCourses && this.yesCourses.length>0) {
      AppComponent.alert({ 'title': '提示', 'text': '只允许关联一门课程' });
      return;
    } 
    this.item.course_id = item.id;
		this.yesCourses.push(item);
  }

  //删除关联课程
  deleteCourse(course) {
    this.item.course_id = "";
    for (var i = 0;i < this.yesCourses.length; i++){
			if (this.yesCourses[i].id==course.id){
				this.yesCourses.splice(i,1);
			}
     }

  }
  //重新加载
  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();
   
  }

  downloadFile(id) {
    FrameRequest.download("pl/plTextbook/downloadFile.htm",  { id: id });
  }



  uploadFile() {
    let obj = this.item;
    
    if(!this.item || !this.item.exam_time_id){
      AppComponent.alert({ 'title': '提示', text: '请选择考试批次' });
      return;
    }

      //上传文书
      let param = {exam_time_id: this.item.exam_time_id};
      this.uploaderFile.choooseFileAndUpload(param, ((ret) => {
        if (ret.errorCode == 0) {
          obj.file_path = ret.map.file_path;
          obj.file_name = ret.map.file_name;
          AppComponent.GobalComponent.successMsg("上传成功!");
        }else if (ret.errorCode == -1) {
         
          AppComponent.GobalComponent.errorMsg(ret.errorMsg);
        }
      }));
  }

  downXls() {
      if(!this.query.status){
        this.query.status = "";
      }
      if(!this.query.exam_time_id){
        this.query.exam_time_id = "";
      }
     
      if(!this.query.is_unified){
        this.query.is_unified = "";
      }

      let param = {
        query: this.query.query,
        status: this.query.status,
        exam_time_id : this.query.exam_time_id,
        is_unified:this.query.is_unified
    };
    AppComponent.GobalComponent.setLoading(true);
    FrameRequest.download("pl/plTextbook/downxls.htm", param, ()=>{
        AppComponent.GobalComponent.setLoading(false);
        AppComponent.GobalComponent.successMsg("导出成功!");
    });
  }

  
  downXlsForUnified() {
   
    if(!this.query.exam_time_id){
      AppComponent.alert({ 'title': '提示', text: '请选择考试批次' });
      return;
    }

   

    let param = {
      exam_time_id : this.query.exam_time_id,
  };
  AppComponent.GobalComponent.setLoading(true);
  FrameRequest.download("pl/plTextbook/downXlsForUnified.htm", param, ()=>{
      AppComponent.GobalComponent.setLoading(false);
      AppComponent.GobalComponent.successMsg("导出成功!");
  });
}
    

}