import { Component, OnInit, ViewChild } from '@angular/core';
import { FlexTableComponent } from '../../../../../shared/common/FlexTable.component';
import { FrameUploaderComponent } from '../../../../../core/uploader/uploader.component';
import { BsModalService } from 'ngx-bootstrap/modal';
import { FormBuilder, Validators } from '@angular/forms';
import { FrameRequest } from '../../../../../shared/frame/frame-request';
import { AppComponent } from '../../../../..';
import { FramePagerComponent } from '../../../../../core/pager/pager.component';

@Component({
  selector: 'app-pl-junior-std-record',
  templateUrl: './pl-junior-std-record.component.html',
  styleUrls: ['./pl-junior-std-record.component.scss']
})
export class PlJuniorStdRecordComponent extends FlexTableComponent implements OnInit {

  public query = {
    "query": "",
    "year_code": "",
    "mk_id": "",
    "status": "",
    "join_school_id" : "",
    "is_xj":"",
    "major_code":""
  };

  QUERY_URL = "pl/plStdRecord/page.htm";
  DELETE_URL = "pl/plStdRecord/delete.htm";
  GET_URL = "pl/plStdRecord/get.htm";
  ADD_URL = "pl/plStdRecord/add.htm";
  EDIT_URL = "pl/plStdRecord/edit.htm";
  UPLOAD_URL = "pl/plStdRecord/upload.htm";
  DOWNLOAD_URL = "pl/plStdRecord/download.htm";
  ERROR_DOWNLOAD_URL = "pl/plStdRecord/downloadError.htm";
  YEAR_CODE_URL = "pl/plExamTime/list.htm";
  MAJOR_LIST_URL = "pl/plMajorRecord/list.htm";
  SUBMIT_URL = "pl/plStdRecord/submit.htm";
  IN_TIME_URL = "pl/plStdRecordTime/inTime.htm";
  UPLOAD_FILE_URL = "pl/plStdRecordFile/upload.htm";
  UPLOAD_DOWNLOAD_URL = "pl/plStdRecordFile/download.htm";
  FIND_URL = "pl/plStdRecordFile/find.htm";
  LASTEST_YEAR_CODE_URL = "pl/plStdRecordTime/getBatch.htm";
  FIND_STD_URL = "/std/stdRegInfo/findStd.htm";
  JOIN_SCHOOL_URL = "pl/plStdRecordSchool/list.htm";
  AUDIT_URL = "pl/plStdRecord/refuse.htm";
  SCHOOL_LIST_URL = "pl/plMajorApplyJoinSchool/list.htm"; //查找主考学校下所有的衔接学校

  majorList = []; //主考学校申报的专业
  filePath: any;//错误文件路径
  apply_form = 1; //专本衔接考生
  status = 2; //待区考试院审核
  inTime: boolean = false;
  joinSchoolShowType = null;
  joinSchool = []; //衔接学校

  @ViewChild('mainPager')
  mainPager:FramePagerComponent;
  
  @ViewChild('uploader')
  uploader: FrameUploaderComponent;
  @ViewChild('uploaderFile')
  uploaderFile: FrameUploaderComponent;
  @ViewChild('joinSchoolFramePager')
  public joinSchoolFramePager: FramePagerComponent;


  constructor(public bsModalService: BsModalService, fb: FormBuilder) {
    super();
    this.formModel = fb.group({
      id: [null],
      'ticket_no': [null, Validators.required],
      'std_name': [null, Validators.required],
      'cert_no': [null, Validators.required],
      'major_record_id': [null, Validators.required],
      'std_no': [null, null],
      'std_num': [null, null],
      'junior_grade': [null, null],
      'junior_major': [null, null],
      'join_school_id' : [null, null]
    });
  }

  ngOnInit() {
    this.query.is_xj="";
    this.chooseMajor();
    setTimeout(
      ()=>{
        FrameRequest.requestEntity(this.LASTEST_YEAR_CODE_URL, {std_type: this.apply_form}, (entity) => {
          if (entity) {
            this.query.year_code = entity.year_code;
            this.framePager.reload();
          }
        });
      }
      ,300
    )
    
  }


  chooseMajor() {
    if(this.query.year_code == null ) {
      this.query.year_code = "";
    }
   // FrameRequest.requestArray(this.MAJOR_LIST_URL, { year_code: this.query.year_code, apply_form: this.apply_form }, (array) => {
   //   this.majorList = array;
   // });

    FrameRequest.requestArray("pl/plMajor/queryMajorByStatus.htm", {status:1,major_level:1}, (arrary) => {
      this.majorList = arrary;
    });

    // FrameRequest.requestEntity(this.IN_TIME_URL, {
    //   year_code: this.query.year_code,
    //   apply_form: this.apply_form
    // }, (entity) => {
    //   this.inTime = entity;
    //   if(!this.inTime) {
    //     AppComponent.alert({title: '提示', text: this.query.year_code +"批次未设置提交时间，请联系考试院设置提交时间"});
    //   }
    // });
  }

  //根据准考证查询考生信息
  findStdInfo(ticket_no: any) {
    FrameRequest.requestEntity(this.FIND_STD_URL, { ticket_no: ticket_no }, (entity) => {
      if (entity) {
        if (!this.item) {
          this.item = {};
        }
        this.item.std_name = entity.std_name;
        this.item.cert_no = entity.cert_no;
      } else {
        AppComponent.alert({ title: "信息提示", text: "准考证填写有误!" });
        return;
      }
    });
  }

  search(param) {
    param.query = this.query.query;
    param.status = this.query.status;
    if (!this.query.mk_id) {
      this.query.mk_id = "";
    }
    param.mk_id = this.query.mk_id;
    if (!this.query.year_code) {
      this.query.year_code = "";
    }
    param.year_code = this.query.year_code;
    if(!this.query.join_school_id) {
      this.query.join_school_id = "";
    }
    param.join_school_id = this.query.join_school_id;

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

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

  }


  async preGoEditEvent(entity?) {
    if (!this.checkBatch()) return;
    return true;
  }

  //提交审核
  async audit() {
    if (!this.query.year_code) {
      AppComponent.alert({ title: "信息提示", text: "请选择批次!" });
      return false;
    }

    let checkedArray = this.mainPager.getRecords();
    if (checkedArray.length > 0) {
        AppComponent.alert({ title: "信息提示", text: "存在未通过学籍电子认证的考生，请通知考生完成学籍电子认证或删除这些考生再提交？" });
        return false;

    }else{
      this.doAudit();
    }

   this.doAudit();

  }

  async doAudit() {

    FrameRequest.requestEntity(this.IN_TIME_URL, {
      year_code: this.query.year_code,
      apply_form: this.apply_form
    }, (entity) => {
      this.inTime = entity;
      if (!this.inTime) {
        AppComponent.alert({ title: '提示', text: this.query.year_code + "批次不在上报规定时间范围内，无法提交" });
      } else {
        let checkedArray = this.framePager.getCheckedArray();
        if (checkedArray.length === 0) {
          AppComponent.confirm("确定提交审核" + this.query.year_code + "批次的所有考生吗？", () => {
            FrameRequest.request(this.SUBMIT_URL, { year_code: this.query.year_code, status: this.status }, () => {
              AppComponent.GobalComponent.successMsg("提交成功");
              this.query.is_xj="";
              this.hideModal();
              this.framePager.reload();
            });
          });
        } else {
          AppComponent.confirm("确定提交审核选中考生吗？", () => {
            let checkIds = this.framePager.getCheckedArray((item) => item.id);
            FrameRequest.request(this.SUBMIT_URL, { year_code: this.query.year_code, ids: checkIds.join(","), status: this.status }, () => {
              AppComponent.GobalComponent.successMsg("提交成功");
              this.query.is_xj="";
              this.hideModal();
              this.framePager.reload();
            });
          });
        }
      }
    });

  }

  checkBatch() {
    if (!this.query.year_code) {
      AppComponent.alert({ title: "信息提示", text: "请选择批次!" });
      return false;
    }
    return true;
  }


  /**
  * 批量导入
  */
  upload(item?: any) {
    if (!this.checkBatch()) {
      return;
    }
    this.uploader.choooseFileAndUpload({ year_code: this.query.year_code }, ((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));
  }


  //模板下载
  download() {
    FrameRequest.download(this.DOWNLOAD_URL, { fileName: 'junior_std_record.xlsx' });
  }

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

  async preSaveEvent() {
    if (!this.item) {
      this.item = {};
    }
    if (!this.item.year_code) {
      this.item.year_code = this.query.year_code;
    }
    if (!this.item.apply_form) {
      this.item.apply_form = this.apply_form;
    }
    return true;
  }

  async preDeleteEvent() {
    let checkedArray = this.framePager.getCheckedArray((item) => item.status);
    for (let i = 0; i < checkedArray.length; i++) {
      if (checkedArray[i] === 2 || checkedArray[i].status === 3) {
        AppComponent.alert({ 'title': '提示', text: '待考试院审核和审批通过的记录不能删除！' });
        return false;
      }
    }
    return true
  }

  deleteAll() {
    if (!this.query.year_code) {
      AppComponent.alert({ 'title': '提示', text: '请选择批次！' });
      return;
    }
    AppComponent.confirm("确定删除批次下等待审核的记录吗？", () => {
      let checkIds = this.framePager.getCheckedArray((item) => item.id);
      FrameRequest.request("pl/plStdRecord/deleteAll.htm", { year_code: this.query.year_code, std_type: this.apply_form }, () => {
        AppComponent.GobalComponent.successMsg("删除成功");
        this.framePager.reload();
      });
    });
  }
  


  goUploadFile(editFormTemplateModal, modalcss?) {
    if (!this.query.year_code) {
      AppComponent.alert({ 'title': '提示', text: '请选择批次！' });
      return;
    }
    let css = modalcss ? modalcss : "modal-lg";
    this.bsModalWin = this.bsModalService.show(editFormTemplateModal, { class: css });
  }

  //上传考生备案相关文件
  uploadFile() {
    if (!this.checkBatch()) return;
    this.uploaderFile.choooseFileAndUpload({ year_code: this.query.year_code, std_type: this.apply_form }, ((ajax) => {
      AppComponent.GobalComponent.successMsg('上传成功');
      this.hideModal();
      this.framePager.reload();
    }).bind(this));
  }

  //查看考生备案相关文件
  checkUploadFile() {
    if (!this.checkBatch()) return;
    FrameRequest.requestEntity(this.FIND_URL, { year_code: this.query.year_code, std_type: this.apply_form }, (entity) => {
      if (!entity) {
        AppComponent.alert({ 'title': '提示', text: '该批次还没有上传文件！' });
      } else {
        FrameRequest.download(this.UPLOAD_DOWNLOAD_URL, { year_code: this.query.year_code, std_type: this.apply_form });
      }
    });

  }

  async aftSaveEvent() {
    AppComponent.alert({ 'title': '提示', text: '保存成功后，请提交考试院审核！' });
  }


  goJoinSchoolDetail(editShowType?) {
    this.editShowType = editShowType;
    FrameRequest.requestArray(this.JOIN_SCHOOL_URL, {year_code: this.query.year_code}, (array) => {
      this.joinSchool = array;
    });
  }

  //退回
  back(join_school_id: any) {
    AppComponent.confirm("确定退回所有考生的备案到衔接学校吗？", () => {
      FrameRequest.request(this.AUDIT_URL, {
        year_code: this.query.year_code,
        join_school_id: join_school_id,
        source_status: 1,
        dest_status: 0
      }, () => {
        AppComponent.GobalComponent.successMsg("退回成功");
        FrameRequest.requestArray(this.JOIN_SCHOOL_URL, {year_code: this.query.year_code}, (array) => {
          this.joinSchool = array;
        });
      });
    });
  }

  //导出
  exportJion() {
    AppComponent.GobalComponent.setLoading(true);
    if(!this.query.year_code) {
      this.query.year_code = "";
    }
    if(!this.query.join_school_id) {
      this.query.join_school_id = "";
    }

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

    
    FrameRequest.download("pl/plStdRecord/exportJion.htm", {
      query:this.query.query,
      year_code : this.query.year_code,
      status : this.query.status,
      mk_id : this.query.mk_id,
      join_school_id : this.query.join_school_id,
      is_xj:this.query.is_xj,
      major_code:this.query.major_code
    }, () => {
      AppComponent.GobalComponent.setLoading(false);
      AppComponent.GobalComponent.successMsg("考生备案导出成功");
    });
  }

}
