import { Component, OnInit, ViewChild } from "@angular/core";
import { FormBuilder, Validators } from "@angular/forms";
import { CustomValidators } from "ng2-validation";
import { BsModalService } from "ngx-bootstrap/modal";
import { FlexTableComponent } from "../../../../shared/common/FlexTable.component";
import { FrameRequest } from "../../../../shared/frame/frame-request";
import * as _ from 'lodash';
import { FrameValidator } from "../../../../shared/frame/Frame-validator";
import { AppComponent } from "../../../..";
import { FlexSelectComponent } from "../../../../shared/components/flexSelect/FlexSelect.component";
import { FrameUploaderComponent } from '../../../../core/uploader/uploader.component';
@Component({
  selector: "app-std-break-discipline-add",
  templateUrl: "./std-break-discipline.add.component.html",
  styleUrls: ["./std-break-discipline.add.component.scss"]
})
export class StdBreakDisciplineAddComponent extends FlexTableComponent
  implements OnInit {
  public query = {
    std_name: "",
    cert_no: "",
    ticket_no: "",
    agent_id: "",
    exam_time_id:""
  };

  public impParam = {
    exam_time_id: ""
  }

  //TODO
  QUERY_URL = "std/stdBreakDiscipline/page.htm";
  DELETE_URL = "std/stdBreakDiscipline/deleteBatch.htm";
  GET_URL = "std/stdBreakDiscipline/get.htm";
  ADD_URL = "std/stdBreakDiscipline/add.htm";
  EDIT_URL = "std/stdBreakDiscipline/edit.htm";

  UPLOAD_URL = "std/stdBreakDiscipline/upload.htm";

  UPLOAD_FILE_URL = "std/stdBreakDiscipline/uploadFile.htm";
  DOWNLOAD_URL = "std/stdBreakDiscipline/downloadFile.htm";

  agentArray=[]
  examTimeIdArray=[]
  courseList=[]
  std_reg_id = ""
  course_id = ""

  ruleArray = []
  itemArray = []

  filePath : String;

  @ViewChild('uploader')
  uploader: FrameUploaderComponent;
  
  @ViewChild('course_code')
  course_code: FlexSelectComponent

  constructor(public bsModalService: BsModalService, fb: FormBuilder) {
    super();
    // CustomValidators.rangeLength([1, 6])
    this.formModel = fb.group({
      id: [null],
      exam_time_id: [null, Validators.compose([Validators.required])],
      std_name: [null, Validators.compose([Validators.required])],
      cert_no: [null, Validators.compose([Validators.required])],
      ticket_no: [null, Validators.compose([Validators.required,Validators.pattern(FrameValidator.pattern_en_number)])],
      agent_id: [null, Validators.compose([Validators.required])],
      course_code: [null, Validators.compose([Validators.required,Validators.pattern(FrameValidator.pattern_number)])],
      seat_no: [null, Validators.compose([Validators.required,Validators.pattern(FrameValidator.pattern_number)])],
      exam_area: [null],
      break_time: [null],
      stop_starttime: [null],
      stop_endtime: [null],
      audit_status: [null],
      agent_remark: [null],
      prov_agent_remark: [null],
      city_agent_remark: [null],

      item_id:[null, Validators.compose([Validators.required])],
      rule_id:[null, Validators.compose([Validators.required])],
      file_path: [null],
      file_name: [null]

    });

    FrameRequest.requestArray('pl/plExamTime/listtime.htm', {}, (array) => {
      this.examTimeIdArray = array;
    });

    FrameRequest.requestArray('std/stdBreakDisciplineRule/listAll.htm', {}, (array) => {
      this.ruleArray = array;
    });

    FrameRequest.requestArray('std/stdBreakDisciplineItem/listAll.htm', {}, (array) => {
      this.itemArray = array;
    });



  }

  changePoint(){
    if(this.query.exam_time_id){
      FrameRequest.requestArray('kw/kwExamPoint/listExamPointByExamTimeId.htm', {exam_time_id:this.query.exam_time_id}, (array) => {
        this.agentArray = array;
      });
    }
  }

  //导入
  importFunc() {
    if (!this.impParam.exam_time_id) {
      AppComponent.alert({title: "信息提示", text: "选择年度码!"});
      return;
    }
    let param = {
      exam_time_id: this.impParam.exam_time_id, 
      title_rows: 1
    };
    this.uploader.choooseFileAndUpload(param, ((ret) => {
      if (ret.errorCode > 0) {
        AppComponent.alert({title:"信息提示", text: ret.errorMsg});
      }
      else if (ret.errorCode == -1) {
        this.filePath = ret.url;
        this.hideModal();
        //this.editShowType = "scoreDetailList";
        AppComponent.alert({ 'title': '提示', 'text': '有错误数据，请修正后，再上传' });
      } else if (ret.errorCode == 0) {
        this.hideModal();
        this.framePager.reload();
        //this.editShowType = "scoreDetailList";
        AppComponent.alert({title:"信息提示", text:"导入成功!"});
      }
    }));
  }

  downTemplate() {
    FrameRequest.download("std/stdBreakDiscipline/download.htm",{templateName:"高等教育自学考试违规信息.xlsx"});
  }

   //错误数据下载
   downloadErrFile() {
    FrameRequest.download("std/stdBreakDiscipline/downloaderror.htm",  { filePath: this.filePath });
  }

  stdRegInfoModalConfirm(modal){
    let checkedArray = modal.framePager.getCheckedArray();
    if(checkedArray.length > 0){
      let checkedItem = checkedArray[0];
      this.item.std_name = checkedItem.std_name;
      this.item.cert_no = checkedItem.cert_no;
      this.item.ticket_no = checkedItem.ticket_no;
      this.std_reg_id = checkedItem.id+"";
      if(this.item.exam_time_id +""){
        this.examTimeAndStd_coursesChange();
      }
    }
    modal.hideModal();
  }

  //联动已经编排的课程
  examTimeAndStd_coursesChange(){ 
    if((this.item.exam_time_id +"") && (this.std_reg_id+"")){
      FrameRequest.requestArray('std/stdBreakDiscipline/stdCourseList.htm', {exam_time_id:this.item.exam_time_id,std_id:this.std_reg_id}, (array) => {
       
        if(array.length == 0){
          AppComponent.alert({title:"信息提示",text:"该考生无已考课程!,请重新选择"},()=>{});
          return;
        }
        this.courseList = array;
      });
    }
  }

  //联动编排信息
  examTimeAndStdAndcourses_layoutChange(){
    
    if((this.item.exam_time_id +"") && (this.std_reg_id+"") && (this.item.course_code+"")){
      this.courseList.forEach((item) => {
        if(item.course_code == this.item.course_code){
          let course_id = item.id;
          FrameRequest.requestArray('std/stdBreakDiscipline/findStdLayOut.htm', {exam_time_id:this.item.exam_time_id,std_id:this.std_reg_id,course_id:course_id}, (array) => {
            //加载联动信息
            if(array.length > 0){
              let entity = array[0];
              this.item.seat_no = entity.seat_no;
              this.item.agent_id = entity.exam_point_id + "";
              this.item.exam_area = entity.unit_name + "-" + entity.room_code;
              this.item.break_time = entity.exam_times;
              this.item.unit_id=entity.unit_id;
            }
           
          });
        }
     });
    }
  }

  getAgentName(agent_id){
    if(!agent_id) return "";
    if(this.agentArray.length > 0){
      agent_id = parseInt(agent_id);
      let agent = _.find(this.agentArray,{id:agent_id});
      return agent?agent.exam_name:"";
    }else{
      return "";
    }
  }
  async aftGoEditEvent(){
    if(this.item.exam_time_id && this.item.ticket_no){
    FrameRequest.requestArray('std/stdBreakDiscipline/queryStdCourseListByTicketNo.htm', {exam_time_id:this.item.exam_time_id,ticket_no:this.item.ticket_no}, (array) => {
       
      if(array.length == 0){
       
        return;
      }
      this.courseList = array;
    });
   }
  }

  async preSaveEvent(){
    // if(!this.item.start_time){
    //     AppComponent.alert({ title: "信息提示", text: "请选择开始时间!" });
    //     return false;
    // }
    // if(!this.item.end_time){
    //     AppComponent.alert({ title: "信息提示", text: "请选择结束时间!" });
    //     return false;
    // }

    let startTime = new Date(Date.parse(this.item.stop_starttime));
    let endTime = new Date(Date.parse(this.item.stop_endtime));
    if(startTime >= endTime){
        AppComponent.alert({ title: "信息提示", text: "禁止开始时间不能大于等于禁止结束时间!" });
        return false;
    }

    if (this.item.audit_status == 2) {
      AppComponent.alert({ 'title': '提示', text: '该记录已经审核通过,不允许再提交!' });
      return false;
    }

    this.item.audit_status=1;
    return true;
}

  getExamTime(exam_time_id){
    if(!exam_time_id) return "";
    if(this.examTimeIdArray.length > 0){
      exam_time_id = parseInt(exam_time_id);
      let exam_name = _.find(this.examTimeIdArray,{id:exam_time_id});
      return exam_name.exam_year_month || "";
    }else{
      return "";
    }
  }

  deleteOne(item) {
    if (item.audit_status == 2) {
      AppComponent.alert({ 'title': '提示', text: '不允许删除审批通过的记录！' });
      return false;
    }
    AppComponent.confirm("确定删除",()=>{
      FrameRequest.requestMap(this.DELETE_URL, {ids:item.id}, () => {
        AppComponent.GobalComponent.successMsg('数据删除成功');
        this.aftDeleteEvent();
        this.framePager.reload();
      });
    })
  }

  async preDeleteEvent(){
    
    let checkArray = this.framePager.getCheckedArray();
    if (checkArray) {
      for (let i = 0; i < checkArray.length; i++) {
        if(checkArray[i].audit_status == 2) {
          AppComponent.alert({ 'title': '提示', text: '不允许删除审批通过的记录！' });
          return false;
        }
      }
    }
    return true;
   
  }

   //上传申报资料
   uploadFile() {

    if (!this.item.exam_time_id) {
      AppComponent.alert({ 'title': '提示', text: '请选择考试批次' });
      return false;
    }

    let obj = this.item;
    
      //上传文书
      let param = {exam_time_id: this.item.exam_time_id};
      this.uploader.choooseFileAndUpload(param, ((ret) => {
        if (ret.errorCode == 0) {
          obj.file_path = ret.map.file_path;
          obj.file_name = ret.map.file_name;
          AppComponent.GobalComponent.successMsg("上传成功!");
        }else if (ret.errorCode == -1) {
         
          AppComponent.GobalComponent.errorMsg(ret.errorMsg);
        }
      }));
  }

  //下载
  downloadFile(id) {
    FrameRequest.download(this.DOWNLOAD_URL,  { id: id });
  }

}
