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

  public query = {
    "query": "",
    "apply_status": "",
    "school_id":"",
    "join_school_id":"",
    "year_code":"",
    "query_school_id":"",
    "query_join_school_id":""
  };

  

  apply_form = 2; //网络助学考生
  joinSchoolList = [];

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

  courseShowType: boolean = false;
  yesStds = [];
  oldStds = [];
  majorList = [];

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

  SCHOOL_URL = "cf/cfOrganization/listOrganizationForCancelPlStdRecord.htm?org_type=1&status=1";
  JION_SCHOOL_URL = "cf/cfOrganization/queryOrgForStdRecordBySchoolId.htm?org_type=3"; //助学点
  QUERY_URL = "pl/plStdRecordApply/page.htm";
  GET_URL = "pl/plStdRecordApply/find.htm";
  DELETE_URL = "pl/plStdRecordApply/delete.htm";
  STD_RECORD_PAGE_URL = "pl/plStdRecord/page.htm?std_type="+this.apply_form;
  ADD_URL = "pl/plStdRecordApply/add.htm";
  EDIT_URL = "pl/plStdRecordApply/edit.htm";
  YEAR_CODE_URL = "pl/plExamTime/list.htm";
  UPLOAD_URL = "pl/plStdRecordApply/upload.htm";
  DOWNLOAD_URL = "pl/plStdRecordApply/download.htm";


  COURSE_URL = "pl/plTextbook/get.htm";
  ADD_COURSE_URL = "pl/plTextbook/addCourse.htm";
  
  DELETE_COURSE_URL = "pl/plTextbook/deleteCourse.htm";
  ERROR_DOWNLOAD_URL = "pl/plTextbook/downloadError.htm";
 
  UPDATE_BATCH_URL = "pl/plTextbook/updateBatch.htm";
  TEXTBOOK_SYNC_URL = "pl/plTextbook/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],
      'apply_topic': [null],
      'apply_remark': [null],
      'file_path': [null]
    });
  }

  ngOnInit() {
    FrameRequest.requestArray(this.JION_SCHOOL_URL, {
      year_code: '' ,
      school_id:'' 
    }, (array) => {
      this.joinSchoolList = array;
    });

    FrameRequest.requestArray("pl/plMajor/queryMajor.htm", {}, (array) => {
      this.majorList = array;
    });


  }

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

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

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

    param.query = this.query.query;
    param.apply_status = this.query.apply_status;
    param.school_id = this.query.query_school_id;
    param.join_school_id = this.query.query_join_school_id;
    param.std_type = this.apply_form;
    
  }

  search2(param) {
    if(!this.query.year_code){
      this.query.year_code = "";
    }
    
    param.query = this.query.query;
    param.year_code = this.query.year_code;
    param.school_id = this.query.school_id;
    param.status = 3;
    
  }

  deleteApply(item){
    if (item.apply_status != '待提交') {
      AppComponent.alert({title:"信息提示",text:"只能删除待提交状态的申请单!"});
      return;
    }

    AppComponent.confirm("确定删除吗?",()=>{
      FrameRequest.requestMap(this.DELETE_URL, {id:item.id}, () => {
        AppComponent.GobalComponent.successMsg('删除成功!');
         this.framePager.reload();
      });
  });

    
  }

  async preGoEditEvent(item){
 
    this.yesStds = [];
    this.oldStds = [];
    
	  if (item) {
		 this.reload(item.id);
	  }else{
      this.item = {};
    }

    
	  return true;
  }
  async preSaveEvent(){
   
    if(!this.item.apply_topic){
      this.item.apply_status=null;
      AppComponent.alert({ title: '信息提示', text: '请填写申请主题！' });
      return false;
    }

    if(!this.item.apply_remark){
      this.item.apply_status=null;
      AppComponent.alert({ title: '信息提示', text: '请填写申请说明！' });
      return false;
    }

    if(this.item.apply_status=='待考试院审核' && !this.item.file_path){
      this.item.apply_status=null;
      AppComponent.alert({ title: '信息提示', text: '请上传证明材料！' });
      return false;
    }

    if (this.yesStds.length>0) {
      let ids=[];
      let join_major_codes=[];
      let school_ids=[];
      let join_school_ids=[];
      this.yesStds.forEach(y => {
        ids.push(y.id);
        join_major_codes.push(y.join_major_code);
        school_ids.push(y.school_id);
        join_school_ids.push(y.join_school_id);
      });
      this.item.ids=ids.join();
      this.item.join_major_codes=join_major_codes.join();
      this.item.school_ids=school_ids.join();
      this.item.join_school_ids=join_school_ids.join();

      
    }else{
      this.item.apply_status=null;
      AppComponent.alert({ title: '信息提示', text: '请添加转专业考生！' });
        return false;
    }

    this.item.std_type=this.apply_form;

    return true;
  }

  callback() {

    let checkedArray = this.framePager.getCheckedArray();

      if (checkedArray.length === 0 || checkedArray.length > 1) {
        AppComponent.alert({ title: "信息提示", text: "请选择一条数据!" })
        return;
      }

      if (checkedArray[0].apply_status != '待考试院审核') {
        AppComponent.alert({ title: "信息提示", text: "只能撤回待考试院审核的申请单!" })
        return;
      }

      AppComponent.confirm("确定撤回申请单吗?",()=>{
        FrameRequest.requestMap("pl/plStdRecordApply/callback.htm", {apply_id:checkedArray[0].id,apply_status:'待提交'}, () => {
          AppComponent.GobalComponent.successMsg('撤回成功!');
          this.framePager.reload();
        });
      });

  }

  addOneStd(event,std){
    
    // 选中
    if(event.target.checked){
      for (var i = 0;i < this.yesStds.length; i++){
        if (this.yesStds[i].id==std.id){
          AppComponent.GobalComponent.errorMsg('该考生已添加，不允许重复添加!');
          return;
        }
      }
      
       // 创建时新增考生
       if (!this.item.id) {
        this.yesStds.push(std);
        this.oldStds.push(std);
        AppComponent.GobalComponent.successMsg('添加成功，请在申请转专业的备案考生栏，选择考生要转的专业!');
      } else {
        // 更新时新增考生
        FrameRequest.requestMap("pl/plStdRecordApply/addStd.htm", {id:std.id,apply_id:this.item.id}, () => {
          AppComponent.GobalComponent.successMsg('添加成功，请在申请转专业的备案考生栏，选择考生要转的专业!');
          this.reload(this.item.id);
        });
      }
    }else{
      // 取消选中
      this.deleteStd(std);
    }
  }

  addStd() {

    let checkedArray = this.framePager2.getCheckedArray();

      if (checkedArray.length === 0 || checkedArray.length > 1) {
        AppComponent.alert({ title: "信息提示", text: "请选择一条数据!" })
        return;
      }

      for (var i = 0;i < this.yesStds.length; i++){
        if (this.yesStds[i].id==checkedArray[0].id){
          AppComponent.alert({ title: "信息提示", text: "该考生已经添加，不允许重复添加!" })
          return;
        }
      }

      // 创建时新增考生
      if (!this.item.id) {
        this.yesStds.push(checkedArray[0]);
        this.oldStds.push(checkedArray[0]);
        AppComponent.GobalComponent.successMsg('添加成功，请在申请转专业的备案考生栏，选择考生要转的专业!');
      } else {
        // 更新时新增考生
        FrameRequest.requestMap("pl/plStdRecordApply/addpl/plStdRecordApply/addStd.htm", {id:checkedArray[0].id,apply_id:this.item.id}, () => {
          AppComponent.GobalComponent.successMsg('添加成功，请在申请转专业的备案考生栏，选择考生要转的专业!');
          this.reload(this.item.id);
        });
      }

  }

 
  deleteStd(std) {
    AppComponent.confirm("确定删除待转专业的考生吗?",()=>{
      // 创建时删除考生
        if (!this.item.id) {
          for (var i = 0;i < this.yesStds.length; i++){
            if (this.yesStds[i].id==std.id){
              this.yesStds.splice(i,1);
            }
          }

          for (var i = 0;i < this.oldStds.length; i++){
            if (this.oldStds[i].id==std.id){
              this.oldStds.splice(i,1);
            }
          }

        } else {
          // 更新时删除考生
          FrameRequest.requestMap("pl/plStdRecordApply/deleteStd.htm", {id:std.id,apply_id:std.apply_id}, () => {
            AppComponent.GobalComponent.successMsg('删除成功!');
            this.reload(std.apply_id);
          });
        }
    });

  }

  //重新加载
  reload(id) {
    
    FrameRequest.requestArray("pl/plStdRecordApply/queryStdByApplyId.htm", { id: id }, (array) => {
      this.yesStds = array;
    });

    FrameRequest.requestArray("pl/plStdRecordApply/queryOldStdByApplyId.htm", { id: id }, (array) => {
      this.oldStds = array;
    });
    
  }

  //上传申报资料
  uploadFile() {
    let obj = this.item;
    if(!obj.id){
      obj.id = '';
    }
    
      //上传文书
      let param = {id:obj.id};
      this.uploader.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);
        }
      }));
  }

   //下载申报资料
   downloadApplyFile(applyId) {
    FrameRequest.download(this.DOWNLOAD_URL,  { id: applyId });
  }
    

}