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-provinceadd",
  templateUrl: "./std-break-discipline.provinceadd.component.html",
  styleUrls: ["./std-break-discipline.provinceadd.component.scss"]
})
export class StdBreakDisciplineProvinceAddComponent extends FlexTableComponent
  implements OnInit {

  bsModalWin2 = null;
  curr_item = null;

  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/deleteForprovince.htm";
  GET_URL = "std/stdBreakDiscipline/get.htm";
  ADD_URL = "std/stdBreakDiscipline/provinceadd.htm";
  EDIT_URL = "std/stdBreakDiscipline/provinceedit.htm";

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

  UPLOAD_FILE_URL = "std/stdBlackList/upload.htm";

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


  

  agentArray=[]
  item_agentArray=[]

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

  ruleArray = []
  itemArray = []
  fileNoticeList = []
  fileDecisionList = []


  filePath : String;

  @ViewChild('uploader')
  uploader: FrameUploaderComponent;
  @ViewChild('uploaderFile')
  uploaderFile: 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,Validators.pattern(FrameValidator.pattern_en_number)])],
      ticket_no: [null, Validators.compose([Validators.required,Validators.pattern(FrameValidator.pattern_en_number)])],
      agent_id: [null],
      course_code: [null],
      seat_no: [null],
      exam_area: [null],
      break_time: [null],
      stop_starttime: [null],
      stop_endtime: [null],
      // audit_status: [null, Validators.compose([Validators.required])],
      agent_remark: [null],
      prov_agent_remark: [null],
      city_agent_remark: [null],

      item_id:[null],
      rule_id:[null],
      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;
    });

    FrameRequest.request('pl/plExamTime/getCurrentExamTimeId.htm',{}, (resp) => {
        if(resp.entity){
          this.query.exam_time_id = resp.entity.id;
          this.exam_time_id = resp.entity.id;
          this.framePager.reload();
        }
        
      }
    );

  }

  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.exam_area = entity.unit_name + "-" + entity.room_code;
              this.item.break_time = entity.exam_times;
              this.item.unit_id=entity.unit_id;

              if(this.item.exam_time_id){
                FrameRequest.requestArray('kw/kwExamPoint/listExamPointByExamTimeId.htm', {exam_time_id:this.item.exam_time_id}, (array) => {
                 
                  this.item_agentArray = array;
                  this.item.agent_id = entity.exam_point_id + "";
                });
              }else{
                this.item.agent_id = entity.exam_point_id + "";
              }

              

            }
           
          });
        }
     });
    }
  }

  //违规事实连动默认违规处理结果
  changeItem(){
    let item_id = this.item.item_id;
    if(item_id){
      if(this.itemArray.length > 0){
        item_id = parseInt(item_id);
        let item_obj = _.find(this.itemArray,{id:item_id});
        if(item_obj && item_obj.rule_id){
          this.item.rule_id = item_obj.rule_id;
          return;
        }else{
          this.item.rule_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 "";
    }
  }

  getItemName(item_id){
    if(!item_id) return "";
    if(this.itemArray.length > 0){
      item_id = parseInt(item_id);
      let item_obj = _.find(this.itemArray,{id:item_id});
      
      return item_obj?(item_obj.item_code+'-'+item_obj.item_content):"";
    }else{
      return "";
    }
  }

  getRuleName(rule_id){
    if(!rule_id) return "";
    if(this.itemArray.length > 0){
      rule_id = parseInt(rule_id);
      let rule_obj = _.find(this.ruleArray,{id:rule_id});
      
      return rule_obj?(rule_obj.code+'-'+rule_obj.name+'('+rule_obj.remark+')'):"";
    }else{
      return "";
    }
  }

  async aftGoEditEvent(){
    // 修改
    if(this.item && 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;

      if(this.item.exam_time_id){
        FrameRequest.requestArray('kw/kwExamPoint/listExamPointByExamTimeId.htm', {exam_time_id:this.item.exam_time_id}, (array) => {
          
          this.item_agentArray = array;
        });
      }
    });
   }else{
     //新增
     if(!this.item.exam_time_id){
      this.item.exam_time_id = this.exam_time_id;
    }
   }


  }

  async preSaveEvent(){
    
    if(this.item.stop_starttime && this.item.stop_endtime){
      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.stop_starttime || !this.item.stop_endtime){
      if(this.item.rule_id == 3 ||this.item.rule_id == 4 ||this.item.rule_id == 5 ||this.item.rule_id == 6 ||this.item.rule_id == 7 ||this.item.rule_id == 8){
        AppComponent.alert({ title: "信息提示", text: "违规处理结果包含停考或延期时，请填写时间!" });
        return false;
      }
    }

    if(!this.item.course_code){
      AppComponent.alert({ 'title': '提示', 'text': "请选择考试科目!" });
      return false;
    }

    if(!this.item.item_id){
      AppComponent.alert({ 'title': '提示', 'text': "请选择违规事实!" });
      return false;
    }

    if(!this.item.rule_id){
      AppComponent.alert({ 'title': '提示', 'text': "请选择违规处理结果!" });
      return false;
    }
   

    this.item.audit_status=2;
    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) {
    
    AppComponent.confirm("确定删除",()=>{
      FrameRequest.requestMap(this.DELETE_URL, {ids:item.id}, () => {
        AppComponent.GobalComponent.successMsg('数据删除成功');
        this.aftDeleteEvent();
        this.framePager.reload();
      });
    })
  }

  async preDeleteEvent(){
    
    return true;
   
  }

  exportExcel() {
    if(!this.query.exam_time_id){
      AppComponent.alert({title:"信息提示",text:"请选择考试时间"},()=>{});
      return;
    }

    let param = {
      exam_time_id:this.query.exam_time_id
    };
    AppComponent.GobalComponent.setLoading(true);
    FrameRequest.download("std/stdBreakDiscipline/exportExcel.htm", param, ()=>{
      AppComponent.GobalComponent.setLoading(false);
      AppComponent.GobalComponent.successMsg("违规数据下载成功!");
    });
  }

    exportNotice() {
      if(!this.query.exam_time_id){
        AppComponent.alert({title:"信息提示",text:"请选择考试时间"},()=>{});
        return;
      }
  
      let param = {
        exam_time_id:this.query.exam_time_id
      };
      //下载
      AppComponent.GobalComponent.setLoading(true);
      FrameRequest.download("std/stdBreakDiscipline/exportNotice.htm", param, () => {
        AppComponent.GobalComponent.setLoading(false);
        AppComponent.GobalComponent.successMsg("违规处理告知书下载成功");
      });
  
     
    }

    exportDecision() {
      if(!this.query.exam_time_id){
        AppComponent.alert({title:"信息提示",text:"请选择考试时间"},()=>{});
        return;
      }
  
      let param = {
        exam_time_id:this.query.exam_time_id
      };
      //下载
      AppComponent.GobalComponent.setLoading(true);
      FrameRequest.download("std/stdBreakDiscipline/exportDecision.htm", param, () => {
        AppComponent.GobalComponent.setLoading(false);
        AppComponent.GobalComponent.successMsg("违规处理决定书下载成功");
      });
  
     
    }

    goQueryUploadFileForNotice(editFormTemplateModal, item,file_type) {
      this.curr_item = item;
      FrameRequest.requestArray("std/stdBlackList/queryStdBreakDisciplineFile.htm", {ticket_no:item.ticket_no,exam_time_id:item.exam_time_id,file_type:file_type}, (arrary) => {
        this.fileNoticeList = arrary;
    });

    let css = "modal-lg";
    this.bsModalWin = this.bsModalService.show(editFormTemplateModal, { class: css });
  }

  checkUploadFile(item,file_type) {
    
    FrameRequest.download("std/stdBlackList/download.htm", {ticket_no:item.ticket_no,exam_time_id:item.exam_time_id,file_type:file_type});


  }

  goUploadFile(editFormTemplateModal, modalcss?) {
    

    let css = modalcss ? modalcss : "modal-lg";
    this.bsModalWin2 = this.bsModalService.show(editFormTemplateModal, { class: css });
  }

  uploadFile(file_type) {
    this.curr_item.file_type = file_type;
    this.uploaderFile.choooseFileAndUpload(this.curr_item, ((ajax) => {
      
      if(ajax.success){
        AppComponent.GobalComponent.successMsg('上传成功');
        this.bsModalWin2.hide();
        FrameRequest.requestArray("std/stdBlackList/queryStdBreakDisciplineFile.htm", {ticket_no:this.curr_item.ticket_no,exam_time_id:this.curr_item.exam_time_id,file_type:file_type}, (arrary) => {
          this.fileNoticeList = arrary;
          
        });
         
      }else{
        AppComponent.GobalComponent.errorMsg(ajax.errorMsg);
        this.bsModalWin2.hide();
      }
     
    }).bind(this));
  }

  deleteFile(item,file_type) {

    
    AppComponent.confirm("确定删除吗？", () => {
     
      FrameRequest.request("std/stdBlackList/deleteFile.htm", {ticket_no:item.ticket_no,exam_time_id:item.exam_time_id,file_type:file_type}, () => {
        AppComponent.GobalComponent.successMsg("删除成功");
        FrameRequest.requestArray("std/stdBlackList/queryStdBreakDisciplineFile.htm", {ticket_no:item.ticket_no,exam_time_id:item.exam_time_id,file_type:file_type}, (arrary) => {
          this.fileNoticeList = arrary;
        });
  
      });
    });
  }

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

}
