import { Component, OnInit, TemplateRef, 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 { 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 * as _ from 'lodash';

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

  public batchQuery = {
    query: "",
    year_code: ""
  }

  public mainQuery = {
    query: "",
    year_code: "",
    school_id: "",
    batch_id: ""
  };
  
  public detailQuery = {
    school_id:"",
    course_id: "",
    major_id: ""
  }
 
  public impParam = {
    year_code: ""
  }

  @ViewChild('uploader')
  uploader: FrameUploaderComponent;
  @ViewChild('mainPager')
  mainPager:FramePagerComponent;
  @ViewChild('detailPager')
  detailPager:FramePagerComponent;

  @ViewChild('rejectModal')
  rejectModal: TemplateRef<any>

  filePath : String;
  yearCodeList = [];
  courseList = [];
  
  BATCH_QUERY_URL = "kj/kjCollegeBatchInfo/page.htm";//批次分页

  QUERY_URL = "kj/kjCollegeScoreMain/page.htm";
  DELETE_URL = "kj/kjCollegeBatchInfo/delete.htm";
  GET_URL = "kj/kjCollegeBatchInfo/get.htm";
  ADD_URL = "kj/kjCollegeBatchInfo/add.htm";
  EDIT_URL = "kj/kjCollegeBatchInfo/edit.htm";

  QUERY_MAIN_URL = "kj/kjCollegeScoreMain/page.htm";//学校上报待审批信息分页

  UPLOAD_URL = "pl/kjCollegeScoreMain/bypaper/upload.htm";
  ORG_LIST_URL = "cf/cfOrganization/list.htm";
  QUERY_DETAIL_URL = "kj/kjCollegeScoreDetail/page.htm";

  AUTH_PASS_URL = "kj/kjCollegeScoreMain/auditpass.htm";
  AUTH_REJECT_URL = "kj/kjCollegeScoreMain/auditreject.htm";

  REG_FORM_URL = "kj/kjCollegeScoreDetail/export.htm";

  EXPORT_URL= "kj/kjCollegeScoreDetail/exportStaticScore.htm";  

  main_id = "";
  school_id="";
  year_code="";
  pageLevel = "main";//标识 主列表 和 计划详情列表切换
  majorList = [];
  masterSchoolList = [];
  defaultBatchName = "";
  GLOBAL_SCORE_TYPE = 4;//毕业论文成绩
  main_status = -1;
  uploadTime = null;

  constructor(
    public bsModalService: BsModalService,
    fb: FormBuilder
  ) {
    super();
    // CustomValidators.rangeLength([1, 6])
    this.formModel = fb.group({
      id: [null],
      'year_code' : [null, Validators.compose([Validators.required])],
      'batch_name' : [null, Validators.compose([Validators.required])],
      'remark' : [null],

    });
  }

  ngOnInit() {
    this.pageLevel = "batch";
    this.editShowType = "showBatchList";
    //专业
    var parm = {};
    FrameRequest.requestArray("pl/plMajor/openMajorList.htm", parm, (arrary) => {
      this.majorList = arrary;
    });
    //主考学校
    FrameRequest.requestArray(this.ORG_LIST_URL, {org_type: 1,status:1}, (arrary) => {
      this.masterSchoolList = arrary;
    });
    //年度码
    FrameRequest.requestArray("pl/plExamTime/listPlExamTimeForBy.htm", {}, (array) => {
      this.yearCodeList = array;
    });

    FrameRequest.requestEntity("kj/kjCollegeBatchInfo/getUploadTime.htm", {scoreType: 6}, (entity) => {
      this.uploadTime = entity;
    });  
  }

  public rejectObject = {
    reject_remark:""
  }

  batchSearch(param) {
    
    if (!this.batchQuery.year_code) {
      this.batchQuery.year_code="";
    }
    param.query = this.batchQuery.query;
    param.yearCode = this.batchQuery.year_code;
    param.scoreType = this.GLOBAL_SCORE_TYPE;//毕业论文成绩
  }

  mainSearch(param) {
    
    if (!this.mainQuery.year_code) {
      this.mainQuery.year_code="";
    }
    if (!this.mainQuery.school_id) {
      this.mainQuery.school_id="";
    }
    param.query = this.mainQuery.query;
    param.yearCode = this.mainQuery.year_code;
    param.schoolId = this.mainQuery.school_id;
    param.batchId = this.mainQuery.batch_id;
    param.scoreType = this.GLOBAL_SCORE_TYPE;//毕业论文成绩
  }

  detailSearch(paramDetail) {
    if (!this.detailQuery.course_id) {
      this.detailQuery.course_id = "";
    }
    if (!this.detailQuery.major_id) {
      this.detailQuery.major_id = "";
    }
    paramDetail.courseId = this.detailQuery.course_id;
    paramDetail.majorId = this.detailQuery.major_id;
    paramDetail.schoolId = this.school_id;
    paramDetail.yearCode = this.year_code;
    paramDetail.scoreType = this.GLOBAL_SCORE_TYPE;//毕业论文成绩
    paramDetail.main_id = this.main_id;
  }


  //保存毕业论文批次
  savePracticalBatch() {
    if (!FrameFunction.validForm(this.formModel)) {
      return;
    }
    let url = this.item.id ? this.EDIT_URL: this.ADD_URL;
    if(_.isUndefined(this.item.id)) delete this.item.id;
    //循环判断元素是否undefined
    for (const key in this.item) {
      if(this.item[key] === undefined) {
        this.item[key] = "";
      }
    }
    //毕业论文批次
    this.item.score_type = this.GLOBAL_SCORE_TYPE;
    FrameRequest.requestEntity(url, this.item, async () => {
      AppComponent.GobalComponent.successMsg('毕业论文批次保存成功!');
      this.framePager.reload();
      if(this.bsModalWin) {
        this.bsModalWin.hide();
      }
      this.item = null;
      this.editShowType = "showBatchList";
    });   
  }

  //审核通过
  doAudit() {
    let checkedArray = this.mainPager.getCheckedArray();
    if (checkedArray.length == 0) {
      AppComponent.alert({title:"信息提示",text:"请选待审核记录!"});
      return;
    }
    let forbiden = false;
    for (let obj of checkedArray) {
      if (obj.status != 2) {
        forbiden = true;
        AppComponent.alert({title:"信息提示",text:"只能审核待审批记录!"});
        break;
      }
    }
    if (forbiden) {
      return false;
    }
    AppComponent.confirm("确定通过",()=>{
      let idArr = checkedArray.map((obj) => obj.id);
      FrameRequest.request(this.AUTH_PASS_URL, {ids: idArr,toStatus: 3}, (ret)=>{
        if (ret.errorCode == 0) {
          this.mainPager.reload();
          AppComponent.GobalComponent.successMsg('成功审核通过!');
        }
      });
    });
  }

  popUpRejectWind() {
    let exist = false;
    let checkedArray = this.mainPager.getCheckedArray();
    if (checkedArray.length == 0) {
      AppComponent.alert({title:"信息提示",text:"请选择待省级审核记录!"});
      return;
    }
    for (let obj of checkedArray) {
      if (obj.status != 2) {
        AppComponent.alert({title:"信息提示",text:"只能驳回待省级审核记录!"});
        exist = true;
        break;
      }
    }
    if (!exist) {
      this.shouModalWin(this.rejectModal,'modal-md');
    }
  }

  doReject() {
    let checkedArray = this.mainPager.getCheckedArray();
    AppComponent.confirm("确定驳回",()=>{
      let idArr = checkedArray.map((obj) => obj.id);
      let rejectParam = {
        id: idArr, 
        toStatus: 0, //驳回到主考学校
        scoreType: this.GLOBAL_SCORE_TYPE, //专本衔接
        msg: this.rejectObject.reject_remark
      }
      FrameRequest.request(this.AUTH_REJECT_URL, rejectParam, (ret)=>{
        if (ret.errorCode == 0) {
          this.hideModal();
          this.mainPager.reload();
          this.editShowType = "showMainList";
          AppComponent.GobalComponent.successMsg('成功驳回!');
        }
      });
    });

  }

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

    AppComponent.confirm("取消后，选择中的主考学校允许重新提交，确认吗",()=>{
      let idArr = checkedArray.map((obj) => obj.id);
      let rejectParam = {
        id: idArr
      }
      FrameRequest.request("kj/kjCollegeScoreMain/cancleConfirmSubmitAudit.htm", rejectParam, (ret)=>{
        if (ret.errorCode == 0) {
          this.hideModal();
          this.mainPager.reload();
          this.editShowType = "showMainList";
          AppComponent.GobalComponent.successMsg('取消确认完成本批次上报成功!');
        }
      });
    });

  }

  

  //打开申报主记录列表
  goMainList(batch_id,year_code) {
    this.mainQuery.batch_id = batch_id;
    this.mainQuery.year_code = year_code;
    this.editShowType = "showMainList";
    this.pageLevel = "main";
    this.mainPager.reload();
  }

  //打开批次对应的计划详情
  goDetailList(id,year_code, school_id, status) {
    this.editShowType = "practicalDetailList";
    this.pageLevel = "detail";
    this.year_code = year_code;
    this.school_id = school_id;
    this.main_status = status;
    this,this.main_id = id;
    this.detailPager.reload();
  }

  //返回主列表
  backMain() {
    this.editShowType = "showMainList";
    this.pageLevel = "main";
  }

  //返回批次列表
  backBatch() {
    this.editShowType = "showBatchList";
    this.pageLevel = "batch";
  }

  //毕业论文答辩申请登记表
  exportRegForm() {
    let checkedArray = this.detailPager.getCheckedArray();
    if(checkedArray.length === 0 || checkedArray.length > 1){
      AppComponent.alert({title:"信息提示",text:"请选择一个考生!"})
      return;
    }
    let array = this.detailPager.getCheckedArray(item => item.id);
    FrameRequest.download(this.REG_FORM_URL, {id: array[0]}, () => {
      AppComponent.GobalComponent.successMsg("毕业论文答辩申请登记表下载成功");
    });
  }

  //批次记录删除后台验证
  //删除主记录
  deleteMain(item) {
    if (item.status != 2) {
      AppComponent.alert({ 'title': '提示', text: '只能删除待省级审核记录！' });
      return false;
    }
    AppComponent.confirm("确定删除",()=>{
      FrameRequest.requestMap("kj/kjCollegeScoreMain/delete.htm", {ids:item.id}, () => {
        AppComponent.GobalComponent.successMsg('数据删除成功');
        this.aftDeleteEvent();
        this.detailPager.reload();
      });
    })
  }

  deletePlanDetail(item) {
    let checkedArray = this.detailPager.getCheckedArray();
    if(checkedArray.length === 0 && !item) {
      AppComponent.alert({title:"信息提示",text:"请选择数据!"})
      return;
    }
    if (this.main_status != 0&&this.main_status != 1) {
      AppComponent.alert({ 'title': '提示', text: '只能删除新建状态记录！' });
      return false;
    }
    AppComponent.confirm("确定删除",()=>{
      let checkedArray = [];
      item ? checkedArray[0] = item.id: 
             checkedArray = this.detailPager.getCheckedArray((item)=>item.id)
      
      FrameRequest.requestMap("kj/kjCollegeScoreDetail/delete.htm", {ids:checkedArray.join()}, () => {
        AppComponent.GobalComponent.successMsg('数据删除成功!');
        this.aftDeleteEvent();
        this.detailPager.reload();
      });
    });
  }

  //导出
  exportStaticScore() {
    if (!this.batchQuery.year_code) {
      AppComponent.alert({title:"信息提示",text:"请选择年度码!"});
      return;
    }

    AppComponent.GobalComponent.setLoading(true);
    FrameRequest.download(this.EXPORT_URL, {
      yearCode : this.batchQuery.year_code,
      scoreType : this.GLOBAL_SCORE_TYPE,
    }, () => {
      AppComponent.GobalComponent.setLoading(false);
      AppComponent.GobalComponent.successMsg("毕业论文成绩上报统计导出成功");
    });
  }
}