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-paperscoreupload",
  templateUrl: "./paper-score-upload.component.html",
  styleUrls: ["./paper-score-upload.component.scss"]
})
export class PaperScoreUploadComponent extends FlexTableComponent implements OnInit {

  public query = {
    query: "",
    year_code: "",
    batch_id: ""
  };
  
  public queryDetail = {
    course_id: "",
    major_id: "",
    year_code:"",
    query: "",
    batch_id: ""
  }
 
  public impParam = {
    year_code: ""
  }

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

  filePath : String;
  yearCodeList = [];
  batchList = [];
  impBatchList = [];//导入界面批次列表
  //TODO
  QUERY_URL = "kj/kjCollegeScoreMain/page.htm";
  DELETE_URL = "kj/kjCollegeScoreMain/delete.htm";
  //GET_URL = "kj/kjCollegeScoreMain/get.htm";
  //ADD_URL = "kj/kjCollegeScoreMain/add.htm";
  //EDIT_URL = "kj/kjCollegeScoreMain/edit.htm";
  GET_URL = "kj/kjCollegeScoreDetail/get.htm";
  ADD_URL = "kj/kjCollegeScoreDetail/add.htm";
  EDIT_URL = "kj/kjCollegeScoreDetail/edit.htm";

  UPLOAD_URL = "pl/kjCollegeScoreMain/bypaper/upload.htm";
  ORG_LIST_URL = "cf/cfOrganization/list.htm";
  QUERY_DETAIL_URL = "kj/kjCollegeScoreDetail/page.htm";
  //主记录提交审核
  SUBMIT_TO_AUTH = "kj/kjCollegeScoreMain/submitaudit.htm";
  //删除详情记录
  DETAIL_DELETE_URL = "kj/kjCollegeScoreDetail/delete.htm";

  INIT_DATA_URL = "kw/kjCollegeBatchInfo/initdata.htm";

  // 导出
  EXPORT_URL= "kj/kjCollegeScoreDetail/exportScoreDetail.htm";  
  EXPORT_PAPERTILE_URL= "kj/kjCollegeScoreDetail/exportDoublePaperTitle.htm";  
  
  JOIN_SCHOOL_URL= "pl/plMajorApplyJoinSchool/list.htm";
  EXPORT_STATIC_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],
      'ticket_no': [null, Validators.required],
      'std_name': [null, Validators.required],
      'paper_title': [null, Validators.required],
      'major_id': [null, Validators.required],
      'score': [null, Validators.required],
      'remark': [null, null],
      'join_school_id': [null, null]
     
    });
  }

  ngOnInit() {
    this.editShowType = "showMainList";
    //专业
    var parm = {ids:""};
    FrameRequest.requestArray("pl/plMajor/list.htm", parm, (arrary) => {
      this.majorList = arrary;
    });
    //主考学校
    FrameRequest.requestArray(this.ORG_LIST_URL, {org_type: 1}, (arrary) => {
      this.masterSchoolList = arrary;
    });
    //年度码
    FrameRequest.requestArray("pl/plExamTime/listPlExamTimeForBy.htm", {}, (array) => {
      this.yearCodeList = array;
    });
    FrameRequest.requestArray("kj/kjCollegeBatchInfo/list.htm", {scoreType: this.GLOBAL_SCORE_TYPE, yearCode:""}, (array) => {
      this.batchList = array;
      this.impBatchList = array;
    });  

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

  createMain(){
    AppComponent.confirm("确定创建成绩上报申请吗",()=>{
      
      FrameRequest.request("kj/kjCollegeScoreMain/addForSchool.htm", {score_type: this.GLOBAL_SCORE_TYPE}, (ret)=>{
        if (ret.errorCode == 0) {
          this.framePager.reload();
          AppComponent.GobalComponent.successMsg('成功提交!');
        }
      });
    });
  }
  
  
  dogoEdit(editTemplateModal,item){
    if (this.main_status != 0 && this.main_status != 1) {
      AppComponent.alert({ 'title': '提示', text: '只能对新建的记录进行操作！' });
      return;
    }
    
    this.goEdit(editTemplateModal,'only','modal-lg',item);

  }

  hideEditModal(){
    this.hideModal();
    this.editShowType = "practicalDetailList";
    this.pageLevel = "detail";
    this.detailPager.reload();
  }

  

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

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

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

  //列表选择年度码选择
  yearCodeChange(year_code) {
    if (year_code) {
      FrameRequest.requestArray("kj/kjCollegeBatchInfo/list.htm", {scoreType: this.GLOBAL_SCORE_TYPE, yearCode:year_code}, (array) => {
        this.batchList = array;
      });
    } else {
      FrameRequest.requestArray("kj/kjCollegeBatchInfo/list.htm", {scoreType: this.GLOBAL_SCORE_TYPE, yearCode:""}, (array) => {
        this.batchList = array;
      });
    }
  }

  //导入界面年度码选择
  impYearCodeChange(year_code) {
    if (year_code) {
      FrameRequest.requestArray("kj/kjCollegeBatchInfo/list.htm", {scoreType: this.GLOBAL_SCORE_TYPE, yearCode:year_code}, (array) => {
        this.impBatchList = array;
      });
    } else {
      FrameRequest.requestArray("kj/kjCollegeBatchInfo/list.htm", {scoreType: this.GLOBAL_SCORE_TYPE, yearCode:""}, (array) => {
        this.impBatchList = array;
      });
    }
  }

  //导入
  importFunc() {
    if (!this.queryDetail.batch_id) {
      AppComponent.alert({title: "信息提示", text: "请选择批次!"});
      return;
    }
    let param = {
      batch_id: this.queryDetail.batch_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 = "showMainList";
        AppComponent.alert({ 'title': '提示', 'text': '有错误数据，请修正后，再上传' });
      } else if (ret.errorCode == 0) {
        this.hideModal();
        this.framePager.reload();
        this.editShowType = "showMainList";
        AppComponent.alert({title:"信息提示", text:"上报成功!"});
      }
    }));
  }

  downTemplate() {
    AppComponent.GobalComponent.setLoading(true);
    FrameRequest.download("pl/kjCollegeScoreMain/template/download.htm", {templateName:"paper_score_upload.xlsx"}, ()=>{
      AppComponent.GobalComponent.setLoading(false);
    });
  }

  //错误数据下载
  downloadErrFile() {
    AppComponent.GobalComponent.setLoading(true);
    FrameRequest.download("pl/kjCollegeScoreMain/error/download.htm",  { filePath: this.filePath }, ()=>{
      AppComponent.GobalComponent.setLoading(false);
    });
  }

  //保存论文成绩批次
  savePracticalBatch() {debugger
    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;
    if(null != this.main_id){
      this.item.main_id = this.main_id;
    }

    if(!this.item.join_school_id){
      this.item.join_school_id = "";
    }
    
    FrameRequest.requestEntity(url, this.item, async () => {
      AppComponent.GobalComponent.successMsg('专本衔接批次保存成功');
      this.hideEditModal();
    });   
  }

  //提交到省
  submit() {
    let checkedArray = this.framePager.getCheckedArray();
    if (checkedArray.length == 0) {
      AppComponent.alert({title:"信息提示",text:"请选待提交记录!"});
      return;
    }
    let repeat = false;
    for (let obj of checkedArray) {
      if (obj.status != 0) {
        repeat = true;
        AppComponent.alert({title:"信息提示",text:"不能重复提交!"});
        break;
      }
    }
    if (repeat) {
      return false;
    }
    AppComponent.confirm("确定提交",()=>{
      let idArr = checkedArray.map((obj) => obj.id);
      FrameRequest.request(this.SUBMIT_TO_AUTH, {ids: idArr, scoreType: this.GLOBAL_SCORE_TYPE}, (ret)=>{
        if (ret.errorCode == 0) {
          this.framePager.reload();
          AppComponent.GobalComponent.successMsg('成功提交!');
        }
      });
    });
  }

  confirmSubmit() {

    AppComponent.confirm("确认后，不可再提交，确认完成本批次上报吗",()=>{
      
      FrameRequest.request("kj/kjCollegeScoreMain/confirmSubmitAudit.htm", {scoreType: this.GLOBAL_SCORE_TYPE}, (ret)=>{
        if (ret.errorCode == 0) {
          this.framePager.reload();
          AppComponent.GobalComponent.successMsg('确定完成本批次上报成功!');
        }
      });
    });
  }

  confirmDoublePaperTitle() {

    AppComponent.confirm("确认完成本批次专业“论文标题”重复校对吗",()=>{
      
      FrameRequest.request("kj/kjCollegeScoreMain/confirmDoublePaperTitle.htm", {scoreType: this.GLOBAL_SCORE_TYPE}, (ret)=>{
        if (ret.errorCode == 0) {
          this.framePager.reload();
          AppComponent.GobalComponent.successMsg('确认完成校对成功!');
        }
      });
    });
  }
  
  

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

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

  //关闭导入框，留在详情界面
  hideImpWin() {
    if(this.bsModalWin) 
      this.bsModalWin.hide();
    this.editShowType = "showMainList";
  }

  //主记录删除
  async preDeleteEvent() {
    let checkArray = this.framePager.getCheckedArray();
    if (checkArray) {
      for (let i = 0; i < checkArray.length; i++) {
        if(checkArray[i].status != 0&&checkArray[i].status != 1) {//只能删除0-新建 状态
          AppComponent.alert({ 'title': '提示', text: '只能删除新建状态记录！' });
          return false;
        }
      }
    }
    return true;
  }

  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(this.DETAIL_DELETE_URL, {ids:checkedArray.join()}, () => {
        AppComponent.GobalComponent.successMsg('数据删除成功!');
        this.aftDeleteEvent();
        this.detailPager.reload();
      });
    })
  }

                                 
  //导出
  exportScoreDetail() {
    AppComponent.GobalComponent.setLoading(true);
    FrameRequest.download(this.EXPORT_URL, {
      yearCode : this.year_code,
      query:this.query.query,
      schoolId : this.school_id,
      scoreType : this.GLOBAL_SCORE_TYPE,
      main_id:this.main_id
    }, () => {
      AppComponent.GobalComponent.setLoading(false);
      AppComponent.GobalComponent.successMsg("上报成绩导出成功");
    });
  }

  exportDoublePaperTitle() {
    AppComponent.GobalComponent.setLoading(true);
    FrameRequest.download(this.EXPORT_PAPERTILE_URL, {
      yearCode : this.year_code,
      schoolId : this.school_id
    }, () => {
      AppComponent.GobalComponent.setLoading(false);
      AppComponent.GobalComponent.successMsg("专业“论文标题”重复的毕业论文成绩导出成功");
    });
  }
  

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

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