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

  public query = {
    query: "",
    year_code: "",
    course_id: "",
    course_name:""
  };
  
  public composeQuery = {
    year_code: ""
  }

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

  filePath : String;
  yearCodeList = [];
  courseList = [];
  //TODO
  QUERY_URL = "kj/kjCourseRatio/result.htm";
  ORG_LIST_URL = "cf/cfOrganization/list.htm";
  UPLOAD_URL = "pl/kjUnifiedScoreMain/uploadCompose.htm";


  school_id="";
  majorList = [];
  masterSchoolList = [];
  is_compose100 =0;

  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, Validators.compose([Validators.required])],
    });
  }

  ngOnInit() {
    this.editShowType = "showMainList";
     //课程--course_exam_type=2为实践课
     //FrameRequest.requestArray("pl/plCourse/listCourseByType.htm", {course_exam_type:2,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/plExamTime/list.htm", {}, (array) => {
      this.yearCodeList = array;
    });
  }

  search(param) {
    param.query = this.query.query;
    if (!this.query.year_code) {
      this.query.year_code="";
    }
    if (!this.query.course_id) {
      this.query.course_id="";
    }
    param.yearCode = this.query.year_code;
    param.courseId = this.query.course_id;
  }

  //弹出修改框
  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();
  }

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

  }

  /**
   * 查询列表课程选择
   */
  courseQueryModal(modal) {
    let checkedArray = modal.framePager.getCheckedArray();
    if (checkedArray.length > 0) {
      this.query.course_name = checkedArray[0].course_name;
	  this.query.course_id = checkedArray[0].id;
	  modal.hideModal();
    }
	
  }

  //合成方法
  composeFunc() {
    if (!this.composeQuery.year_code) {
      AppComponent.alert({title:"信息提示",text:"请选择年度码!"});
      return;
    }

    if(this.is_compose100 == 1){
      AppComponent.confirm("确定百分百合成成绩吗",()=>{
        AppComponent.GobalComponent.setLoading(true);
        FrameRequest.request("pl/kjUnifiedScoreMain/compose100.htm", {year_code: this.composeQuery.year_code}, (ret)=>{
          if (ret.errorCode == 0) {
            this.hideImpWin();
            this.framePager.reload();
            AppComponent.GobalComponent.successMsg('百分百合成成功!');
            AppComponent.GobalComponent.setLoading(false);
          }
        });
      
      });

      
    }else{
      let progress_this = this;
      AppComponent.confirm("确定合成成绩吗",()=>{
        progress_this.progress_value = 0;
        progress_this.interval = setInterval(function() { 
          if(progress_this.progress_value <99){
            progress_this.progress_value += 1;
          }
          
        }, 2000);

        FrameRequest.request("pl/kjUnifiedScoreMain/compose.htm", {year_code: this.composeQuery.year_code}, (ret)=>{
          if (ret.errorCode == 0) {
              window.clearInterval(progress_this.interval);
              AppComponent.alert({title:"信息提示", text:"成绩合成成功!"},function(){
                progress_this.hideImpWin();
                progress_this.framePager.reload();

                progress_this.progress_value = -1;
              
            }); 

            
          }else{
            progress_this.hideImpWin();
           // AppComponent.GobalComponent.errorMsg(ret.errorMsg);

            window.clearInterval(progress_this.interval);
            progress_this.progress_value = -1;

            AppComponent.alert({title:"信息提示", text: ret.errorMsg});
            
          }
        });
      
      });

     
    }
    
  }

  //统考成绩补合成
  importFunc() {
   
    AppComponent.confirm("确定统考成绩补合成吗",()=>{
        let param = {
          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.hideImpWin();
            AppComponent.GobalComponent.errorMsg('有错误数据，请修正后，再上传!');
          } else if (ret.errorCode == 0) {
            this.hideImpWin();
            this.framePager.reload();
            AppComponent.GobalComponent.successMsg('统考成绩补合成成功!');
           
          }
        }));
    
    });

  }

  downTemplate() {
    FrameRequest.download("pl/kjUnifiedScoreMain/download.htm",{templateName:"compose_upload.xlsx"});
  }

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