import { Component, OnInit } from '@angular/core';
import * as _ from 'lodash';
import { BsModalService } from 'ngx-bootstrap/modal';
import { FuncService } from '../../../../../core/service/func.service';
import { AjaxService } from '../../../../../core/service/ajax.service';
import { MsgService } from '../../../../../core/service/msg.service';
declare var aliPlayerUtil :any;
declare let laydate;


@Component({
  selector: 'app-exam-video-view',
  templateUrl: './exam-video-view.component.html',
  styleUrls: ['./exam-video-view.component.scss']
})
export class ExamVideoViewComponent implements OnInit {
  param = {
    examDate:'',
		hide_judge : false,
		// pause : false,
		// fullscreen : false,
    score_batch : 1,
    
		cur_score_seq : -1,
    last_score_seq : -1,
    next_score_seq : -1, //传递给后台的考生序号
    judge_score_num : 0,
    room:{ly_group_id:null,ly_room_id:null,room_addr: null},
    group:{ly_group_id:null,ly_room_id:null},
    percent: null,
  };
  
  GroupArray: any[];
  RoomMap: {};
  room: any;
  RoomArray: any;
  JudgeArray: any;
  ExRoomFace: any;
  
  videoArray = [];//上一个视频

  gCurrIdx = 0;//单分组多视频播放下标
  gFormalVideo = true;//是主机位
  gVideoList = [];//单分组对应多个视频

  currentStd: any;
  aliPlayer: any;
  curStep = '';
  repeat = true;

  bsModalWin: any;

  devMode = '';//test
  dateArray: any;
  tpl: any;
  curVideo: any;

  VideoTotal = null;
  vrotate = 0;

  
 
  constructor(public bsModalService: BsModalService,) { }

  ngOnInit() {
    this.param.examDate = FuncService.dateToShortString(new Date());
    this.getDate();
    this.init();
  }
 
  init(){
    if(!this.IsDate(this.param.examDate)){
      MsgService.errorAlert("请输入正确的日期!");
      return;
    }
    AjaxService.request('exam/video/room/list.htm', {exam_date:this.param.examDate /*exam_date : FrameService.shortDateString(new Date())*/ }, (data) => {
      var GroupArray = new Array();
				var RoomMap = {};
        _.each(data.array,(room)=>{
          let flag = false;
					for (let i = 0; i < GroupArray.length; i++) {
						if (GroupArray[i].ly_group_id == room.ly_group_id) {
							flag = true;
							break;
            }
           
          }
					if (!flag) {
            GroupArray.push(room);
						RoomMap['RoomArray_' + room.ly_group_id] = new Array();
					}
					RoomMap['RoomArray_' + room.ly_group_id].push(room);
        })
				this.GroupArray = GroupArray;
				this.RoomMap = RoomMap;
    });
  }

  changeGroup (event) {
		this.room = [];
		this.RoomArray = this.RoomMap['RoomArray_' + this.param.group.ly_group_id];
  }

  // 轮询评委
  repeatJudge () {
		this.changeRoom(false);
		if (this.repeat)
      setTimeout(() => {
        this.repeatJudge()
      }, 5000);
  }

  // 切换考场联动评委
  changeRoom (flag) {
		// if (this.curStep == 'Examing')
    //   return;
   
    AjaxService.request('exam/video/room/judge.htm', {room_id : this.param.room.ly_room_id, group_id : this.param.group.ly_group_id}, (data) => {
      if(data.map && data.map.JudgeArray) {
        this.JudgeArray = data.map.JudgeArray;
      }
        
        // test
        if(this.devMode == 'test'){
          _.each(this.JudgeArray,item=>{
            item.room_id = 123;
          })
        }
        this.ExRoomFace = data.map.ExRoomFace;
        this.param.score_batch = data.map.ScoreBatch;

        if (this.ExRoomFace && this.ExRoomFace.exam_status && this.ExRoomFace.exam_status == 'Init') {
          this.curStep = 'Init';
        }
        if (this.ExRoomFace && this.ExRoomFace.exam_status && this.ExRoomFace.exam_status == 'Judge') {
          this.repeat = true;
          this.curStep = 'Judge';
          if (flag)
            this.repeatJudge();
        }
        if (this.ExRoomFace && this.ExRoomFace.exam_status && this.ExRoomFace.exam_status == 'Examing') {
          this.repeat = false;
          if (this.curStep != 'Examing')
            this.curStep = 'Examing';
        }

    });
  }

  // 是否可播放视频
  judgeAllReady(){
     let allReady = true;
    _.each(this.JudgeArray,item=>{
      // 未登陆
      if(item.status == ''){
        allReady = false;
      }
    })
    
    return allReady;
  }

  startRoom () {
		for (let i = 0; i < this.JudgeArray.length; i++) {
			if (this.JudgeArray[i].judge_id == undefined)
				return;
    }

   let fn = function() {
   let url = "exam/video/room/start.htm";
   AjaxService.request(url, {room_id : this.param.room.room_id,json_value : JSON.stringify(this.JudgeArray)}, (data) => {
      	this.JudgeArray = data.array;
				this.curStep = 'Judge';
				this.repeat = true;
				this.repeatJudge();
        MsgService.successToastr('考场已开启，请评委们使用手机号码作为用户名，手机后四位为密码在iPad上登录！');
    }) 
   }

   MsgService.confirmAlert('确定要开启本考场吗？请仔细确认评委信息！',fn);
  }

  startVideo(tpl){
    this.tpl = tpl;
    this.nextGroupVideo(true);
  }

  initVideoPlayer(url?){
    let _this = this;
    this.bsModalWin = this.bsModalService.show(this.tpl, { class: 'modal-9p' , backdrop: 'static', keyboard: false});
    this.aliPlayer = aliPlayerUtil.init('aliPlayer',url);

    // 技术播放自动下一个
    this.aliPlayer.on("ended", function() {
      //console.log("skips out---->" + _this.gCurrIdx);
      //分组多个视频循环播放
      if (_this.gVideoList.length > 1 && _this.gCurrIdx <= _this.gVideoList.length - 1) {
        let v = _this.gVideoList[_this.gCurrIdx];
        aliPlayerUtil.changeSource(_this.aliPlayer, v['video_file']);
        _this.gCurrIdx ++;
        //是否需要快进
        try {
          let skips = parseInt(v["skip_face_secs"]) + parseInt(v["skip_prepare_secs"]);
          console.log(v);
          if (skips > 0) {
            _this.aliPlayer.seek(0);
            _this.aliPlayer.seek(skips);
          }
        } catch(e) {}
          return;
        }
      _this.nextGroupVideo();
    });
  }

  changeVideoSource(url){
    aliPlayerUtil.changeSource(this.aliPlayer,url);
  }

  hideModal(){
    if(this.bsModalWin){
      this.bsModalWin.hide();
      this.param.next_score_seq = -1;
    } 
  }

  pauseVideo(){
    aliPlayerUtil.pause(this.aliPlayer);
  }

  playVideo(){
    aliPlayerUtil.play(this.aliPlayer);
  }

  /*****************
   * 上一个考生视频
   */
  lastGroupVideo(){
    this.initRotate();
    if(this.param.last_score_seq == -1) return;
    this.param.next_score_seq--;
    this.param.cur_score_seq = (this.param.next_score_seq -1) ;
    this.param.last_score_seq = (this.param.cur_score_seq -1) ;

    AjaxService.requestArray('exam/video/room/list/video.htm', {
      real_exam_seq: this.param.next_score_seq,
      room_id: this.param.room.ly_room_id
    }, (data) => {
      if(data && data.length > 0) {
        this.gVideoList = data;
        aliPlayerUtil.changeSource(this.aliPlayer, data[0].video_file);
      }
    });
  }

  /********************
   *  下一个考生视频
   */
  nextGroupVideo(firstLoad?){
    let param = {
      real_exam_seq:this.param.next_score_seq,
      room_id : this.param.room.ly_room_id, 
      group_id : this.param.group.ly_group_id
    };
    // 第一次加载
    if (this.param.next_score_seq == -1) {
      param['next_flag'] = false;
    } else {
      param['next_flag'] = true;
      this.initRotate();
    }

    AjaxService.request('exam/video/room/std/next.htm', param, (data) => {
      let ex_video_list = data.map['ExVideoList'];
      this.VideoTotal = data.map['VideoTotal'];
      if(data.map['error_code'] == 'minVideoPlayLimit') {
        MsgService.errorToastr("当前视频播放时间不足，请继续观看视频！");
        return;
      }
      if (data.map['error_code'] == 'ExistNoScoreRecord') {
        MsgService.errorToastr("有评委未对当前视频评分，请等待评委评分后进行播放！");
        return;
      }
      if (data.map['error_code'] == 'ExceedSubmitLimit') {
        MsgService.errorToastr("评委未提交分数过多，请等待评委提交分数后进行播放！");
        return;
      }
      if (ex_video_list && ex_video_list.length > 0) {
        this.gCurrIdx = 0;
        this.gVideoList = ex_video_list;
        let ex_video = ex_video_list[0];
        
        this.param.next_score_seq = parseInt(ex_video['score_exam_seq']);
        this.param.cur_score_seq = (this.param.next_score_seq - 1) ;
        this.param.last_score_seq = (this.param.cur_score_seq - 1);

        this.videoArray.push(ex_video['video_file']);
        if (firstLoad) {
          this.initVideoPlayer();
        }
        aliPlayerUtil.changeSource(this.aliPlayer,ex_video['video_file']);
        this.gCurrIdx ++;
        //是否需要快进
        try {
          let skips = parseInt(ex_video["skip_face_secs"]) + parseInt(ex_video["skip_prepare_secs"]);
          if (skips > 0) {
            this.aliPlayer.seek(0);
            this.aliPlayer.seek(skips);
          }
        } catch(e) {}
      } else {
        MsgService.errorToastr("无下一个考生视频");
      }
      
    }, {RequestWithLoading: true});
  }

  //一分组对应多视频-播放指定科目的视频
  playSubjectVideo(v, obj, idx) {
    this.gCurrIdx = idx+1;
    this.gFormalVideo=true;
    aliPlayerUtil.changeSource(this.aliPlayer, v.video_file);
    //是否需要快进
    try {
      let skips = parseInt(v["skip_face_secs"]) + parseInt(v["skip_prepare_secs"]);
      if (skips > 0) {
        this.aliPlayer.seek(0);
        this.aliPlayer.seek(skips);
      }
    } catch(e) {}
   
  }

  playSubjectVideoRelated(v, obj, idx) {
    this.gCurrIdx = idx+1;
    this.gFormalVideo=false;
    aliPlayerUtil.changeSource(this.aliPlayer, v.video_file_related);
  }

  IsDate(str) {
    let arr = str.split("-");
    if (arr.length == 3) {
        let intYear = parseInt(arr[0], 10);
        let intMonth = parseInt(arr[1], 10);
        let intDay = parseInt(arr[2], 10);
        if (isNaN(intYear) || isNaN(intMonth) || isNaN(intDay)) {
            return false;
        }
        if (intYear > 2100 || intYear < 1900 || intMonth > 12 || intMonth < 0 || intDay > 31 || intDay < 0) {
            return false;
        }
        if ((intMonth == 4 || intMonth == 6 || intMonth == 9 || intMonth == 11) && intDay > 30) {
            return false;
        }
        if (intYear % 100 == 0 && intYear % 400 || intYear % 100 && intYear % 4 == 0) {
        } else {
        }
        return true;
    }
    return false;
  }
 
  /***
   * 旋转-默认旋转90度
   */
  // rotate() {
  //   let rot = this.aliPlayer.getRotate();
  //   //视频垂直，要设置高度
  //   if(rot == 90 || rot == 270) {
  //     //视频的高度，超过了限制，如何设置高度 TODO
      
  //   }
  //   if(rot+90 == 360) {
  //     this.aliPlayer.setRotate(0);
  //   } else  {
  //     this.aliPlayer.setRotate(rot + 90);
  //   }
  // }

    rotate() {
      this.vrotate++;
      if(this.vrotate == 1) {
        document.getElementById('aliPlayer').style.transform = 'rotate(90deg)';
      } else if(this.vrotate == 2) {
        document.getElementById('aliPlayer').style.transform = 'rotate(180deg)';
      } else if(this.vrotate == 3) {
        document.getElementById('aliPlayer').style.transform = 'rotate(270deg)';
      } else if(this.vrotate == 4) {
        document.getElementById('aliPlayer').style.transform = 'rotate(360deg)';
        this.vrotate = 0;
      }
    }

    initRotate() {
      document.getElementById('aliPlayer').style.transform = 'rotate(360deg)';
      this.vrotate = 0;
    }

     //初始化时间控件
  getDate() {
    setTimeout(() => {
      laydate.render({
        elem:'#examDate',
        type:'date',
        theme:'#0c6acf',
        trigger: 'click',
        done:(value, date, endDate)=>{
          this.param.examDate = value;
          this.init();
        }
      });
    }, 10);
  }
}
