import { Component, OnInit, TemplateRef, ViewChild } from '@angular/core';
import { BsModalService } from 'ngx-bootstrap/modal';
import { FormBuilder, Validators } from '@angular/forms';
import { FlexTableComponent } from '../../../../../shared/common/FlexTable.component';
import { FrameRequest } from '../../../../../shared/frame/frame-request';
import { AppComponent } from '../../../../../app.component';
import { DomSanitizer } from '@angular/platform-browser';
import { FramePagerComponent } from '../../../../../core/pager/pager.component';
import { FrameFunction } from '../../../../../shared/frame/frame_function';

const SHOW_EDIT_TYPE2 = {
  "MODAL":"modal",
  "ONLY":"only",
  "SHOW":"show",
};

@Component({
  selector: 'app-files-extract',
  templateUrl: './files-extract.component.html',
  styleUrls: ['./files-extract.component.scss']
})
export class FilesExtractComponent  extends FlexTableComponent implements OnInit {

  QUERY_URL = "by/scan/std/page.htm";
  GET_URL= "by/scan/std/find.htm";
  EDIT_URL = "by/scan/std/edit.htm";
  PDF_URL = "by/scan/std/pdf/download.htm";
  BATCH_URL ="by/scan/std/yearmonth/list.htm";
  APPLY_QUERY_URL = "by/apply/his/page.htm";
  APPLY_QUERY_OTHER_URL = "by/apply/his/other/page.htm";

  pdfurl:any;
  pdfname:any;
  id: any;
  status = true;
  batchArr = [];
  tagArr = [];
  matchArr = [
    {name:'待匹配', value:null},
    {name:'已匹配', value:1},
    {name:'存疑需确认', value:2},
    {name:'未成功匹配', value:3},
  ];



  public query = {
    query : '',
    year_month: '',
    tag: '',
    match_status: '',
    match_query: '',
    match_other_query: '',
    major_name: '',
    year_month_his:''
  };

  @ViewChild('framePager2')
  framePager2: FramePagerComponent; 
  @ViewChild('framePager3')
  framePager3: FramePagerComponent; 

  constructor(public bsModalService: BsModalService, fb: FormBuilder,private sanitizer: DomSanitizer) {
    super();
    this.formModel = fb.group({
      id: [null],
      std_name: [null,Validators.required],
      cert_id: [null,null],
      graduate_no: [null,null],
      graduate_major: [null,null],
      edu_level: [null,null]
    });
   }

  ngOnInit() {
    this.requestBatch();
  }


  check(editTemplateModal,item) {
    this.id = item.id;
    this.query.year_month_his=this.query.year_month;
    this.goEdit(editTemplateModal,'only','modal-lg',item);
  }

  editMatch(matchTemplateModal,item) {
    this.id = item.id;
    this.goEditMatch(matchTemplateModal,'match','modal-lg',item);
  }


  async preGoEditEvent(item?){
    this.status = true;
    AppComponent.GobalComponent.setLoading(true);
    if(item) {
      this.query.match_other_query = item.std_name;
      //this.query.year_month = item.year+'年' + item.month+'月';
    }
    FrameRequest.requestEntity("by/scan/std/pdf/exists.htm", {id: this.id}, (entity) => {
      if (!entity) {
        this.downloadFile();
      }else{
        AppComponent.alert({title:"信息提示",text:entity});
        AppComponent.GobalComponent.setLoading(false);
        this.hideModal();
      }
    });
      return true;
    }

    downloadFile() {
      FrameRequest.downloadService(this.PDF_URL, {id: this.id}).subscribe(res => {
        let content = res.headers.get('content-disposition');
        this.pdfname = content.substring(content.indexOf("=")+1,content.length);
        let blob = new Blob([res.json()], { type: "application/pdf" });
        let objectUrl = URL.createObjectURL(blob);
        objectUrl += '#view=FitH,top';
        this.pdfurl = this.sanitizer.bypassSecurityTrustResourceUrl(objectUrl);
        AppComponent.GobalComponent.setLoading(false);
        });
    }

    requestBatch() {
      FrameRequest.requestArray(this.BATCH_URL, {}, (array)=> {
        this.batchArr = array;
      });
    }

    getTag($event) {
      this.tagArr = [];
      FrameRequest.requestArray('by/scan/std/tag/list.htm', {year_month: $event}, (array)=> {
        this.tagArr = array;
      });
    }

    //匹配
    match() {
      AppComponent.confirm('确认要匹配吗？匹配需要一定时间，请耐心等待！',() => {
        AppComponent.GobalComponent.setLoading(true);
        FrameRequest.request('by/std/match.htm', {}, () => {
          AppComponent.GobalComponent.successMsg('已完成匹配!');
          this.framePager.reload();
          AppComponent.GobalComponent.setLoading(false);

        });
      });
    }

    matchByNo() {
      AppComponent.confirm('确认要以毕业证号匹配吗？匹配需要一定时间，请耐心等待！',() => {
        AppComponent.GobalComponent.setLoading(true);
        FrameRequest.request('by/std/matchByNo.htm', {}, () => {
          AppComponent.GobalComponent.successMsg('已完成匹配!');
          this.framePager.reload();
          AppComponent.GobalComponent.setLoading(false);
        });
      });
    }

    

    oneMatch(id) {
      AppComponent.confirm('确认要匹配吗？',() => {
        FrameRequest.request('by/std/match.htm', {id: id}, () => {
          AppComponent.GobalComponent.successMsg('已完成匹配！');
          this.framePager.reload();
        });
      });
    }

    async goEditMatch(template: TemplateRef<any>,editShowType = SHOW_EDIT_TYPE2.MODAL,modalcss:string,item?){
   
      FrameFunction.UntouchedForm(this.formModel);
       //新增
       if(!item || item.id === undefined) {
          if(! await this.preGoEditEvent()) return ;
          if(!this.item) {
            this.item = {};
          } 
          this.formModel.reset();
          this.showEdit(template, editShowType, modalcss);
          this.aftGoEditEvent();
        } else {
          FrameRequest.requestEntity(this.GET_URL,{id: item.id}, async (entity) => {
            if(! await this.preGoEditEventMatch(entity)) return ;
            this.showEdit(template, editShowType, modalcss);
            setTimeout(async ()=>{
              this.item = entity;
              this.aftGoEditEvent();
            },100)
          });
        }
      }

    async preGoEditEventMatch(entity){
      this.query.match_query = entity.std_name;
      this.status = true;
      AppComponent.GobalComponent.setLoading(true);
      FrameRequest.requestEntity("by/scan/std/pdf/exists.htm", {id: this.id}, (entity) => {
        if (!entity) {
          this.downloadFile();
          this.framePager2.reload();
        }else{
          AppComponent.alert({title:"信息提示",text:entity});
          AppComponent.GobalComponent.setLoading(false);
          this.hideModal();
        }
      });
        return true;
      }

      handMatch(id) {
        AppComponent.confirm('确定要匹配该考生吗？', () => {
          FrameRequest.request('by/apply/his/match/hand.htm', {apply_his_id: id, by_scan_std_id:this.item.id}, () => {
            AppComponent.GobalComponent.successMsg('修改成功！');
            this.hideModal();
            this.framePager.reload();
          });
        });
      }

      handMatchAndUpdate(id) {
        AppComponent.confirm('确定要更新并匹配该考生吗？', () => {
          FrameRequest.request('by/apply/his/match/handMatchAndUpdate.htm', {apply_his_id: id, by_scan_std_id:this.item.id}, () => {
            AppComponent.GobalComponent.successMsg('更新并匹配成功！');
            this.hideModal();
            this.framePager.reload();
          });
        });
      }

      updateMatchStatus(id) {
        AppComponent.confirm('确定要更新匹配状态吗？', () => {
          FrameRequest.request('by/apply/his/match/updateMatchStatus.htm', {apply_his_id: id, by_scan_std_id:this.item.id}, () => {
            AppComponent.GobalComponent.successMsg('更新匹配状态成功！');
            this.hideModal();
            this.framePager.reload();
          });
        });
      }

     
      

}
