import { Component, OnInit, Input, ViewChild, Output, EventEmitter } from "@angular/core";
import { FlexTableComponent } from "../../../../shared/common/FlexTable.component";
import { FormBuilder, Validators } from '@angular/forms';
import { CustomValidators } from 'ng2-validation';
import { BsModalService } from "ngx-bootstrap/modal";
import { FramePagerComponent } from "../../../../core/pager/pager.component";
import { FrameRequest } from "../../../../shared/frame/frame-request";
import { FrameUploaderComponent } from "../../../../core/uploader/uploader.component";
import { AppComponent, InjectorInstance } from "../../../..";
import { FrameValidator } from "../../../../shared/frame/Frame-validator";
import { FrameFunction } from "../../../../shared/frame/frame_function";
import { FlexSelectComponent } from "../../../../shared/components/flexSelect/FlexSelect.component";

import { DomSanitizer } from  '@angular/platform-browser';
import { RequestOptions } from "@angular/http";
import { HttpClient, HttpHeaders } from "@angular/common/http";
import { FrameVariable } from "../../../../shared/frame/frame-variable";
import { FileUploader, FileItem, ParsedResponseHeaders } from "ng2-file-upload";

declare var webcamInit: any;

@Component({
  selector: "std-hz",
  templateUrl: "./std-hz.component.html",
  styleUrls: ["./std-hz.component.scss"]
})
export class StdHzComponent extends FlexTableComponent implements OnInit {
  rightSelectedItem: any;
  uploadFile: any;
 
  public query = {
    "std_name": "",
    "cert_no": "",
    "ticket_no": "",
    'exam_time_id': "",
  };

  // QUERY_URL = "std/stdRegInfo/pageHz.htm";
  QUERY_URL = "std/stdRegInfo/page.htm";
  BATCH_PAGE_QUERY_URL = "hz/cjJigechengjiOld/page.htm";
  DELETE_URL = "";
  GET_URL = "hz/cjJigechengjiOld/getStdRegInfo.htm";
  BATCH_GET_URL = "hz/cjJigechengjiOld/batchGet.htm";
  ADD_URL = "";
  UPLOAD_URL = "std/stdRegInfo/upload.htm";
  EDIT_URL = "std/stdRegInfo/edit.htm";

  BATCH_UPLOAD_URL = "std/stdRegInfo/uploadImg.htm";

  @ViewChild('uploader')
  uploader: FrameUploaderComponent;

  @ViewChild('batchUploader')
  batchUploader: FrameUploaderComponent;

  @ViewChild('batchFramePager')
  batchFramePager:FramePagerComponent;
  

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

  batchModalWin: any;
  exam_time_info;
  //查询条件
  batchQueryCond = "";
  //按批次查询考生信息列表
  batchItems;
  //按批次选中的考生信息
  batchItem;

  selectedBatchId;
  examAreaOrgArray = [];
  nSocialMajorArray = [];
  socialMajorArray = [];
  socialSchoolArray = [];
  batchUploadPhotoModalWin: any;

  file: Array<Object>;
  loading: boolean;
  batchFormModel: any;

  isSFZ = true;//是否身份证
  
  uploadImageUrl = null;

  uploadImageUrlSource = null;

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

  is_old_std: boolean;
  old_batch_item: any;

  constructor(
    public bsModalService: BsModalService,
    fb: FormBuilder,
    bfb: FormBuilder,
    private sanitizer: DomSanitizer,
  ) {
    super();
    this.file = [];

    this.batchFormModel = bfb.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)])],//手机号
      // learn_form: [null],
      // enrol_place: [null, Validators.compose([Validators.required])],
      political_status: [null, Validators.compose([Validators.required])],
      std_email: [null, Validators.compose([Validators.required,Validators.email])],
      std_family_reg: [null, Validators.compose([Validators.required])],
      // old_ticket_no1: [null],
      std_postcode: [null, 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_edu: [null, Validators.compose([Validators.required])],
      // std_birth_place: [null],
      // old_ticket_no2: [null],
      remark: [null],
      major_id: [null, Validators.compose([Validators.required])],
      school_id: [null, Validators.compose([Validators.required])],
      exam_area_id: [null, Validators.compose([Validators.required])],
    });

    
  }

  ngOnInit() {
   

  }

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

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

    }

  upload(){
    this.uploader.choooseFileAndUpload({}, ((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));
  }
 

  //处理考生类型下拉数据
  transStdSource(resp){
    this.stdSourceArray = [];
    for (const key in resp.config.stdSourceMap) {
      if (resp.config.stdSourceMap.hasOwnProperty(key)) {
        const element = resp.config.stdSourceMap[key];
        this.stdSourceArray.push({value:element[key],text:key});
      }
    }
  }

  //选中右侧考生列表
  chooseBatchItem(item){
    if(this.is_old_std){
      this.old_batch_item = item;
      this.selectedBatchId = item.zhunkaozhenghao;
      return;
    }
    this.initBatchItemData();
    this.selectedBatchId = item.zhunkaozhenghao;
    this.batchItem.std_name = item.xingming;
    this.batchItem.old_ticket_no1 = item.kaohao;
    this.batchItem.old_ticket_no2 = item.jiukaohao;
    this.rightSelectedItem = item;

    FrameRequest.requestMap(this.BATCH_GET_URL,{zhunkaozhenghao:item.zhunkaozhenghao}, async (resp) => {
      // this.transStdSource(resp);
        
        if(resp.std_reg_info){
          if(resp.std_reg_info.photo_url)
            resp.std_reg_info.photo_path_full =  resp.url + resp.std_reg_info.photo_url;
          this.batchItem = resp.std_reg_info;
           //初始化社会考生专业
          if(this.batchItem.std_source == 1){
            this.initSocialMajor();
            //查询主考院校By专业
            this.initSocialSchoolArray(this.batchItem.major_id);

          }
          //非社会考生专业
          else{
            this.initNSocialMajor();
          }
        }
     
      if(this.examAreaOrgArray.length == 0 ){
        this.examAreaOrgArray = resp.examAreaOrgArray;
      }
     
      setTimeout(() => {
        AppComponent.GobalComponent.setLoading(false);
      }, 800);
    });
    
  }
  initBatchItemData(){
    AppComponent.GobalComponent.setLoading(true);
    this.batchItem =  {
      std_name: "",
      std_pass1: "",
      std_pass2: "",
      std_source:"",
      std_eng_name: "",
      cert_no: "",
      std_sex: "",
      political_status: "",
      std_nation: "",
      std_family_reg: "",
      school_id: "",
      std_edu: "",
      std_occupation: "",
      std_healthy: "",
      std_birth: "",
      major_id: "",
      major_code: "",
      major_name: "",
      std_mobile: "",
      std_postcode: "",
      std_address: "",
      email: "",
      remark: "",
      // major_id:"",
      // school_id:"",
      exam_area_id:"",
    };

    //加载 考取数据
    if (this.examAreaOrgArray.length == 0) {
      FrameRequest.requestMap(this.BATCH_GET_URL,{}, async (resp) => {
        this.examAreaOrgArray = resp.examAreaOrgArray;
        setTimeout(() => {
          AppComponent.GobalComponent.setLoading(false);
        }, 300);
      });
    } else {
      setTimeout(() => {
        AppComponent.GobalComponent.setLoading(false);
      }, 300);
    }
    
 
  }
  transStatus(val){
    if(val == null || val == undefined){
      return "待换证";
    }else if(val == 1){
      return "待确定";
    }else if(val == 2){
      return "已换证";
    }
  }

  transStdStatus(val){
    
    if(val == null || val == undefined){
      return "待注册";
    }else if(val == 1){
      return "新注册";
    }else if(val == 2){
      return "个人信息已完善";
    }else if(val == 3){
      return "已上传图片";
    }else if(val == 4){
      return "已完善全部信息";
    }
  }

  batchSearch(param){
    param['exam_time_id'] = this.query.exam_time_id;
    return param;
  }

  //跳转批量处理页面
  async goBatchItem(){
    this.initBatchItemData();
  }

  refreshBatchItems(){
    // AppComponent.GobalComponent.setLoading(true);
    // FrameRequest.requestArray(this.BATCH_QUERY_URL,{exam_time_id:this.query.exam_time_id,query:this.batchQueryCond}, async (array) => {
    //   this.batchItems = array;
    //   setTimeout(() => {
    //     AppComponent.GobalComponent.setLoading(false);
    //   }, 300);
    // });

      // this.batchFramePager.goSearch(null);
      document.getElementById("batchItemsSearchBtn").click();
  }
  
  //考生来源切换
  stdSourceChange(event){
    let val = event.currentTarget.value;
    //社会考生
    if(val == 1){
      this.initSocialMajor();
    }else{
      this.initNSocialMajor();
    }
  }

  initSocialMajor(){
    if(this.socialMajorArray.length > 0) return;
    AppComponent.GobalComponent.setLoading(true);
    FrameRequest.requestArray("//std/stdRegInfo/getSocialMajorList.htm",{}, async (array) => {
      this.socialMajorArray = array; 
      setTimeout(() => {
        AppComponent.GobalComponent.setLoading(false);
      }, 300);
    });
  }

  initNSocialMajor(){
    if(this.nSocialMajorArray.length > 0) return;
    AppComponent.GobalComponent.setLoading(true);
    FrameRequest.requestArray("//std/stdRegInfo/getNSocialMajorList.htm",{}, async (array) => {
      this.nSocialMajorArray = array; 
      setTimeout(() => {
        AppComponent.GobalComponent.setLoading(false);
      }, 300);
    });
  }

  initSocialSchoolArray(major_id){
    AppComponent.GobalComponent.setLoading(true);
    FrameRequest.requestArray("/std/stdRegInfo/getOrgBySocialMajor.htm",{major_id:major_id}, async (array) => {
      this.socialSchoolArray = array; 
      setTimeout(() => {
        AppComponent.GobalComponent.setLoading(false);
      }, 300);
    });
  }

  //社会专业切换
  socialMajorChange(event){
    let val = event.currentTarget.value;
    if(!String(val))return;
    this.initSocialSchoolArray(val);
  }


  batchAdd(){
     //验证必填项
    if(this.batchItem.id != undefined && String(this.batchItem.id)){
      //提示数据已经存在 无法新增
      AppComponent.alert({ 'title': '提示', 'text': "当前数据已经存在无法新增!请重置数据后,完善数据后再提交!" });
      return;
    }
    if (!FrameFunction.validForm(this.batchFormModel)) {
      AppComponent.alert({ 'title': '提示', 'text': "请完善所有输入项后再提交!" });
      return;
    }
    this.batchItem.exam_time_id = this.query.exam_time_id;
    if(!this.batchItem.old_ticket_no1){
      this.batchItem.old_ticket_no1 =this.rightSelectedItem.zhunkaozhenghao;
    }else{
      this.batchItem.old_ticket_no2 =this.rightSelectedItem.zhunkaozhenghao;
    }

    AppComponent.GobalComponent.setLoading(true);
    //保存考生基础信息
    FrameRequest.request("std/stdRegInfo/batchAdd.htm", this.batchItem, (ret) => {
      if (ret.success) {
        // AppComponent.GobalComponent.successMsg('添加数据成功');
        // this.initBatchItemData();
        // //重新加载列表
        // this.refreshBatchItems();
        // setTimeout(() => {
        //   AppComponent.GobalComponent.setLoading(false);
        // }, 100);

          //保存关系数据
          
          FrameRequest.request("hz/cjJigechengjiOld/saveToNew.htm", {
            std_id: ret.entity.id,
            zhunkaozhenghao:this.rightSelectedItem.zhunkaozhenghao,
            xingming:this.rightSelectedItem.xingming,
            kaohao:this.rightSelectedItem.kaohao,
          }, (ret) => {
            if (ret.success) {
               //提示
              AppComponent.GobalComponent.successMsg('添加数据成功');
              this.initBatchItemData();
              //重新加载列表
              this.refreshBatchItems();
              setTimeout(() => {
                AppComponent.GobalComponent.setLoading(false);
              }, 100);
            }else{
              AppComponent.GobalComponent.errorMsg(ret.errorMsg);
              setTimeout(() => {
                AppComponent.GobalComponent.setLoading(false);
              }, 100);
            }
          })
          
         
      }else{
        AppComponent.GobalComponent.errorMsg(ret.errorMsg);
        setTimeout(() => {
          AppComponent.GobalComponent.setLoading(false);
        }, 100);
      }
    });
  }

  batchConfirm(){
    if(this.batchItem.id == undefined || !String(this.batchItem.id)){
      //提示数据已经存在 无法新增
      AppComponent.alert({ 'title': '提示', 'text': "请先保存数据后再提交!" });
      return;
    }
    if(this.is_old_std){
      let old_ticket_no = this.batchItem.zhunkaozhenghao;
      AppComponent.confirm(`确定对现考生[${this.batchItem.std_name}][${this.batchItem.cert_no}]换证,并关联老考生[${this.old_batch_item.xingming}][${this.old_batch_item.zhunkaozhenghao}]的历史成绩`,()=>{
        AppComponent.GobalComponent.setLoading(true);
        FrameRequest.request("std/stdRegInfo/updateOldTicketNo.htm", {std_id:this.batchItem.id,old_ticket_no:old_ticket_no}, (ret) => {
          if (ret.success) {
            AppComponent.GobalComponent.successMsg('换证已经处理完成!');
          }else{
            AppComponent.GobalComponent.errorMsg(ret.errorMsg);
          }
          setTimeout(() => {
            AppComponent.GobalComponent.setLoading(false);
          }, 100);
        });
      })
    }else{
     
    }
  

    // AppComponent.GobalComponent.setLoading(true);
     //保存考生基础信息

     /*
     FrameRequest.request("hz/cjJigechengjiOld/score.htm", {std_id:this.batchItem.id}, (ret) => {
      if (ret.success) {
        if(String(ret.errorCode) != "0" && String(ret.errorCode) ){
          AppComponent.GobalComponent.errorMsg(ret.errorMsg);
        }else{
          AppComponent.GobalComponent.successMsg('换证已经处理完成!');
          this.refreshBatchItems();
        }
        setTimeout(() => {
          AppComponent.GobalComponent.setLoading(false);
        }, 100);
      }else{
        AppComponent.GobalComponent.errorMsg(ret.errorMsg);
        setTimeout(() => {
          AppComponent.GobalComponent.setLoading(false);
        }, 100);
      }
    });
    */


  }
 
   
  goBatchStdHz(templateModal){
    let checkedArray = this.framePager.getCheckedArray();
    //不选 或单选
    if (checkedArray.length > 1) {
      AppComponent.alert({title:"信息提示",text:"对已存在考生账号换证只允许选择单条记录!"});
      return;
    }
     

    this.batchModalWin = this.bsModalService.show(templateModal, { class: "modal-md" });
    if(checkedArray.length == 1){
      this.is_old_std = true;

      // this.batchItem = checkedArray[0];
      FrameRequest.requestMap(this.GET_URL,{id:checkedArray[0].id}, async (map) => {
        map.std.photo_path_full = map.url + map.std.photo_url;
        this.batchItem = map.std;
         // this.chooseBatchItem(checkedArray[0])
        if(this.batchItem.std_source == 1){
          this.initSocialMajor();
          //查询主考院校By专业
          if(this.batchItem.major_id)
            this.initSocialSchoolArray(this.batchItem.major_id);

        }
        //非社会考生专业
        else{
          this.initNSocialMajor();
        }
      })

     
    }else{
      this.is_old_std = false;
      this.batchItem = {};
    }
    
    //请求数据
    // this.refreshBatchItems()
    // this.batchFramePager.goSearch(null);
  }

  
  // 弹出上传图片modal
  batchUploadPic(templateModal){
    if(this.batchItem.id == undefined || !String(this.batchItem.id)){
      //提示数据已经存在 无法新增
      AppComponent.alert({ 'title': '提示', 'text': '考生信息未提交无法上传图片,请提交后再操作!' });
      return;
    }
    this.batchUploadPhotoModalWin = 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);
  }

  //处理上传文件
  handleUploadFile() {
    // let _this = this;
    this.batchFileuploader.onBuildItemForm  = (fileItem: FileItem, form: any) =>{
      form.append("std_id", this.batchItem.id);
    }
    // this.batchFileuploader.onCompleteItem  = (item: FileItem, response: string, status: number, headers: ParsedResponseHeaders) => {
    //   AppComponent.GobalComponent.setLoading(false);
    //   debugger
    // }
    this.batchFileuploader.onSuccessItem  = (item: FileItem, response: string, status: number, headers: ParsedResponseHeaders) =>{
      AppComponent.GobalComponent.successMsg('图片上传成功');
      let respObj = JSON.parse(response);
      // respObj.entity.photo_url = respObj.entity.photo_url + "?" + new Date().getTime();
      let url = respObj.map.url;
      let std = respObj.map.stdRegInfo;
      std.photo_url_full = url + std.photo_url + "?" + new Date().getTime();
      this.batchItem = std;
      this.batchUploadPhotoModalWin.hide();
    }
    // this.batchFileuploader.onErrorItem  = (item: FileItem, response: string, status: number, headers: ParsedResponseHeaders) =>{
    //   debugger
    //   AppComponent.alert({ 'title': '提示', 'text': '图片上传失败!' });
    // }
 
    this.batchFileuploader.queue[0].upload();
  }
 
 
}
