import { Component, OnInit, ViewChild } from '@angular/core';
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 { FlexTableComponent } from '../../../../../shared/common/FlexTable.component';

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

  public query = {
    "query": "",
    "year_code": "",
    "mr_id": "",
    "status": "",
    "join_school_id" : "",
    "remark":""
  };
  QUERY_URL = "pl/plStdRecord/pageNet.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/uploadNet.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";
  ASSIST_SCHOOL_URL = "cf/cfOrganization/list.htm?org_type=3&status=1";
  FIND_STD_URL = "/std/stdRegInfo/findStd.htm";

  majorList = []; //主考学校申报的专业
  filePath: any;//错误文件路径
  apply_form = 2; //网络助学考生
  status = 2; //待区考试院审核
  inTime: boolean = false;
  @ViewChild('uploader')
  uploader: FrameUploaderComponent;
  @ViewChild('uploaderFile')
  uploaderFile: FrameUploaderComponent;


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

  ngOnInit() {
    this.chooseMajor();
    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();
      }
    });
  }
  chooseMajor() {
    FrameRequest.requestArray(this.MAJOR_LIST_URL, {
      year_code: this.query.year_code === null ? "" : this.query.year_code,
      apply_form: this.apply_form
    }, (array) => {
      this.majorList = array;
    });
   
  }

  //根据准考证查询考生信息
  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;
      } else {
        AppComponent.alert({ title: "信息提示", text: "准考证填写有误!" });
        return;
      }
    });
  }

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

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

    FrameRequest.requestEntity(this.IN_TIME_URL, {
      year_code: this.query.year_code === null ? "" : this.query.year_code,
      apply_form: this.apply_form
    }, (entity) => {
      this.inTime = entity;
      if (!this.inTime) {
        AppComponent.alert({ title: '提示', text: this.query.year_code + "批次不在提交审核时间范围内，不允许提交！" });
        return false;
      }else{
        this.doSubmit();
      }
    });
    
  }

  async doSubmit(){

    let checkedArray = this.framePager.getCheckedArray();
    if (checkedArray.length === 0) {
      AppComponent.confirm("确定提交本批次的所有考生吗？", () => {
        FrameRequest.request(this.SUBMIT_URL, { year_code: this.query.year_code, status: this.status,std_type:2 }, () => {
          AppComponent.GobalComponent.successMsg("提交成功");
          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,std_type:2 }, () => {
            AppComponent.GobalComponent.successMsg("提交成功");
            this.framePager.reload();
          });
      });

    }
  }

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

  async isInTime() {
    FrameRequest.requestEntity(this.IN_TIME_URL, {
      year_code: this.query.year_code === null ? "" : this.query.year_code,
      apply_form: this.apply_form
    }, (entity) => {
      this.inTime = entity;
      if (!this.inTime) {
        AppComponent.alert({ title: '提示', text: this.query.year_code + "批次不在提交审核时间范围内，不允许提交！" });
        return false;
      }else{
        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: 'net_std_record.xlsx' });
  }

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

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


 

  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
  }


  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 });
      }
    });

  }

  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();
      });
    });
  }
  


}
