import { Component, OnInit, ViewChild, ElementRef, TemplateRef } from '@angular/core';
import { FlexTableComponent } from '../../../../../shared/common/FlexTable.component';
import { BsModalService } from 'ngx-bootstrap/modal';
import { FormControl, Validators, FormBuilder } from '@angular/forms';
import { CustomValidators } from 'ng2-validation';
import { FrameFunction } from '../../../../../shared/frame/frame_function';
import { FrameRequest } from '../../../../../shared/frame/frame-request';
import { AppComponent } from '../../../../../app.component';
import { deprecate } from 'util';
import { FrameUploaderComponent } from '../../../../../core/uploader/uploader.component';
import { FramePagerComponent } from '../../../../../core/pager/pager.component';
import { FlexSelectComponent } from "../../../../../shared/components/flexSelect/FlexSelect.component";

@Component({
    selector: 'app-unified-layout',
    templateUrl: './unified-layout.component.html',
    styleUrls: ['./unified-layout.component.scss']
})

export class UnifiedLayoutComponent extends FlexTableComponent implements OnInit {
    
    examPointList = [];
    examUnitList = [];
    filePath : String;
    filePathForRoomName : String;

    @ViewChild('uploader')
    uploader: FrameUploaderComponent;
    @ViewChild('uploaderForRoomName')
    uploaderForRoomName: FrameUploaderComponent;
    @ViewChild('donePager')
    donePager:FramePagerComponent;
    @ViewChild('toLayoutPager')
    toLayoutPager:FramePagerComponent;
    @ViewChild('examUnitPager')
    examUnitPager:FramePagerComponent;

    @ViewChild('exam_time_select')  
	exam_time_select:FlexSelectComponent;
	
	@ViewChild('layoutModal')
    layoutModal: TemplateRef<any>
    
    @ViewChild('ticketnoModal')
	ticketnoModal: TemplateRef<any>

    UPLOAD_URL="kw/kwLayout/updateaddress.htm";
    UPLOAD_URL_FORROOMNAME="kw/kwLayout/updateaddressForRoomName.htm";

    public query = {
        exPointId: "",
        examTimeId: "",
        exUnitId: "",//具体选择的考点
        maxCourse: 30  //默认30
    }

    ticket_no="";

    constructor(public bsModalService: BsModalService, fb: FormBuilder) { 
        super(bsModalService);
        this.formModel = fb.group({
             'maxCourse': [null, Validators.compose([Validators.required])],
          });
    }
  
    ngOnInit() {
        let this_ = this;
      
            FrameRequest.requestMap("kw/kwLayout/initdata.htm", {}, (map)=>{
                this_.examPointList = map["examPointList"];
                //this_.examUnitList = map["examUnitList"];
                if (map["exam_time_id"]) {
                    this_.query.examTimeId = map["exam_time_id"];
                    this_.examTimeChange(this_.query.examTimeId);
                }
            });
       
    }
    //编排完成后刷新主界面
    fresh(){
        this.donePager.reload();
        this.toLayoutPager.reload();
    }
    //编排界面-分页查询条件
    search(param) {
        if (!this.query.exPointId) {
            this.query.exPointId="";
        }
        if (!this.query.exUnitId) {
            this.query.exUnitId="";
        }
        if (!this.query.examTimeId) {
            this.query.examTimeId="";
        }
        param.exam_point_id=this.query.exPointId;
        param.exam_unit_id=this.query.exUnitId;
        param.exam_time_id=this.query.examTimeId;
    }


    examUnitsearch(param) {
        param.exam_time_id=this.query.examTimeId;
        param.exam_point_id=this.query.exPointId;
        param.aloneFlag = 0;//编排的考点只查 统考编排的考点，过滤掉特殊课程考点!
	}
	//确认编排
	confirmLayout() {
		AppComponent.confirm("没有配置独立编排的课程，将以普通课程编排，确认继续编排吗？",()=>{
			this.shouModalWin(this.layoutModal,'modal-lg');
		});
	}
    //编排操作
    layout() {
        if (!FrameFunction.validForm(this.formModel)) {
            return;
        }
        if (!this.query.exPointId) {
            AppComponent.alert({ title: "信息提示", text: "请选择考试批次!" });
            return;
        }
        if (Number(this.query.maxCourse) < 1 || Number(this.query.maxCourse) > 30) {
            AppComponent.alert({ title: "信息提示", text: "输入1-30之间课程数!" });
            return;
        }
        let param = {
            exam_point_id: this.query.exPointId,
            max_courses: this.query.maxCourse
		};

		AppComponent.GobalComponent.setLoading(true);
		//先取消编排
		//this.cancelLayout();
        //编排
        
		FrameRequest.request("kw/kwLayout/layout.htm", param, (ret) => {
            
            AppComponent.GobalComponent.setLoading(false);
			if (ret.errorCode == 0) {
				//AppComponent.GobalComponent.successMsg("编排成功!");
				super.hideModal();
                this.fresh();
                AppComponent.alert({ 'title': '提示', 'text': "编排成功!" });

				return;
			}else{
                super.hideModal();
                AppComponent.alert({ 'title': '提示', 'text': ret.errorMsg });

               // AppComponent.GobalComponent.errorMsg(ret.errorMsg);
            }
		});
		
    }

  //参数处理,父类调用,覆盖了父类该方法
  async preShowModalWin(){
    var param = {
        exam_point_id:this.query.exPointId,
        alone_flag: 0,
        RequestLoading:true
    };
    await FrameRequest.getRequestPromise('kw/kwExamUnit/getunitlist.htm',param)
    .then((resp) => {
      this.examUnitList = resp['array'];
    })
    return true;
  }

  //编排查询------------------------------------------------------------------------------------------------------
  examTimeChange(examTimeId) {
    if (!examTimeId) {
        return;
    }
    var param = {
        start: 0,
        limit: 100,
        exam_time_id: examTimeId,
        RequestLoading: true
    }
    FrameRequest.requestPage("kw/kwExamPoint/page.htm", param, (page)=>{
        this.examPointList = page.records;
        //默认选中第一个考点
        if (this.examPointList.length > 0) {
            this.query.exPointId = this.examPointList[0].id;
            this.donePager.reload();
            this.toLayoutPager.reload();
            //刷新该考点下面的考点
            this.freshExamUit(this.query.exPointId);
        }
    });
  }

  freshExamUit(exPointId) {
    if (!exPointId) {
        return;
    }
    var param = {
        start: 0,
        limit: 100,
        exam_time_id: this.query.examTimeId,
        exam_point_id: exPointId,
        aloneFlag: 0
    }
    AppComponent.GobalComponent.setLoading(true);
    FrameRequest.requestPage("kw/kwExamUnit/page.htm", param, (page)=>{
        AppComponent.GobalComponent.setLoading(false);
        this.examUnitList = page.records;
    });
  }

  formate(row) {
    if(row.exam_times == "A") {
        return row.exam_first_day + "上午";
    } else if(row.exam_times == "B") {
        return row.exam_first_day + "下午";
    } else if(row.exam_times == "C") {
        return row.exam_second_day + "上午";
    } else if(row.exam_times == "D") {
        return row.exam_second_day + "下午";
    } else if(row.exam_times == "X") {
        return row.exam_third_day + "上午";
    } else if(row.exam_times == "Y") {
        return row.exam_third_day + "下午";
    }    
  }

  //取消编排
  cancelLayout() {
    if (!this.query.examTimeId) {
        AppComponent.alert({ title: "信息提示", text: "请选择考试批次!" });
        return;
    }
    if (!this.query.exPointId) {
        AppComponent.alert({ title: "信息提示", text: "请选择考区!" });
        return;
    }
    AppComponent.confirm("确定取消?",()=>{
     let param = {
         exam_point_id:this.query.exPointId,
         exam_time_id:this.query.examTimeId,
         RequestLoading:true
	 };
	 AppComponent.GobalComponent.setLoading(true);
     FrameRequest.request("kw/kwLayout/cancelLayout.htm", param, (ret) => {
         
		AppComponent.GobalComponent.setLoading(false);
         if (ret.errorCode == 0) {
             AppComponent.GobalComponent.successMsg("取消成功!");
             this.fresh();
             return;
         }else{
            AppComponent.GobalComponent.errorMsg(ret.errorMsg);
            this.fresh();
            return;
         }
     });
    });
  }

  //导出编排汇总--只会导出统考的
  exportLySummary() {
    if (!this.query.examTimeId) {
        AppComponent.alert({ title: "信息提示", text: "请选择考试批次!" });
        return;
    }
    if (!this.query.exPointId) {
        AppComponent.alert({ title: "信息提示", text: "请选择考点!" });
        return;
    }
    let param = {
        exam_point_id: this.query.exPointId,
        exam_unit_id: "",
		exam_time_id: this.query.examTimeId,
		alone_flag: 0
    };
    AppComponent.GobalComponent.setLoading(true);
    FrameRequest.download("kw/kwLayout/exportsummery.htm", param, ()=>{
        AppComponent.GobalComponent.setLoading(false);
        AppComponent.GobalComponent.successMsg("考场地址导出成功");
    });
  }

  //导出编排汇总--只会导出统考的
  exportLySummaryForRoomName() {
    if (!this.query.examTimeId) {
        AppComponent.alert({ title: "信息提示", text: "请选择考试批次!" });
        return;
    }
    if (!this.query.exPointId) {
        AppComponent.alert({ title: "信息提示", text: "请选择考点!" });
        return;
    }
    let param = {
        exam_point_id: this.query.exPointId,
        exam_unit_id: this.query.exUnitId,
		exam_time_id: this.query.examTimeId,
		alone_flag: 0
    };
    AppComponent.GobalComponent.setLoading(true);
    FrameRequest.download("kw/kwLayout/exportsummeryForRoomName.htm", param, ()=>{
        AppComponent.GobalComponent.setLoading(false);
        AppComponent.GobalComponent.successMsg("考场地址导出成功");
    });
  }

  //更新考场地址
  uploadExamAddr() {
    
    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;
          AppComponent.alert({ 'title': '提示', 'text': '有错误数据，请修正后，再上传' });
        } else if (ret.errorCode == -2) {
            
            AppComponent.alert({ 'title': '提示', 'text': ret.errorMsg });
        } else if (ret.errorCode == 0) {
          AppComponent.alert({title:"信息提示", text:"更新成功!"});
        }
      }));
  }

  //更新考场地址
  uploadExamAddrForRoomName() {
    
    let param = {
        title_rows: 1
      };
      this.uploaderForRoomName.choooseFileAndUpload(param, ((ret) => {
        if (ret.errorCode > 0) {
          AppComponent.alert({title:"信息提示", text: ret.errorMsg});
        }
        else if (ret.errorCode == -1) {
          this.filePathForRoomName = ret.url;
          AppComponent.alert({ 'title': '提示', 'text': '有错误数据，请修正后，再上传' });
        } else if (ret.errorCode == -2) {
            AppComponent.alert({ 'title': '提示', 'text': ret.errorMsg });
        } else if (ret.errorCode == 0) {
          AppComponent.alert({title:"信息提示", text:"更新成功!"});
        }
      }));
  }


  //错误数据下载
  downloadErrFile() {
    AppComponent.GobalComponent.setLoading(true);
    FrameRequest.download("pl/kwLayout/error/download.htm",  { filePath: this.filePath }, ()=>{
        AppComponent.GobalComponent.setLoading(false);
    });
  }
  downloadErrFileForRoomName() {
    AppComponent.GobalComponent.setLoading(true);
    FrameRequest.download("pl/kwLayout/error/download.htm",  { filePath: this.filePathForRoomName }, ()=>{
        AppComponent.GobalComponent.setLoading(false);
    });
  }
  
  //导出编排数据
  expLyData() {
    if (!this.query.examTimeId) {
        AppComponent.alert({ title: "信息提示", text: "请选择考试批次!" });
        return;
    }
    if (!this.query.exPointId) {
        AppComponent.alert({ title: "信息提示", text: "请选择考点!" });
        return;
    }
    
    if (!this.donePager.getRecords() || this.donePager.getRecords().length == 0) {
        AppComponent.alert({ title: "信息提示", text: "没有可以导出的数据!" });
        return;
    }
    let param = {
        exam_point_id:this.query.exPointId,
        exam_time_id:this.query.examTimeId
    };
    AppComponent.GobalComponent.setLoading(true);
    FrameRequest.download("kw/kwLayout/expdonexls.htm", param, ()=>{
        AppComponent.GobalComponent.setLoading(false);
        AppComponent.GobalComponent.successMsg("导出成功!");
    });
  }

 
  previewTicketno() {
    this.shouModalWin(this.ticketnoModal,'modal-lg');
  }

  //预览准考证
  downTicket() {
    if(!this.ticket_no){
      AppComponent.alert({ 'title': '提示', 'text': '请输入准考证号' });
      return;
	}
	
    FrameRequest.requestEntity("std/stdRegInfo/queryStdByTicketNo.htm",{ticket_no: this.ticket_no},  (entity) => {
        
        if(entity) {
            AppComponent.GobalComponent.setLoading(true);
            FrameRequest.download("std/stdRegInfo/downTicket.htm",  {ticket_no: this.ticket_no,is_layout:1}, ()=>{
                AppComponent.GobalComponent.setLoading(false);
                this.hideModal();
                AppComponent.GobalComponent.successMsg("下载成功!");
            });
    
        }else{
            AppComponent.alert({ 'title': '提示', 'text': '准考证'+this.ticket_no+'在系统中不存在!' });
        }
        
    })
    
    }
}
  