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

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

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

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

  filePath : String;
  yearCodeList = [];
  courseList = [];
  //TODO
  QUERY_URL = "kj/kjUnifiedScoreMain/page.htm";
  DELETE_URL = "kj/kjUnifiedScoreMain/delete.htm";
  GET_URL = "kj/kjUnifiedScoreMain/get.htm";
  ADD_URL = "kj/kjUnifiedScoreMain/add.htm";
  EDIT_URL = "kj/kjUnifiedScoreMain/edit.htm";

  UPLOAD_URL = "pl/kjUnifiedScoreMain/upload.htm";
  UPLOAD_FORDBF_URL = "pl/kjUnifiedScoreMain/uploadForDbf.htm";

  ORG_LIST_URL = "cf/cfOrganization/list.htm";
  QUERY_DETAIL_URL = "kj/kjUnifiedScoreDetail/page.htm";
  //删除详情记录
  DETAIL_DELETE_URL = "kj/kjUnifiedScoreDetail/delete.htm";

  main_id="";
  school_id="";
  pageLevel = "main";//标识 主列表 和 计划详情列表切换
  majorList = [];
  masterSchoolList = [];
  defaultBatchName = "";

  interval = null;
  progress_value = -1;

  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, null],
    });
  }

  ngOnInit() {
    this.editShowType = "showMainList";
     //课程--course_exam_type=2为实践课
     FrameRequest.requestArray("pl/plCourse/listCourseByType.htm", {course_exam_type:1,special_flag:""}, (arrary)=>{
       this.courseList = arrary;
     });
    //专业
    var parm = {ids:""};
    FrameRequest.requestArray("pl/plMajor/list.htm", parm, (arrary) => {
      this.majorList = arrary;
    });
    //主考学校
    FrameRequest.requestArray(this.ORG_LIST_URL, {org_type: 4}, (arrary) => {
      this.masterSchoolList = arrary;
    });
    //年度码
    FrameRequest.requestArray("pl/plYearCode/list.htm", {}, (array) => {
      this.yearCodeList = array;
    });
  }

  search(param) {
    if(!this.query.year_code){
      this.query.year_code = "";
    }
    
    param.query = this.query.query;
    param.yearCode = this.query.year_code;
    param.schoolId = this.school_id;
    param.scoreType = 0;//实践课
  }

  searchDetail(paramDetail) {
    paramDetail.query = this.queryDetail.query;
    paramDetail.course_id = this.queryDetail.course_id;
    paramDetail.major_id = this.queryDetail.major_id;
    paramDetail.yearCode = this.impParam.year_code;
    paramDetail.mainId = this.main_id;
    paramDetail.std_source = this.queryDetail.std_source;


  }

  resetDetail(){
    this.queryDetail.query="";
    this.queryDetail.course_id=null;
    this.queryDetail.major_id=null;
    this.queryDetail.std_source="";
  }

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


  }

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

  //年度码选择
  yearCodeChange(year_code) {

  }

  //导入
  importFunc() {
    if (!this.impParam.year_code) {
      AppComponent.alert({title: "信息提示", text: "选择年度码!"});
      return;
    }
    let param = {
      year_code: this.impParam.year_code, 
      main_id: this.main_id,
      title_rows: 1
    };
    let progress_this = this;
    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) {
        AppComponent.alert({title:"信息提示", text:"统考成绩导入校验成功，系统后台正在导入成绩中!"},function(){
          progress_this.progress_value = 0;
          progress_this.interval = setInterval(function() {
            
            progress_this.doProgress();
            }, 5000);
        });

     }

    }));
  }


  //导入
  importFuncForDbf() {
    if (!this.impParam.year_code) {
      AppComponent.alert({title: "信息提示", text: "选择年度码!"});
      return;
    }
    let param = {
      year_code: this.impParam.year_code, 
      main_id: this.main_id,
      title_rows: 1
    };

    let progress_this = this;

    this.uploaderForDbf.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) {
       
        AppComponent.alert({title:"信息提示", text:"统考成绩导入校验成功，系统后台正在导入成绩中!"},function(){
          progress_this.progress_value = 0;
          progress_this.interval = setInterval(function() {
            
            progress_this.doProgress();
            }, 2000);
        });

      }
    }));
  }
  
  doProgress(){
    let doProgress_this = this;
    
    // 查询后台导入进度
    FrameRequest.requestEntity('kj/kjUnifiedScoreMain/queryProgress.htm',{}, (entity) => {
      if(entity){
        doProgress_this.progress_value = entity;

        if(doProgress_this.progress_value>=100) {
          doProgress_this.progress_value = 100;
          window.clearInterval(doProgress_this.interval);
          AppComponent.alert({title:"信息提示", text:"统考成绩导入成功!"},function(){
            doProgress_this.hideModal();
            doProgress_this.detailPager.reload();
            doProgress_this.editShowType = "scoreDetailList";

            doProgress_this.progress_value = -1;
            
          }); 
    
        }

      }
      
    });

    
  }

  // downTemplate() {
  //   FrameRequest.download("pl/kjUnifiedScoreMain/download.htm");
  // }

  //错误数据下载
  downloadErrFile() {
    FrameRequest.download("pl/kjUnifiedScoreMain/downloaderror.htm",  { filePath: this.filePath });
  }

  //保存实践课批次
  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 = 0;
    FrameRequest.requestEntity(url, this.item, async () => {
      AppComponent.GobalComponent.successMsg('实践课批次保存成功');
      this.framePager.reload();
      if(this.bsModalWin) {
        this.bsModalWin.hide();
      }
      this.item = null;
      this.editShowType = "showMainList";
    });   
  }

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

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

  deletePlanDetail(item) {
    let checkedArray = this.detailPager.getCheckedArray();
    if(checkedArray.length === 0 && !item) {
      AppComponent.alert({title:"信息提示",text:"请选择数据!"})
      return;
    }
    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();
      });
    })
  }

  downTemplate() {
    FrameRequest.download("pl/kjCollegeScoreMain/template/download.htm",{templateName:"unified_score_upload.xlsx"});
  }

  //导出上报数据
  export() {
    let param = {
      query: this.queryDetail.query,
      course_id: this.queryDetail.course_id, 
      major_id: this.queryDetail.major_id,
      yearCode:this.impParam.year_code,
      mainId:this.main_id,
      std_source:this.queryDetail.std_source
    };
    AppComponent.GobalComponent.setLoading(true);
    FrameRequest.download("kj/kjUnifiedScoreDetail/exportForScoreInput.htm", param, ()=>{
      AppComponent.GobalComponent.setLoading(false);
      AppComponent.GobalComponent.successMsg("下载成功!");
    });
  }
}