import { Component, OnInit, TemplateRef, ViewChild } from "@angular/core";
import { FormBuilder, Validators, FormGroup} from '@angular/forms';
import { CustomValidators } from 'ng2-validation';
import { BsModalService } from "ngx-bootstrap/modal";
import { FlexTableComponent } from "../../../../../shared/common/FlexTable.component";
import { AppComponent } from "../../../../../app.component";
import {FrameUploaderComponent} from '../../../../../core/uploader/uploader.component';
import { FrameRequest } from "../../../../../shared/frame/frame-request";
import { FramePagerComponent } from "../../../../../core/pager/pager.component";
import { FrameFunction } from "../../../../../shared/frame/frame_function";
import { ThemesService } from "../../../../../core/themes/themes.service";

@Component({
  selector: "app-pl-paperaudit",
  templateUrl: "./paper-audit.component.html",
  styleUrls: ["./paper-audit.component.scss"]
})
export class PaperAuditComponent extends FlexTableComponent implements OnInit {

  @ViewChild('uploader')
  uploader: FrameUploaderComponent;
  @ViewChild('framePager')
  framePager:FramePagerComponent;
  @ViewChild('oldCjPager')
  oldCjPager:FramePagerComponent;
  @ViewChild('ticketAssoPager')
  ticketAssoPager:FramePagerComponent;

  courseList=[];
  //TODO
  QUERY_URL = "by/byPaperApply/page.htm";
  DELETE_URL = "by/byPaperApply/delete.htm";
  GET_URL = "by/byPaperApply/get.htm";
  ADD_URL = "by/byPaperApply/add.htm";
  EDIT_URL = "by/byPaperApply/edit.htm";

  AUTH_DETAIL_URL = "by/byPaperApply/getdetail.htm";
  AUTH_LIST_URL = "by/byPaperApply/viewauth.htm";//审核记录
  UPLOAD_URL = "pl/byPaperApply/upload.htm";

  

  orgList = [];
  authList = [];

  filePath : String;
  radioSelect : any;
  
  majorList = [];
  masterSchoolList = [];
  majorLevel = "";
  org_id = null;
  org_code = null;
  examTimeId = null;
  status = null;

  stdRefWin: any;

  scoreList = [];

  constructor(
    public bsModalService: BsModalService,
    fb: FormBuilder
  ) {
    super();
    this.formModel = fb.group({
      id: [null],
      'std_name' : [null],
      'cert_no': [null],
      'ticket_no': [null],
      'std_sex': [null],
      'nation': [null],
      'std_birth': [null],
      'native_prov': [null],
      'native_city': [null],
      'political': [null],
      'pre_edu': [null],
      'work_unit': [null],
      'telephone': [null],
      'address': [null],
      'post_code': [null],
      'radioSelect' : [null, Validators.compose([Validators.required])],
      'remark' : [null],
      'auth_remark' : [null, Validators.compose([Validators.required])]
      
    });
    
  }

  ngOnInit() {
    FrameRequest.requestMap("by/byPaperApply/initdata.htm", {}, async (map)=>{
      this.majorList  = map.majorList;//专业
      this.orgList = map.cityOrgList;//市考办
      this.masterSchoolList = map.schoolOrgList;//主考学校
      this.query.examTimeId = map.examTimeId;
      this.examTimeId = map.examTimeId;
      this.org_id = map.org_id;
      this.org_code = map.org_code;

      if(null != map.org_id){
        this.query.masterSchoolId = map.org_id;
      }

      if(null != map.status){
        this.query.status = map.status;
        this.status = map.status;
      }

      this.framePager.reload();

    });
  }

  public query = {
    query: "",
    cityOrgId: "",
    masterSchoolId: "",
    examTimeId: "",
    majorId: "",
    status: "",
    is_firstauth_pass:""
  };

  
  public stdRefQuery = {
    certNo: "",
    ticketNo: "",
    majorId: "", //待毕业专业
    masterSchoolId: ""
  }

  search(param) {
    param.query = this.query.query;
   
    if (!this.query.majorId) {
      this.query.majorId = "";
    }
    if (!this.query.masterSchoolId) {
      this.query.masterSchoolId = "";
    }
    if (!this.query.examTimeId) {
      this.query.examTimeId = "";
    }
    if (!this.query.status) {
      this.query.status="";
    }
    
    param.major_id = this.query.majorId;
    param.school_id = this.query.masterSchoolId;
    param.exam_time_id = this.query.examTimeId;
    param.by_status = this.query.status;

  }


  //打印毕业论文答辩
  printPaper() {
    let checkedArray = this.framePager.getCheckedArray();;
    if(checkedArray.length != 1){
      //按查询条件生成
      AppComponent.alert({ 'title': '提示', 'text': "请选择一条记录!" });
      return;
    }
    AppComponent.GobalComponent.setLoading(true);
    FrameRequest.download("kj/kjCollegeScoreDetail/export.htm", {ticket_no: checkedArray[0].ticket_no,apply_id: checkedArray[0].id}, () => {
      AppComponent.GobalComponent.setLoading(false);
      AppComponent.GobalComponent.successMsg("导出成功");
    });
  }



  //弹出审核框
  showEditWin(obj) {
    if (!obj) {
      let checkedArray = this.framePager.getCheckedArray();
      if (checkedArray.length == 0) {
        AppComponent.alert({title:"信息提示",text:"请选择待审批记录!"});
        return;
      }
     
      obj = checkedArray[0];
    } 

    // 主考学校审核
    if(this.org_code != '999'){
      // 主考学校，只能审核状态是待主考学校审核的记录
      if(obj.status != '1'){
        AppComponent.alert({title:"信息提示",text:"申请单状态不是待主考学校审核,不允许审核!"});
        return;
      }

      // 申请单对应的主考学校与当前账号不一致
      if(obj.school_id != this.org_id){
        AppComponent.alert({title:"信息提示",text:"申请单对应的主考学校不是当前账号主考学校,不允许审核!"});
        return;
      }

    }

    // 考试院审核
    if(this.org_code == '999'){
      if(obj.status != '1' && obj.status != '2'){
        AppComponent.alert({title:"信息提示",text:"只能审批待审批记录!"});
        return;
      }
      
    }

    this.editShowType="only";
    FrameRequest.requestMap(this.AUTH_DETAIL_URL, {id: obj.id}, (map) => {
      this.item = map.detail;
      this.authList = map.authList;
      this.majorLevel = map.majorLevel;
      this.radioSelect = null;
      this.scoreList = map.scoreMap;
     
    });
  }

  resetByScore(){

    AppComponent.confirm("确定重新下载考生毕业成绩吗?",()=>{
      let param = {
        paper_apply_id: this.item.id  
      };
      
      AppComponent.GobalComponent.setLoading(true);
      FrameRequest.requestEntity("by/byPaperApply/resetPaperScore.htm", param, async () => {
        AppComponent.GobalComponent.setLoading(false);
        AppComponent.GobalComponent.successMsg('毕业成绩重新下载成功!');
        
        //刷新成绩显示
        FrameRequest.requestArray("by/byPaperApply/queryPaperScore.htm", {paper_apply_id: this.item.id}, (arrary) => {
          this.scoreList = arrary;
        });
      });
   });
  }


  //审核
  doAudit() {
    if (!FrameFunction.validForm(this.formModel)) {
      return;
    }
    this.item.auth_type = this.radioSelect;
    if (this.item.auth_type == 0) {//主考学校审核通过
      this.item.status = '2';
      this.item.is_auth_back = 0;
    } else if (this.item.auth_type == 1) {//主考学校审核驳回
      this.item.status = '0';
      this.item.is_auth_back = 1;//标识驳回
    } else if (this.item.auth_type == 2) {//考试院审核通过
      this.item.status = '3';
    } else if (this.item.auth_type == 3) {//考试院审核不通过
      this.item.status = '4';
    }
   
    AppComponent.GobalComponent.setLoading(true);
    FrameRequest.request("by/byPaperApply/audit.htm", this.item, (ret)=>{
      AppComponent.GobalComponent.setLoading(false);
      this.hideModal();
      this.framePager.reload();

      if (ret.errorCode == 1) {
        AppComponent.GobalComponent.successMsg("审核成功!");
      }else{
        AppComponent.GobalComponent.errorMsg(ret.errorMsg);
      }     

    });
  }

  
  callBackApply() {
    let checkedArray = this.framePager.getCheckedArray();
      if (checkedArray.length == 0 || checkedArray.length>1) {
        AppComponent.alert({title:"信息提示",text:"请选择一条记录!"});
        return;
      }

      // 主考学校撤回
      if(this.org_code != '999'){
          if (checkedArray[0].status != '2') {
            AppComponent.alert({title:"信息提示",text:"只能撤回状态是待考试院审核的记录!"});
            return;
          }

            // 申请单对应的主考学校与当前账号不一致
          if(checkedArray[0].school_id != this.org_id){
            AppComponent.alert({title:"信息提示",text:"申请单对应的主考学校不是当前账号主考学校,不允许撤回!"});
            return;
          }
      }

      // 考试院撤回
      if(this.org_code == '999'){
          if (checkedArray[0].status != '2' && checkedArray[0].status != '3' && checkedArray[0].status != '4') {
            AppComponent.alert({title:"信息提示",text:"申请单的状态不是待考试院审核、审核通过、审核不通过，不允许撤回!"});
            return;
        }
     }
    
    AppComponent.confirm("确定撤回申请单吗?",()=>{

    AppComponent.GobalComponent.setLoading(true);
    FrameRequest.request("by/byPaperApply/callBack.htm", {id: checkedArray[0].id}, (ret)=>{
      AppComponent.GobalComponent.setLoading(false);
      this.hideModal();
      this.framePager.reload();
      if (ret.errorCode == 1) {
       
        AppComponent.GobalComponent.successMsg("撤回成功!");
      }else{
        
        AppComponent.GobalComponent.errorMsg(ret.errorMsg);
      }
    });
  });
  }





  //上传毕业照片
  uploadByPhoto(applyId) {
    let param = {
      byApplyId: applyId,
      RequestLoading: true
    };
    this.uploader.choooseFileAndUpload(param, ((ret) => {
      if (ret.errorCode > 0) {
        AppComponent.alert({title:"信息提示", text: ret.errorMsg});
      } else if (ret.errorCode == -1) {
        AppComponent.GobalComponent.successMsg("上传失败!");
      } else if (ret.errorCode == 0) {
        AppComponent.GobalComponent.successMsg("上传成功!");
        this.item.by_photo = ret.map.file_path;
        this.item.by_photo_path = ret.map.by_photo_path;
      }
    }));
  }


  //删除毕业申请验证----只能删除0、1状态的
  deleteApply(item){
    
    if (item.status > 1) {
      AppComponent.alert({title:"信息提示",text:"只能删除新建、待主考学校审核状态的申请!"});
      return;
    }

    if(this.org_code != '999'){
        // 申请单对应的主考学校与当前账号不一致
        if(item.school_id != this.org_id){
          AppComponent.alert({title:"信息提示",text:"申请单对应的主考学校不是当前账号主考学校,不允许删除!"});
          return;
        }
    }

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

    
  }

  //******************************************新建毕业申请*********************************************** */
  stdRefList = [];//引用考生列表
  stdTicketRefList = [];//准考证引用考生列表
  radioItem = {};
  ticketRadioItem = {};
  byMajorList = [];//毕业带选择专业
  selectOldMajorList = [];//新专业对应的老专业
  showStdRefDialog(templateModal) {
    this.selectOldMajorList = [];
    this.stdRefQuery.certNo="";
    this.stdRefQuery.ticketNo="";
    this.stdRefQuery.majorId="";
    this.stdRefQuery.masterSchoolId="";
    this.stdRefWin = this.bsModalService.show(templateModal, { class: "modal-lg" });
  }
  //引用考生-查询
  findStdRefList() {
    if (!this.stdRefQuery.certNo && !this.stdRefQuery.ticketNo) {
      AppComponent.alert({title:"信息提示",text:"请输入过滤条件!"});
      return;
    }
    //刷新考生
    let param = {
      cert_no: this.stdRefQuery.certNo, 
      ticket_no: this.stdRefQuery.ticketNo,
      std_source: "" 
    };
    AppComponent.GobalComponent.setLoading(true);
    FrameRequest.requestArray("std/stdRegInfo/list.htm", param, (arrary) => {
        AppComponent.GobalComponent.setLoading(false);
        if (null == arrary || arrary.length == 0) {
          AppComponent.alert({title:"信息提示",text:"查询不到考生信息!"});
          return;
        } else {
          this.stdRefList = arrary;
        }
    });
  }

  
  //新申请
  selectStdRef() {
    if (!this.stdRefList.length || !this.radioItem['id']) {
      AppComponent.alert({title:"信息提示",text:"请选择考生!"});
      return;
    }
    if (!this.stdRefQuery.majorId) {
      AppComponent.alert({title:"信息提示",text:"请选择专业!"});
      return;
    }
    
    if (!this.stdRefQuery.masterSchoolId) {
      AppComponent.alert({title:"信息提示",text:"请选择学校!"});
      return;
    }
    let param = {
      std_reg_id: this.radioItem['id'], 
      major_id: this.stdRefQuery.majorId,
      school_id: this.stdRefQuery.masterSchoolId
    };

    AppComponent.confirm("确定申请毕业论文答辩吗",()=>{
      FrameRequest.requestEntity("by/byPaperApply/createbymgm.htm", param, async () => {
        AppComponent.GobalComponent.successMsg('提交成功!');
        this.framePager.reload();
        this.stdRefWin.hide();
      });
    });

    
  }

  freshSchoolInfo(majorId) {
   
    this.freshOldMajor(majorId);//刷新对应老专业显示
  }
  
  freshOldMajor(majorId) {
    let param = {
      new_major_id: majorId
    }
    FrameRequest.requestArray("pl/plMajorOldNew/getOldMajorList.htm", param, (array)=>{
      this.selectOldMajorList = array;
    });
  }


  //保存基本信息
  saveBaseInfo() {
    AppComponent.GobalComponent.setLoading(true);
    FrameRequest.requestEntity("by/byPaperApply/edit.htm", this.item, (entity)=>{
      AppComponent.GobalComponent.setLoading(false);
      AppComponent.GobalComponent.successMsg('保存成功!');
    });
  }


  downApplyXls() {
    let param = {
      exam_time_id: this.query.examTimeId,
      by_status: this.query.status,
      major_id: this.query.majorId,
      school_id: this.query.masterSchoolId,
      query : this.query.query
    };
    AppComponent.GobalComponent.setLoading(true);
    FrameRequest.download("by/byPaperApply/downapplyxls.htm", param, ()=>{
        AppComponent.GobalComponent.setLoading(false);
        AppComponent.GobalComponent.successMsg("导出成功!");
    });
  }

  resetdata(){
    this.query.query="";
    this.query.majorId="";
    this.query.status=this.status;
    this.query.masterSchoolId = this.org_id;
    this.query.examTimeId=this.examTimeId;
  }

  formateFinalScore(item) {
    if (item.final_score == '888') {
      return '顶替';
    } else if (item.final_score == '999') {
      return '免考';
    }
    if (item.final_score == '-9') {
      return '缺考';
    } else if (item.final_score == '-3') {
      return '违纪';
    } else if (item.final_score == '-2') {
      return '免考';
    } else if (item.final_score == '-1') {
      return '舞弊';
    } else if (item.final_score == '200') {
      return '免考';
    } else if (item.final_score == '201') {
      return '及格';
    } else if (item.final_score == '202') {
      return '中等';
    } else if (item.final_score == '203') {
      return '良好';
    } else if (item.final_score == '204') {
      return '优秀';
    }
    if (Number(item.final_score) < 60) {
      return "";
    }
    return item.final_score;
  }


}