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 { FlexOptrComponent } from "../../flexOptr/flexOptr.component";
import { FlexSelectComponent } from "../../../../shared/components/flexSelect/FlexSelect.component";

@Component({
  selector: "app-std-break-discipline-audit",
  templateUrl: "./std-break-discipline.audit.component.html",
  styleUrls: ["./std-break-discipline.audit.component.scss"]
})
export class StdBreakDisciplineAuditComponent extends FlexTableComponent
  implements OnInit {
  public query = {
    std_name: "",
    cert_no: "",
    ticket_no: "",
    agent_id: "",
    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";

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

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

  ruleArray = []
  itemArray = []

  @ViewChild('exam_time_id')
  exam_time_id: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],
      cert_no: [null],
      ticket_no: [null],
      agent_id: [null],
      course_code: [null],
      seat_no: [null],
      exam_area: [null],
      break_time: [null],
      stop_starttime: [null],
      stop_endtime: [null],
      audit_status: [null],
      agent_remark: [null],
      city_agent_remark: [null],
      prov_agent_remark: [null,Validators.compose([Validators.required])],
      item_id:[null, Validators.compose([Validators.required])],
      rule_id:[null, Validators.compose([Validators.required])]
    });

   

    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.requestArray('cf/cfOrganization/list.htm', {org_type: 4}, (array) => {
      this.agentArray = 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;
     // });

     FrameRequest.requestArray('cf/cfOrganization/list.htm', {org_type: 4}, (array) => {
      this.agentArray = array;
    });

    }
  }

  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(this.agentArray.length > 0){
      agent_id = parseInt(agent_id);
      let agent = _.find(this.agentArray,{id:agent_id});
      return agent?agent.exam_name:"";
    }else{
      return "";
    }
  }

  //批量审批通过
  batchAudit(){
    
    let exam_time_id = this.query.exam_time_id;
    if(null != exam_time_id && "" != exam_time_id){
      this.exam_time_id.items.forEach((item) => {
         if(item.id == exam_time_id){
          let paramObj = {exam_time_id:this.query.exam_time_id};
          let agent_nameInfo = "";
          if(String(this.query.agent_id)){
            paramObj['org_id'] = this.query.agent_id;
            let agent = this.agentArray.find((value, index, arr) => {
              return arr[index].id == this.query.agent_id;
            });
            
            agent_nameInfo = `[${agent.exam_name}]`;
          }
          AppComponent.confirm(`确定批量审批通过[${item.exam_year_month}] ${agent_nameInfo}?`,()=>{
            FrameRequest.request('std/stdBreakDiscipline/batchAudit.htm', paramObj, (ret)=>{
              if (ret.errorCode == 0) {
                this.framePager.reload();
                AppComponent.GobalComponent.successMsg("批量审批成功");
              }
            });
          });
         }
      });
    
    }else{
      AppComponent.alert({text:"请选择考试批次!"});
    }
    
     
  }

   //批量审批退回
   batchBack(){
    let exam_time_id = this.query.exam_time_id;
    if(null != exam_time_id && "" != exam_time_id){
      this.exam_time_id.items.forEach((item) => {
         if(item.id == exam_time_id){
          let paramObj = {exam_time_id:this.query.exam_time_id};
          let agent_nameInfo = "";
          if(String(this.query.agent_id)){
            paramObj['org_id'] = this.query.agent_id;
            let agent = this.agentArray.find((value, index, arr) => {
              return arr[index].id == this.query.agent_id;
            });
            
            agent_nameInfo = `[${agent.exam_name}]`;
          }
          AppComponent.confirm(`确定批量审批退回[${item.exam_year_month}] ${agent_nameInfo}?`,()=>{
            FrameRequest.request('std/stdBreakDiscipline/batchBack.htm', paramObj, (ret)=>{
              if (ret.errorCode == 0) {
                this.framePager.reload();
                AppComponent.GobalComponent.successMsg("批量审批退回成功");
              }
            });
          });
         }
      });
    
    }else{
      AppComponent.alert({text:"请选择考试批次!"});
    }
  }

  //批量审批拒绝
  batchRefuse(){
    
    let exam_time_id = this.query.exam_time_id;
    if(null != exam_time_id && "" != exam_time_id){
      this.exam_time_id.items.forEach((item) => {
         if(item.id == exam_time_id){
          let paramObj = {exam_time_id:this.query.exam_time_id};
          let agent_nameInfo = "";
         
          if(String(this.query.agent_id)){
            paramObj['org_id'] = this.query.agent_id;
            let agent = this.agentArray.find((value, index, arr) => {
              return arr[index].id == this.query.agent_id;
            });
            
            agent_nameInfo = `[${agent.exam_name}]`;
          }
          AppComponent.confirm(`确定批量审批拒绝[${item.exam_year_month}] ${agent_nameInfo}?`,()=>{
            FrameRequest.request('std/stdBreakDiscipline/batchReFuse.htm', paramObj, (ret)=>{
              if (ret.errorCode == 0) {
                this.framePager.reload();
                AppComponent.GobalComponent.successMsg("批量审批拒绝成功");
              }
            });
          });
         }
      });
    
    }else{
      AppComponent.alert({text:"请选择考试批次!"});
    }
  }

  goBack(audit_status){

    if(audit_status == 1){
      this.item.audit_status = 3;
      this.save();
    }else{
      AppComponent.alert({text:"状态不是审核中，不允许审核!"});
    }
    
  }

  finish(audit_status){
    if(audit_status == 1){
      this.item.audit_status = 2;
      this.save();
    }else{
      AppComponent.alert({text:"状态不是审核中，不允许审核!"});
    }
    
  }

  refuse(audit_status){
    if(audit_status == 1){
      this.item.audit_status = 3;
      this.save();
    }else{
      AppComponent.alert({text:"状态不是审核中，不允许审核!"});
    }
  }


  //一键处理违纪
  dealDiscipline(){
   
    let exam_time_id = this.query.exam_time_id;
    if(null != exam_time_id && "" != exam_time_id){
      AppComponent.confirm('请确保违纪数据已经完成审批，确认一键处理违纪吗？（取消单科成绩和取消当次所有科成绩）',()=>{
        FrameRequest.request('std/stdBreakDiscipline/dealDiscipline.htm', {exam_time_id:exam_time_id}, (ret)=>{
          if (ret.errorCode == 0) {
            AppComponent.GobalComponent.successMsg("一键处理违纪成功");
          }else{
            AppComponent.GobalComponent.errorMsg(ret.errorMsg);
          }
        });
      });
    
    }else{
      AppComponent.alert({text:"请选择考试批次!"});
    }
    
     
  }

  //统一门户违纪同步
  synDiscipline(){
   
    let exam_time_id = this.query.exam_time_id;
    if(null != exam_time_id && "" != exam_time_id){
      AppComponent.confirm('请确保统一门户违纪数据已经同步自考前置库，确认将违纪数据从自考前置库同步到自考违纪表吗？',()=>{
        FrameRequest.request('std/stdBreakDiscipline/synDiscipline.htm', {exam_time_id:exam_time_id}, (ret)=>{
          if (ret.errorCode == 0) {
            AppComponent.GobalComponent.successMsg("统一门户违纪数据同步成功");
          }else{
            AppComponent.GobalComponent.errorMsg(ret.errorMsg);
          }
        });
      });
    
    }else{
      AppComponent.alert({text:"请选择考试批次!"});
    }
    
     
  }

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

}
