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';
import { FramePagerComponent } from "../../../../../core/pager/pager.component";

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

  main_id = null;
  main_status = null;
  curr_item = null;
  bsModalWin2 = null;

  public query = {
    "query": "",
    "year_code": "",
    "main_name":"",
    "mr_id": "",
    "cancel_status": "",
    "join_school_id" : "",
    "remark":"",
    "std_type":"2",
    "create_org_id":""
  };

  public querystd = {
    query: "",
    "std_type":"2"
  };
  MAIN_QUERY_URL = "pl/plStdRecordCancelMain/page.htm";
  QUERY_URL = "pl/plStdRecordCancel/page.htm";
  DELETE_URL = "pl/plStdRecordCancel/delete.htm";
  GET_URL = "pl/plStdRecordCancel/get.htm";
  ADD_URL = "pl/plStdRecordCancel/add.htm";
  EDIT_URL = "pl/plStdRecordCancel/edit.htm";
  UPLOAD_URL = "pl/plStdRecordCancel/uploadCancel.htm";
  DOWNLOAD_URL = "pl/plStdRecordCancel/download.htm";
  ERROR_DOWNLOAD_URL = "pl/plStdRecordCancel/downloadError.htm";
  YEAR_CODE_URL = "pl/plExamTime/list.htm";
  MAJOR_LIST_URL = "pl/plMajorRecord/list.htm";
  SUBMIT_URL = "pl/plStdRecordCancel/submit.htm";
  IN_TIME_URL = "pl/plStdRecordTime/inTime.htm";
  UPLOAD_FILE_URL = "pl/plStdRecordCancelFile/upload.htm";
  UPLOAD_DOWNLOAD_URL = "pl/plStdRecordCancelFile/download.htm";
  FIND_URL = "pl/plStdRecordCancelFile/find.htm";
  LASTEST_YEAR_CODE_URL = "pl/plStdRecordTime/getBatch.htm";
  ASSIST_SCHOOL_URL = "cf/cfOrganization/list.htm?org_type=3";

  SCHOOL_URL = "cf/cfOrganization/listOrganizationForCancelPlStdRecord.htm?org_type=1&status=1";
  EXPORT_URL = "pl/plStdRecord/export.htm";
  STD_QUERY_URL = "pl/plStdRecord/queryPlStdRecordByQuery.htm";
  FILE_QUERY_URL = "pl/plStdRecordCancelFile/queryStdRecordCancelFile.htm";

  majorList = []; //主考学校申报的专业
  filePath: any;//错误文件路径
  apply_form = 2; //网络助学考生
  status = 2; //待区考试院审核
  inTime: boolean = false;
  curr_year_code: any;
  std_type = "2";
  stdRefList: any;
  fileList: any;

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


  constructor(public bsModalService: BsModalService, fb: FormBuilder) {
    super();
    this.formModel = fb.group({
     // query: [null]
      
    });
  }


  ngOnInit() {
    this.editShowType = 'detail';
    FrameRequest.requestEntity(this.LASTEST_YEAR_CODE_URL, {std_type:this.std_type}, (entity) => {
      if (entity) {
        this.curr_year_code = entity.year_code;
        this.query.year_code = entity.year_code;
        this.mainPager.reload();
      }
    });
  }
  


  //关闭导入框，留在详情界面
  hideImpWin() {
    if(this.bsModalWin) 
      this.bsModalWin.hide();
      this.editShowType = "only";
  }

  hideEditWin() {
    this.editShowType = "only";
      
  }

  goBack(){
    if(this.bsModalWin) 
      this.bsModalWin.hide();
    this.editShowType = "detail";
  }

  goDetailList(item){
    this.main_id = item.id;
    this.main_status = item.status;
    this.editShowType = "only";
    this.framePager.reload();
  }

  searchDetail(param){
    param.query = this.query.query;

    param.main_id = this.main_id;
  }

  search(param){
    param.query = this.query.query;
    param.year_code =this.query.year_code;
    param.cancel_status =this.query.cancel_status;
    param.std_type = this.std_type;
  }

  showCreate(createApplyModal,modal){
    if (!this.query.year_code) {
      AppComponent.alert({ 'title': '提示', text: '请选择注销批次！' });
      return;
    }
   

    this.shouModalWin(createApplyModal,modal);
  }


  createMain(){
   
    AppComponent.confirm("确定创建考生注销申请单吗",()=>{
      let main_name = this.query.main_name;
      if(!main_name){
        main_name = "";
      }

      FrameRequest.request("pl/plStdRecordCancelMain/add.htm", {year_code:this.query.year_code,std_type: this.std_type,main_name:main_name}, (ret)=>{
        if (ret.errorCode == 0) {
          
          this.mainPager.reload();
          this.query.main_name="";
          this.bsModalWin.hide();
          AppComponent.GobalComponent.successMsg('创建申请单成功!');
        }
      });
    });
  }

  resetDetail(){
    this.query.query = "";
  }

  resetMain(){
    if(this.curr_year_code){
      this.query.year_code = this.curr_year_code;
    }else{
      this.query.year_code = "";
    }
     this.query.query = "";
     this.query.cancel_status = "";
     this.query.std_type = this.std_type;
  }

  deleteMain(item){
    AppComponent.confirm("确定删除注销申请单吗",()=>{
      FrameRequest.request("pl/plStdRecordCancelMain/delete.htm", {ids:item.id}, (ret)=>{
        if (ret.errorCode == 0) {
          
          this.mainPager.reload();
          
          AppComponent.GobalComponent.successMsg('删除申请单成功!');
        }
      });
    });
  }

  dogoEdit(editTemplateModal,item){
    if (this.main_status != 1) {
      AppComponent.alert({ 'title': '提示', text: '只能对待主考学校审核提交的申请单进行操作！' });
      return;
    }
    item={};
    this.goEdit(editTemplateModal,'only','modal-lg',item);
    
    
  }

  async aftGoEditEvent(){
    this.editShowType='add';
  }

// 提交审核
  apply(){
      
    let checkedArray = this.mainPager.getCheckedArray();
    if (checkedArray.length === 0) {
        AppComponent.alert({ 'title': '提示', text: '请选择申请单！' });
        return;
    } else {
      AppComponent.confirm("确定提交选中的记录吗？", () => {
        let checkIds = this.mainPager.getCheckedArray((item) => item.id);
        FrameRequest.request("pl/plStdRecordCancel/apply.htm", {ids: checkIds.join(",") }, () => {
          AppComponent.GobalComponent.successMsg("提交成功");
          this.mainPager.reload();
        });
      });

      
    }
  }

  //引用考生-查询
  findStdRefList() {
    
    if (!this.querystd.query) {
      AppComponent.alert({title:"信息提示",text:"请输入关键字!"});
      return;
    }

   
    AppComponent.GobalComponent.setLoading(true);
    FrameRequest.requestArray(this.STD_QUERY_URL, this.querystd, (arrary) => {
      
        AppComponent.GobalComponent.setLoading(false);
        this.stdRefList = arrary;
    });
  }

  stdRefRadioCheckFun(item) {
   
    this.item = item;
  }

  resetStd(){
    this.querystd.query = "";
   
  }


  addStdRecordCancel() {
    
    if (!this.item || !this.item.id) {
      AppComponent.alert({title:"信息提示",text:"请选择一条考生备案信息!"});
      return ;
    }

    if(this.item.status != '3'){
      AppComponent.alert({title:"信息提示",text:"只允许选择状态是审核通过并归档的考生备案信息!"});
      return ;
    }

    AppComponent.confirm("确定保存考生备案注销信息吗？", () => {
      this.item.main_id = this.main_id;
      FrameRequest.request(this.ADD_URL, this.item, () => {
        AppComponent.GobalComponent.successMsg("保存成功");
        this.hideEditWin();
        this.framePager.reload();
      });
    });
  }


    //撤回
    callback() {
      
      let checkedArray = this.mainPager.getCheckedArray();
      if (checkedArray.length === 0) {
          AppComponent.alert({ 'title': '提示', text: '请选择申请单！' });
          return;
      } else {
        AppComponent.confirm("确定撤回选中的记录吗？", () => {
          let checkIds = this.mainPager.getCheckedArray((item) => item.id);
          FrameRequest.request("pl/plStdRecordCancel/callback.htm", {ids: checkIds.join(",") }, () => {
            AppComponent.GobalComponent.successMsg("撤回成功");
            this.mainPager.reload();
          });
        });

        
      }
    }

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

  //提交审核
  audit() {
    if (!this.checkBatch()) return;
    if(!this.isInTime()) return;
    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 }, () => {
          AppComponent.GobalComponent.successMsg("提交成功");
          this.framePager.reload();
        });
      });
    } else {
      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.framePager.reload();
      });
    }
  }

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

    if (this.main_status != 1) {
      AppComponent.alert({ 'title': '提示', text: '只能对待主考学校审核提交的申请单进行操作！' });
      return;
    }
    
    this.uploader.choooseFileAndUpload({main_id:this.main_id}, ((ajax) => {
      if (ajax.errorCode === -1) {
        this.filePath = ajax.url;
        AppComponent.alert({ 'title': '提示', 'text': '有错误数据，请修正后，在重新上传' });
      } else {
        AppComponent.GobalComponent.successMsg('批量导入成功');
        this.filePath = '';
        this.framePager.reload();
      }
    }).bind(this));
  }


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

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

  //导出
  exportNet() {
    AppComponent.GobalComponent.setLoading(true);
    FrameRequest.download("pl/plStdRecordCancel/exportNet.htm", {
      query:this.query.query,
      main_id : this.main_id
    }, () => {
      AppComponent.GobalComponent.setLoading(false);
      AppComponent.GobalComponent.successMsg("考生备案注销导出成功");
    });
  }


 

  async preSaveEvent() {
    this.item.main_id=this.main_id;
    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?) {
    

    let css = modalcss ? modalcss : "modal-lg";
    this.bsModalWin2 = this.bsModalService.show(editFormTemplateModal, { class: css });
  }

  goQueryUploadFile(editFormTemplateModal, item) {
   
      this.curr_item = item;
      this.main_id = item.id;
      this.main_status = item.status;
      FrameRequest.requestArray(this.FILE_QUERY_URL, {main_id:item.id}, (arrary) => {
        this.fileList = arrary;
    });

    let css = "modal-lg";
    this.bsModalWin = this.bsModalService.show(editFormTemplateModal, { class: css });
  }

  //上传考生备案相关文件
  uploadFile() {
    if (!this.checkBatch()) return;

    if (this.curr_item.status != 1) {
      AppComponent.alert({ 'title': '提示', text: '只能对待主考学校审核提交的申请单进行操作！' });
      return;
    }

    
    this.uploaderFile.choooseFileAndUpload({ main_id:this.curr_item.id}, ((ajax) => {
      
      if(ajax.success){
        AppComponent.GobalComponent.successMsg('上传证明材料成功');
        this.bsModalWin2.hide();
          FrameRequest.requestArray(this.FILE_QUERY_URL, {main_id:this.curr_item.id}, (arrary) => {
            this.fileList = arrary;
        });
      }else{
        AppComponent.GobalComponent.errorMsg(ajax.errorMsg);
        this.bsModalWin2.hide();
      }
     
    }).bind(this));
  }

  //查看考生备案相关文件
  checkUploadFile(item) {
    
    FrameRequest.download(this.UPLOAD_DOWNLOAD_URL, { id: item.id});


  }

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

  deleteFile(item) {

    if (this.curr_item.status != 1) {
      AppComponent.alert({ 'title': '提示', text: '只能对待主考学校审核提交的申请单进行操作！' });
      return;
    }
    
    AppComponent.confirm("确定删除证明材料吗？", () => {
     
      FrameRequest.request("pl/plStdRecordCancelFile/delete.htm", { ids: [item.id] }, () => {
        AppComponent.GobalComponent.successMsg("删除成功");
          FrameRequest.requestArray(this.FILE_QUERY_URL, {main_id:item.main_id}, (arrary) => {
            this.fileList = arrary;
        });
  
      });
    });
  }


}
