import { Component, OnInit } from '@angular/core';
import { FlexTableComponent } from '../../../../../shared/common/FlexTable.component';
import { BsModalService } from 'ngx-bootstrap/modal';
import { FormBuilder, Validators } from '@angular/forms';
import { FrameValidator } from '../../../../../shared/frame/Frame-validator';
import { FrameRequest } from '../../../../../shared/frame/frame-request';
import { AppComponent } from '../../../../..';
import { FrameFunction } from '../../../../../shared/frame/frame_function';
import * as _ from 'lodash';

@Component({
  selector: 'app-paper-thesis-print',
  templateUrl: './paper-thesis-print.component.html',
  styleUrls: ['./paper-thesis-print.component.scss']
})
export class PaperThesisPrintComponent extends FlexTableComponent implements OnInit {

  List_URL = "std/stdRegInfo/list.htm";
  GET_URL = "std/stdRegInfo/get.htm";
  EDIT_URL = "/std/stdRegInfo/editStdReg.htm";
  BATCH_GET_URL = "std/stdRegInfo/batchGet.htm";
  GET_SCHOOL_NAME = "std/stdRegInfo/getSchoolName.htm";
  GET_SCHOOL_BY_MAJOR = "std/stdRegInfo/getSchoolByMajor.htm";
  REG_FORM_URL = "kj/kjCollegeScoreDetail/export.htm";

  stdList = [];
  ticket_no: any;
  std_name: any;
  cert_no: any;
  examAreaOrgArray = [];
  schoolArray = [];
  majorArray = [];
  majorArraySource: any;
  school_name: string;
  flag: boolean = true;
  schoolFlag: boolean = true;
  schoolFlag2: boolean = true;
  old_cert_no: any;
  new_cert_no: any;
  updateCertNoNew_std_id: any;
  updateCertNoWin: any;


  constructor( public bsModalService: BsModalService,
    fb: FormBuilder) { 
    super();
    this.formModel = fb.group({
      std_name: [null, Validators.compose([Validators.required])],//非特殊字符
      cert_no: [null, Validators.compose([Validators.required,Validators.pattern(FrameValidator.pattern_en_number)])],
      std_sex: [null, Validators.compose([Validators.required])],
      std_nation: [null, Validators.compose([Validators.required])],
      std_occupation: [null, Validators.compose([Validators.required])],
      std_birth: [null, Validators.compose([Validators.required])],
      std_mobile: [null, Validators.compose([Validators.required,Validators.pattern(FrameValidator.pattern_phone)])],//手机号
      political_status: [null, Validators.compose([Validators.required])],
      std_email: [null,Validators.compose([Validators.email])],
      std_family_reg: [null, Validators.compose([Validators.required])],
      std_postcode: [null,Validators.compose([Validators.pattern(FrameValidator.pattern_postcode)])],//邮政编码 
      std_source: [null, Validators.compose([Validators.required])],
      std_address: [null, Validators.compose([Validators.required])],
      std_healthy: [null, Validators.compose([Validators.required])],
      std_dh: [null],
      remark: [null],
      std_edu: [null, Validators.compose([Validators.required])],
      std_yhkh: [null],
      std_eng_name: [null],
      major_id: [null, Validators.compose([Validators.required])],
      school_id: [null],
      exam_area_id: [null, Validators.compose([Validators.required])],
    });
  }

  ngOnInit() {
    this.initMajorArray();
    this.initSchoolArray();
  }

  search() {
    FrameRequest.requestArray(this.List_URL, {
      ticket_no : this.ticket_no === undefined ? '': this.ticket_no,
      std_name :this.std_name === undefined ? '': this.std_name,
      cert_no : this.cert_no === undefined ? '': this.cert_no
    }, (array) => {
      this.stdList = array;
     });
  }

  //考生详情界面
  goStdDetail(id: any, editShowType: any, flag: boolean) {
    this.flag = flag;
    FrameRequest.requestEntity(this.GET_URL,{id: id}, async (entity) => {
      if(entity) {
        this.item = entity;
        this.chooseSchool(entity.std_source);
        this.goEditEvent(entity);
      }
      this.editShowType = editShowType;
    });
  }

   goEditEvent(entity){

    //新增
    if(!entity ||!entity.id) {
      
      FrameRequest.requestMap("/std/stdRegInfo/examAreaOrgArray.htm",{}, async (resp) => {
        this.examAreaOrgArray = resp.examAreaOrgArray;
        if(this.examAreaOrgArray.length > 0 ){
        }
      })
      return true;
    }
    //修改
    else{
        FrameRequest.requestMap(this.BATCH_GET_URL,{id:entity.id}, async (resp) => {
          resp.std_reg_info.photo_url_full =  resp.config.url + resp.std_reg_info.photo_url;
          if(resp.std_reg_info){
            entity.photo_url_full = resp.std_reg_info.photo_url_full;
          }
          if(this.examAreaOrgArray.length == 0 ){
            this.examAreaOrgArray = resp.examAreaOrgArray;
          }

        let std_major = resp.std_major;

        this.initMajorLevel(std_major.major_level,entity);
        this.initSchool(entity.id);

          setTimeout(() => {
            AppComponent.GobalComponent.setLoading(false);
          }, 800);
        });
      }

    return true;
  }

  initMajorLevel(major_level,entity){
    entity.major_level = major_level;
  }

  initSchool(id){
    FrameRequest.requestEntity(this.GET_SCHOOL_NAME, {id : id}, (entity) => {
      this.school_name = entity;
    });
  }

  initMajorArray(){
    FrameRequest.requestArray('std/stdRegInfo/queryOpenMajorList.htm',{}, (array) => {
      this.majorArray = array;
      }
    )
  }

  initSchoolArray() {
    FrameRequest.requestArray('cf/cfOrganization/list.htm', {org_type: 1, status: 1}, (array) => {
      this.schoolArray = array;
    });
  }

  //根据考生类型，选择主考学校
  chooseSchool(std_source: any) {
    //社会考生
    if(Number(std_source) === 1) {
      this.schoolFlag = false;
      this.schoolFlag2 = true;
    } else { //助学考生
      this.schoolFlag = true;
      this.schoolFlag2 = false;
    }
  }

  //根据专业选择对应的主考学校，只针对社会考生
  majorChange(major_id: any){
    if(Number(this.item.std_source) === 1) {
      FrameRequest.requestArray(this.GET_SCHOOL_BY_MAJOR, {major_id: major_id}, (array) => {
        if(array && array.length > 0) {
          this.school_name = array[0].org_name;
        }
      });
    }
  }

  
 async saveStd() {
  if (!FrameFunction.validForm(this.formModel)) {
    return;
  }
  if(Number(this.item.std_source) === 3 && !this.item.school_id) {
    AppComponent.alert({ 'title': '提示', 'text': '请选择主考学校' });
    return ;
  }
  let url = this.item.id ? this.EDIT_URL: this.ADD_URL;
  if(!await this.preSaveEvent()) return;
  if(_.isUndefined(this.item.id)) delete this.item.id;
  //循环判断元素是否undefined
  for (const key in this.item) {
    if(this.item[key] === undefined) {
      this.item[key] = "";
    }
  }
  FrameRequest.requestEntity(url, this.item, async () => {
    AppComponent.GobalComponent.successMsg('信息保存成功');
    this.hideModal();
  });
}

public getCheckedArray(func?){
  let checkedArray = []
  _.forEach(this.stdList, (item)=> {
    if(item['isChecked'] === true) 
    if(func && _.isFunction(func)){
      checkedArray.push(func.call(this,item));
    }else{
      checkedArray.push(item);
    }
  });
  return checkedArray;
}

  hideCertNoNewWin(){
    this.updateCertNoWin.hide();
  }

  //打印毕业论文答辩
  printPaper() {
    let checkedArray = this.getCheckedArray();
    if(checkedArray.length != 1){
      //按查询条件生成
      AppComponent.alert({ 'title': '提示', 'text': "请选择一条考生信息!" });
      return;
    }
    AppComponent.GobalComponent.setLoading(true);
    FrameRequest.download(this.REG_FORM_URL, {ticket_no: checkedArray[0].ticket_no}, () => {
      AppComponent.GobalComponent.setLoading(false);
      AppComponent.GobalComponent.successMsg("导出成功");
    });
  }

}
