import { Component, OnInit,ViewChild } from '@angular/core';
import { FrameRequest } from '../../../../shared/frame/frame-request';
import { FlexTableComponent } from '../../../../shared/common/FlexTable.component';
import { AppComponent } from '../../../..';
import { FrameUploaderComponent } from "../../../../core/uploader/uploader.component";
import { DomSanitizer } from  '@angular/platform-browser';
import * as _ from 'lodash';
import { Validators, FormBuilder } from '@angular/forms';
import { FrameValidator } from '../../../../shared/frame/Frame-validator';
import { BsModalService } from 'ngx-bootstrap/modal';
import { FrameFunction } from '../../../../shared/frame/frame_function';
import { FrameVariable } from "../../../../shared/frame/frame-variable";
import { FileUploader, FileItem, ParsedResponseHeaders } from "ng2-file-upload";

@Component({
  selector: 'app-std-reg-search',
  templateUrl: './std-reg-search.component.html',
  styleUrls: ['./std-reg-search.component.scss']
})
export class StdRegSearchComponent 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";
  BATCH_UPLOAD_URL = "std/stdRegInfo/uploadImg.htm";

  @ViewChild('uploaderImgs')
  uploaderImgs:FrameUploaderComponent;

  uploadImageUrlSource = null;

  filePath: any;//错误文件路径

  stdList = [];
  ticket_no: any;
  std_name: any;
  cert_no: any;
  std_mobile: any;
  examAreaOrgArray = [];
  schoolArray = [];
  majorArray = [];

  std_citys = [];
  std_countys = [];

  provinces = [];
  citys = [];
  countys = [];

  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;
  uploadImageUrl = null;
  batchUploadPhotoModalWin4Edit: any;
  uploadFile: any;

  batchFileuploader:FileUploader = new FileUploader({
    url: FrameVariable.BASE_URL + this.BATCH_UPLOAD_URL, 
    method: "POST",                                                                     
    itemAlias: "file",     
    isHTML5: true,
    autoUpload: false,
    removeAfterUpload: true,                                            
    });

  fileuploader4Edit:FileUploader = new FileUploader({
    url: FrameVariable.BASE_URL + this.BATCH_UPLOAD_URL, 
    method: "POST",                                                                     
    itemAlias: "file",     
    isHTML5: true,
    autoUpload: false,
    removeAfterUpload: true,                                            
    });
  upload_dir_id: any;
  upload_img_access: any;
  upload_img_passList: any;
  upload_img_failList: any;
  upload_img_failList_size: any;
  upload_img_passListStd: any;

  uploadImgsWin: any;


  constructor( public bsModalService: BsModalService,
    fb: FormBuilder,private sanitizer: DomSanitizer,) { 
    super();
    this.formModel = fb.group({
      std_name: [null, Validators.compose([Validators.required])],//非特殊字符
      // std_eng_name: [null],
      // enrol_no: [null, Validators.compose([Validators.required])],
      cert_no: [null, Validators.compose([Validators.required,Validators.pattern(FrameValidator.pattern_en_number)])],
      // school_code: [null],
      std_sex: [null, Validators.compose([Validators.required])],
      ticket_no: [null],
      std_nation: [null, Validators.compose([Validators.required])],
      // belong_city_id: [null],
      std_occupation: [null, Validators.compose([Validators.required])],
      std_birth: [null, Validators.compose([Validators.required])],
      // enrol_county_city: [null],
      std_mobile: [null, Validators.compose([Validators.required,Validators.pattern(FrameValidator.pattern_phone)])],//手机号
      bindphone: [null, Validators.compose([Validators.pattern(FrameValidator.pattern_phone)])],//手机号
      bind_email: [null, Validators.compose([Validators.pattern(FrameValidator.pattern_email)])],//邮件

      
      // learn_form: [null],
      // enrol_place: [null, Validators.compose([Validators.required])],
      political_status: [null, Validators.compose([Validators.required])],
      //std_email: [null,Validators.compose([Validators.email])],//, Validators.compose([Validators.required,Validators.email])
      std_email: [null, Validators.compose([Validators.pattern(FrameValidator.pattern_email)])],//邮件

      std_family_reg: [null, Validators.compose([Validators.required])],
      // old_ticket_no1: [null],
      std_postcode: [null,Validators.compose([Validators.pattern(FrameValidator.pattern_postcode)])],//邮政编码 , Validators.compose([Validators.required,Validators.pattern(FrameValidator.pattern_postcode)])
      std_source: [null, Validators.compose([Validators.required])],
      std_address: [null, Validators.compose([Validators.required])],
      // assist_attr: [null],
      std_healthy: [null, Validators.compose([Validators.required])],
      // std_birth_place: [null],
      // old_ticket_no2: [null],
      std_dh: [null],
      remark: [null],
      std_edu: [null, Validators.compose([Validators.required])],
      std_yhkh: [null],
      std_eng_name: [null],
      major_id: [null],
      school_id: [null],
      exam_area_id: [null],
      std_city: [null],
      std_county: [null],
      is_identfiy: [null],
      cert_type: [null],
      photo_compliance: [null],
      province: [null],
      city: [null],
      county: [null],
      
    });
  }

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

    FrameRequest.requestArray('std/stdRegInfo/queryCity.htm',{}, (array) => {
      this.std_citys = array;
      }
    );

    FrameRequest.requestArray('epidemic/highRiskArea/queryBzmbGbXzqhdm.htm',{parent_id:'000000'}, (array) => {
      this.provinces = array;
      }
    );
  }

  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,
      std_mobile: this.std_mobile === undefined ? '': this.std_mobile,
    }, (array) => {
      this.stdList = array;
      if(array && array.length>0){
        
      }else{
        AppComponent.GobalComponent.errorMsg("没有可查询的记录");
      }
     
     });
  }

  //考生详情界面
  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) => {
          if(resp.std_reg_info.photo_url){
            resp.std_reg_info.photo_url_full =  resp.config.url + resp.std_reg_info.photo_url;
          }

          if(resp.std_reg_info.photo_url_full){
            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);

        if(entity.std_city){
          FrameRequest.requestArray('std/stdRegInfo/queryCityCounty.htm',{std_city:entity.std_city}, (array) => {
            this.std_countys = array;
            }
          );
        }

        if(entity.province){
          FrameRequest.requestArray('epidemic/highRiskArea/queryBzmbGbXzqhdm.htm',{parent_id:entity.province}, (array) => {
            this.citys = array;
            }
          );
        }

        if(entity.city){
          FrameRequest.requestArray('epidemic/highRiskArea/queryBzmbGbXzqhdm.htm',{parent_id:entity.city}, (array) => {
            this.countys = array;
            }
          );
        }

          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("/std/cfOrganization/listOrderBy.htm",{org_type:1,status:1}, async (array) => {
      this.schoolArray = array;
    })
   
  }

  // majorLevelChange(event){
  //   let major_level = event.currentTarget.value;
  //   if(!this.majorArraySource){
  //     FrameRequest.requestArray('std/stdRegInfo/queryOpenMajorList.htm',{}, (array) => {
  //         this.majorArraySource = array;
  //         this.majorFilterByLevel(major_level);
  //       })
  //   }
  //   else{
  //     this.majorFilterByLevel(major_level);
  //   }

  // }

  // majorFilterByLevel(major_level){
  //   this.majorArray = _.filter(this.majorArraySource,{'major_level': parseInt(major_level)});
  // }
  //根据考生类型，选择主考学校
  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;
        }
      });
    }
  }

  sfzchangeItem(event){
    let cert_type = event.currentTarget.value;
    
    if(cert_type == 1 && this.item.cert_no && this.item.cert_no.length == 18){
      
      let  cert_no = this.item.cert_no;
      //生日
      this.item.std_birth  = cert_no.substring(6,10) + "-" + cert_no.substring(10,12) + "-" + cert_no.substring(12,14);
      //性别 
      this.item.std_sex = (parseInt(this.item.cert_no.substring(16,17)) % 2) == 1?"1":"2";
      this.item.cert_no = this.item.cert_no.toUpperCase();
    }
    
  } 

  certNoBlurItem(event){
    
    let value = event.currentTarget.value;
    if(this.item.cert_type == 1 && value && value.length == 18){
      let  cert_no = this.item.cert_no;
      //生日
      this.item.std_birth  = cert_no.substring(6,10) + "-" + cert_no.substring(10,12) + "-" + cert_no.substring(12,14);
      //性别 
      this.item.std_sex = (parseInt(this.item.cert_no.substring(16,17)) % 2) == 1?"1":"2";
      this.item.cert_no = this.item.cert_no.toUpperCase();
    }
  }

  
  async preSaveEvent(){
    if(this.item.std_source == 3 && !String(this.item.schoole_id)){
      AppComponent.alert({ 'title': '提示', 'text': "助学考生主考学校为必填项!" });
      return false;
    }

    if(!this.item.major_id){
      AppComponent.alert({ 'title': '提示', 'text': "请选择专业!" });
      return false;
    }

    if(!this.item.exam_area_id){
      //AppComponent.alert({ 'title': '提示', 'text': "请选择所属考区!" });
      //return false;
      this.item.exam_area_id= 1020;
    }

    if(this.item.cert_type == 1 && this.item.cert_no && this.item.cert_no.length == 18){
      //性别 
      let cert_no_sex = (parseInt(this.item.cert_no.substring(16,17)) % 2) == 1?"1":"2";
      if(cert_no_sex != this.item.std_sex){
        AppComponent.alert({ 'title': '提示', 'text': "性别与身份证性别不符合,不允许修改!" });
        return false;
      }
    }
   
    return true;
  }

 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] = "";
    }
  }
  this.item.isCanEdit="";
  this.item.isProvince="";
  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;
}

  toUpdateCertNoNew(tm){
    let checkedArray = this.getCheckedArray();
    if(checkedArray.length != 1){
      //按查询条件生成
      AppComponent.alert({ 'title': '提示', 'text': "请选择一条考生信息!" });
    }else{
      this.updateCertNoNew_std_id = checkedArray[0].id;
      FrameRequest.request('std/stdRegInfo/toUpdateNewCertNo.htm',{std_id:checkedArray[0].id}, (resp) => {
        if(resp.success){
          if(resp.errorMsg){
           AppComponent.alert({ 'title': '提示', 'text': resp.errorMsg });
          }else{
           //跳转新证件model
           this.old_cert_no = resp.entity.cert_no;
           this.new_cert_no = "";
           let modalcss = "modal-sm";
           this.updateCertNoWin = this.bsModalService.show(tm, { class: modalcss });
          }
        }else{
         AppComponent.alert({ 'title': '提示', 'text': resp.errorMsg });
        }
       }
     )
  
    }
  }

  updateCertNoNew(){
    if(!this.new_cert_no){
      AppComponent.alert({ 'title': '提示', 'text': "请输入新身份证号" });
      return;
    }

    AppComponent.confirm("确认为考生升级身份证?",()=>{
      FrameRequest.request('std/stdRegInfo/updateNewCertNo.htm',{std_id:this.updateCertNoNew_std_id,cert_no_new:this.new_cert_no}, (resp) => {
        if(resp.success){
          if(resp.errorMsg){
            AppComponent.GobalComponent.errorMsg(resp.errorMsg);
          }else{
           //跳转新证件model
           AppComponent.GobalComponent.successMsg("身份证升位成功");
           
           this.search();
           //关闭model
           this.updateCertNoWin.hide();
          }
        }else{
          AppComponent.GobalComponent.errorMsg(resp.errorMsg);
        }
       })
    });
 
  }

  checkIdentifyCard(){
    let checkedArray = this.getCheckedArray();
    if(checkedArray.length != 1){
      //按查询条件生成
      AppComponent.alert({ 'title': '提示', 'text': "请选择一条考生信息!" });
      return;
    }else{
      let is_identfiy = checkedArray[0].is_identfiy;
      if(is_identfiy == 1){
        AppComponent.alert({ 'title': '提示', 'text': "该考生身份证认证已经通过，不需要再次认证!" });
        return;
      }else{
        let cert_no = checkedArray[0].cert_no;
        
            FrameRequest.request('std/stdRegInfo/identifyCard.htm',{std_id:checkedArray[0].id}, (resp) => {
              if(resp.success){
                if(resp.errorMsg){
                  AppComponent.alert({ 'title': '提示', 'text': resp.errorMsg });
                }else{
                  AppComponent.alert({ 'title': '提示', 'text': "身份认证成功!" });
                }
              }else{
              AppComponent.alert({ 'title': '提示', 'text': resp.errorMsg });
              }
            }
           )
        
       
      }
  
    }
  }

  hideCertNoNewWin(){
    this.updateCertNoWin.hide();
  }
  
  resetData(){
    this.ticket_no="";
    this.std_name="";
    this.cert_no="";
    this.std_mobile = "";
  }

    //个人信息编辑 弹出上传图片modal
    UploadPic4Edit(templateModal){
    if(this.item.id == undefined || !String(this.item.id)){
      //提示数据已经存在 无法新增
      AppComponent.alert({ 'title': '提示', 'text': '考生信息未提交无法上传图片,请提交后再操作!' });
      return;
    }
    
    if(this.item.isProvince != 999){
      if(this.item.isCanEdit == 1){
          AppComponent.alert({ 'title': '提示', 'text': "当前批次内存在报考信息,无法重新上传图片!" });
          return;
      }else if(this.item.isCanEdit == 2){
        AppComponent.alert({ 'title': '提示', 'text': "存在历史成绩,无法重新上传图片!" });
        return;
      }else{
          this.batchUploadPhotoModalWin4Edit = this.bsModalService.show(templateModal, { class: "modal-md" });
          this.uploadImageUrl = null;
      }
      
    }else{
        this.batchUploadPhotoModalWin4Edit = this.bsModalService.show(templateModal, { class: "modal-md" });
        this.uploadImageUrl = null;
    }

  }

      //选择上传附件
  img_accept_type = "image/png, image/jpeg, image/gif, image/jpg";
  onChangeSelectFile(event){
    this.batchFileuploader.clearQueue();
    if(event.currentTarget.files.length != 1){
      AppComponent.alert({ 'title': '提示', 'text': '请选择单个上传文件!' });
      return;
    }
    const file = event.currentTarget.files[0];   
    this.uploadFile = file;
    //图片格式 大小验证
    if(this.img_accept_type.indexOf(file.type) == -1){
      AppComponent.alert({ 'title': '提示', 'text': '上传图片只支持png jpeg gif jpg格式!' });
      return;
    }
    // 必须 bypassSecurityTrustUrl 转换一下 url ，要不然angular会报，说url不安全错误。   
    this.uploadImageUrlSource =  window.URL.createObjectURL(file);
    this.uploadImageUrl = this.sanitizer.bypassSecurityTrustUrl(this.uploadImageUrlSource); 

    this.batchFileuploader.addToQueue(event.currentTarget.files, event.target.options);
  }

  onChangeSelectFile4Edit(event){
    this.fileuploader4Edit.clearQueue();
    if(event.currentTarget.files.length != 1){
      AppComponent.alert({ 'title': '提示', 'text': '请选择单个上传文件!' });
      return;
    }
    const file = event.currentTarget.files[0];   
    this.uploadFile = file;
    //图片格式 大小验证
    if(this.img_accept_type.indexOf(file.type) == -1){
      AppComponent.alert({ 'title': '提示', 'text': '上传图片只支持png jpeg gif jpg格式!' });
      return;
    }
    // 必须 bypassSecurityTrustUrl 转换一下 url ，要不然angular会报，说url不安全错误。   
    this.uploadImageUrlSource =  window.URL.createObjectURL(file);
    this.uploadImageUrl = this.sanitizer.bypassSecurityTrustUrl(this.uploadImageUrlSource); 

    this.fileuploader4Edit.addToQueue(event.currentTarget.files, event.target.options);
  }

  


  handleUploadFile4Edit(){
    this.fileuploader4Edit.onBuildItemForm  = (fileItem: FileItem, form: any) =>{
      form.append("std_id", this.item.id);
    }
 
    this.fileuploader4Edit.onSuccessItem  = (item: FileItem, response: string, status: number, headers: ParsedResponseHeaders) =>{
      
      let respObj = JSON.parse(response);
      if(respObj.success){
        let url = respObj.map.url;
        let std = respObj.map.stdRegInfo;
        this.item.photo_url = null;
        std.photo_url_full = url + std.photo_url;
        AppComponent.GobalComponent.successMsg('图片上传成功');
        setTimeout(() => {
          this.item = std;
          this.batchUploadPhotoModalWin4Edit.hide();
        }, 500);
      }else{
        AppComponent.alert({ 'title': '提示', 'text': respObj.errorMsg });
        setTimeout(() => {
          this.batchUploadPhotoModalWin4Edit.hide();
        }, 500);
      }
      
    }
 
    this.fileuploader4Edit.queue[0].upload();
  }

  cityChange(event){
    let std_city = event.currentTarget.value;
   
    if(std_city){
      FrameRequest.requestArray('std/stdRegInfo/queryCityCounty.htm',{std_city:std_city}, (array) => {
          this.std_countys = array;  
        })
    }

  }


  cityChangeForAddress(parent_id){
    if(parent_id){
      FrameRequest.requestArray('epidemic/highRiskArea/queryBzmbGbXzqhdm.htm',{parent_id:parent_id}, (array) => {
          this.citys = array;  
        })
    }

  }

  countyChangeForAddress(parent_id){
    if(parent_id){
      FrameRequest.requestArray('epidemic/highRiskArea/queryBzmbGbXzqhdm.htm',{parent_id:parent_id}, (array) => {
          this.countys = array;  
        })
    }

  }


  
  downloadIdCardPhoto(){
    
    let mess = "";
    if(this.item.idcard_photo_path){
      mess = "身份证照片已经存在，确定重新更新身份证照片吗？";
    }else{
      mess = "确定更新身份证照片吗？";
    }

    AppComponent.confirm(mess,()=>{
      FrameRequest.request('std/stdRegInfo/downloadIdCardPhoto.htm',{std_id:this.item.id}, (resp) => {
        if(resp.success){
          if(resp.errorMsg){
            AppComponent.GobalComponent.errorMsg(resp.errorMsg);
        
          }else{
            this.item.idcard_photo_path = resp.entity.idcard_photo_path;
            AppComponent.GobalComponent.successMsg('下载身份证照片成功!');
          }
        }else{
          AppComponent.GobalComponent.errorMsg(resp.errorMsg);
         
        }
       }
     )
     
    });

    
  }


}
