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

@Component({
  selector: 'app-by-turn-in-add',
  templateUrl: './by-turn-in-add.component.html',
  styleUrls: ['./by-turn-in-add.component.scss']
})
export class ByTurnInAddComponent  extends FlexTableComponent implements OnInit {

  public query = {
    query: "",
    time: "",
    prov_code: "",
    status:""
  };
  QUERY_URL = "by/byTurnInApply/search.htm";
  FIND_STD_URL = "/std/stdRegInfo/findStd.htm";
  DELETE_URL = "by/byTurnInApply/delete.htm";

  ADD_URL = "by/byTurnInApply/add.htm";
  TIME_URL = "by/byTurnTimeConfig/list.htm?turn_type=3";
  PROVINCE_URL = "by/byTurnInApply/queryProvince.htm";
  
  PROV_URL = "frame/zone/province/list.htm";
  TO_AUDIT_URL = "by/byTurnInApply/toAudit.htm";
  AUDIT_URL = "by/byTurnInApply/audit.htm";
  PRINT_URL = "by/byTurnInApply/print.htm";

  SCHOOL_URL = "cf/cfOrganization/list.htm?org_type=1&status=1";
  CITY_URL = "cf/cfOrganization/list.htm?org_type=2&status=1";
  PRINT_TURN_IN_URL = "by/byTurnInApply/printTurnin.htm";

  scoreList = []; //转考的课程信息
  apply: any; //转考信息
  appr_type: any;
  reject_advice: any;

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

  ngOnInit() {
  }

  showAdd(template: TemplateRef<any>, editShowType) {
    this.scoreList = [];
    this.apply={};

    setTimeout(() => {
      this.editShowType = editShowType;
      this.reject_advice = "";
      this.appr_type = "";
    }, 500);
  }

  showAudit(item,template: TemplateRef<any>, editShowType) {
    if (!this.loadData(item)) return;
    setTimeout(() => {
      this.editShowType = editShowType;
      this.reject_advice = "";
      this.appr_type = "";
    }, 500);
  }

  loadData(item) {
    
    FrameRequest.requestMap(this.TO_AUDIT_URL, { id: item.id }, (map) => {
      this.scoreList = map['scoreList'];
      this.apply= map['apply'];
    });
    return true;
  }

  //审批
  audit() {
    if (!this.check()) return;
    FrameRequest.request(this.AUDIT_URL, {
      isPass: this.appr_type,
      reject_advice: this.reject_advice,
      id: this.apply.id
    }, () => {
      AppComponent.GobalComponent.successMsg("审核成功");
      this.hideModal();
      this.framePager.reload();
    });
  }

  //检查
  check() {
    if (!FrameFunction.validForm(this.formModel)) {
      return;
    }
    if (this.appr_type === undefined) this.appr_type = "";
    if (this.reject_advice === undefined) this.reject_advice = "";
    if (this.appr_type === '') return true;
    if (Number(this.appr_type) === 0 && !this.reject_advice) {
      AppComponent.alert({ title: '提示', text: '请填写驳回意见' });
      return false;
    }
    return true;
  }

  printTurnin() {
    let checkedArray = this.framePager.getCheckedArray((item) => item.id);
    if (checkedArray && (checkedArray.length == 0 || checkedArray.length > 1)) {
      AppComponent.alert({ title: '提示', text: '请选择一条记录' });
      return ;
    }
    FrameRequest.download(this.PRINT_TURN_IN_URL, {id: checkedArray.join()}, () => {
      AppComponent.GobalComponent.successMsg("转入登记表生成成功");
    });
  }

  //根据准考证查询考生信息
  findStdInfo(ticket_no: any) {
    FrameRequest.requestEntity(this.FIND_STD_URL, {ticket_no: ticket_no}, (entity) => {
      if(entity) {
       
        this.apply.std_photo_url =  entity.photo_url;
        this.apply.std_reg_id = entity.id;
        
      } else {
        this.apply.zk_in_zkz = "";
        AppComponent.alert({ title: "信息提示", text: "转入准考证【"+ticket_no+"】在广西自考系统不存在!" });
        return ;
      }
    });
  }

  findCourse(i,course_code) {
    FrameRequest.requestEntity("pl/plCourse/findByCourse.htm", {course_code: course_code}, (entity) => {
      if(entity) {
        for(let j=0;j<this.scoreList.length;j++) {
          if(i == j) {
            this.scoreList[j].kc_mc = entity.course_name;
            if(entity.course_score){
              this.scoreList[j].kc_xf = parseInt(entity.course_score) ;
            }
            
           
            break;
          }
        }
        
        
      } else {
        for(let j=0;j<this.scoreList.length;j++) {
          if(i == j) {
            this.scoreList[j].kc_dm = "";
            this.scoreList[j].kc_mc = "";
            this.scoreList[j].kc_xf = "";
            break;
          }
        }
        
        AppComponent.alert({ title: "信息提示", text: "课程代码【"+course_code+"】在广西自考系统不存在!" });
        return ;
      }
    });
  }

  addScore() {
    if(!this.apply.ks_zkz){
      AppComponent.alert({ title: "信息提示", text: "请先填写转出准考证号。" });
      return ;
    }
    this.scoreList.push(
      {
        "ks_zkz": this.apply.ks_zkz,
        "kc_dm":  "",
        "kc_mc": "",
        "bk_cj": "",
        "kc_xf": "",
        "hg_yydm": "",
        "hg_sj": "",
        "et_dm": ""
      }
    );
  }

  removeScore(i? :any) {
    AppComponent.confirm("确定删除该行成绩吗",()=>{
      let tempArr = [];
    for(let j=0;j<this.scoreList.length;j++) {
      if(i !== j) {
        tempArr.push(this.scoreList[j]);
      }
    }
    this.scoreList = tempArr;
    });
  }

  checkDate(dateStr){
    var a = /^(\d{4})-(\d{2})-(\d{2})$/
    if (!a.test(dateStr)) {
        return false
    }else{
        return true;
    }
  }

  //外省转入申请
  applyTurnin() {
    if (!this.scoreList || this.scoreList.length == 0) {
      AppComponent.alert({ title: '提示', text: '请填写转入成绩。' });
      return false;
    }

    if(!this.apply.ks_birthday){
      this.apply.ks_birthday = "";
    }

    if(!this.apply.zk_out_sj){
      this.apply.zk_out_sj = "";
    }

    if(!this.apply.std_photo_url){
      this.apply.std_photo_url = "";
    }

    if(!this.apply.ks_sfz){
      this.apply.ks_sfz = "";
    }

    for(let j=0;j<this.scoreList.length;j++) {
      if(this.scoreList[j]) {
        if (!this.scoreList[j].ks_zkz) {
          AppComponent.alert({ title: '提示', text: '请填写准考证号。' });
          return false;
        }

        if (!this.scoreList[j].kc_dm) {
          AppComponent.alert({ title: '提示', text: '请填写课程代码。' });
          return false;
        }

        if (!this.scoreList[j].kc_mc) {
          AppComponent.alert({ title: '提示', text: '请填写课程名称。' });
          return false;
        }

        if (!this.scoreList[j].bk_cj) {
          AppComponent.alert({ title: '提示', text: '请填写成绩。' });
          return false;
        }

        if (!this.scoreList[j].kc_xf) {
          AppComponent.alert({ title: '提示', text: '请填写学分。' });
          return false;
        }

        if (!this.scoreList[j].hg_yydm) {
          AppComponent.alert({ title: '提示', text: '请填写合格原因。' });
          return false;
        }

        if (!this.scoreList[j].hg_sj) {
          AppComponent.alert({ title: '提示', text: '请填写合格时间。' });
          return false;
        }else{
          if(!this.checkDate(this.scoreList[j].hg_sj)){
            
            AppComponent.alert({ title: '提示', text: '请填写正确的合格时间，如2019-01-01。' });
            return false;
        }

        }

        if (!this.scoreList[j].et_dm) {
          AppComponent.alert({ title: '提示', text: '请填写考次号。' });
          return false;
        }
      }
    }

    AppComponent.confirm("确定提交外省转入申请吗",()=>{
      AppComponent.GobalComponent.setLoading(true);
      FrameRequest.requestEntity(this.ADD_URL, this.apply, (entity)=>{
        
         // 更新转入成绩
          FrameRequest.request("by/byTurnInAppl/updateScore.htm", {
            ks_zkz : this.apply.ks_zkz,
            time_config_id : this.apply.time_config_id,
            ks_sfz :this.apply.ks_sfz,
            kc_dm : this.scoreList.map(item => item.kc_dm),
            kc_mc : this.scoreList.map(item => item.kc_mc),
            bk_cj : this.scoreList.map(item => item.bk_cj),
            kc_xf : this.scoreList.map(item => item.kc_xf),
            hg_yydm : this.scoreList.map(item => item.hg_yydm),
            hg_sj : this.scoreList.map(item => item.hg_sj),
            et_dm : this.scoreList.map(item => item.et_dm)
          }, () => {
           
            AppComponent.GobalComponent.setLoading(false);
            AppComponent.GobalComponent.successMsg('外省转入申请成功!');
            this.hideModal();
          });
        
      }, function (error) {
        AppComponent.GobalComponent.setLoading(false);
       
        
      }
    );
    });

  }

  //更新转入成绩
  updateScore() {
    
    // AppComponent.GobalComponent.setLoading(true);
    FrameRequest.request("by/byTurnInAppl/updateScore.htm", {
      ks_zkz : this.apply.ks_zkz,
      time_config_id : this.apply.time_config_id,
      ks_sfz :this.apply.ks_sfz,
      kc_dm : this.scoreList.map(item => item.kc_dm),
      kc_mc : this.scoreList.map(item => item.kc_mc),
      bk_cj : this.scoreList.map(item => item.bk_cj),
      kc_xf : this.scoreList.map(item => item.kc_xf),
      hg_yydm : this.scoreList.map(item => item.hg_yydm),
      hg_sj : this.scoreList.map(item => item.hg_sj),
      et_dm : this.scoreList.map(item => item.et_dm)
    }, () => {
      // AppComponent.GobalComponent.setLoading(false);
      AppComponent.GobalComponent.successMsg("修改成功!");
      this.hideModal();
    });
  }


  deleteApply(item){
    if (item.status == 5||item.status == 4) {
      AppComponent.alert({title:"信息提示",text:"不允许删除审核通过或已归档的申请单!"});
      return;
    }

    AppComponent.confirm("确定删除吗?",()=>{
      FrameRequest.requestMap(this.DELETE_URL, {ids:item.id}, () => {
        AppComponent.GobalComponent.successMsg('删除成功!');
         this.framePager.reload();
      });
  });

    
  }

}
