import {Component, OnDestroy, OnInit} from '@angular/core';
import {BsModalService} from 'ngx-bootstrap/modal';
import {FramePageComponent} from '../../../../frame/core/page/frame.page';

declare var aliPlayerUtil: any;

@Component({
  selector: 'app-video',
  templateUrl: './video.component.html',
  styleUrls: ['./video.component.scss']
})
export class VideoComponent extends FramePageComponent implements OnInit, OnDestroy {

  currentStep = 'Init';
  inroom: any;
  currentRoom: any;
  room_key: any;
  timeArr = [];
  judgeArr = [];
  initRoom: any;
  currentStd = [];
  infoStdArray = [];
  totalRoom: any;
  cert_id: any;
  pause: boolean = false;
  real_exam_seq = 0;
  recCount = 0;
  gCurrIdx: number;

  private intervalId: any;
  private aliPlayer: any;

  private scoreIntervalId: any;
  canPlayLastVideo = "InActive";
  roomTotal = 0;
  subCount = 1;
  //第二机位
  video_relate_url = '';
  lyGroupParam: any;


  constructor(modalService: BsModalService) {
    super(modalService);
    this.inroom = {};
  }


  ngOnInit(): void {
  }


  //初始化
  goInit() {
    this.room_key = '';
    this.inroom = {};
    this.initRoom = {};
    this.judgeArr = [];
    this.timeArr = [];
    this.infoStdArray = [];
    this.currentRoom = {};
    this.currentStd = [];
    this.totalRoom = {};
    this.currentStep = 'Init';
    this.real_exam_seq = 0;
    clearTimeout(this.intervalId);
    clearTimeout(this.scoreIntervalId);
    this.canPlayLastVideo = "InActive";
    this.roomTotal = 0;
    this.recCount = 0;
    this.gCurrIdx = 0;
    //this.aliPlayer=null;
    aliPlayerUtil.dispose(this.aliPlayer)

  }

  //根据密钥-查找考场相关信息
  changeRoomKey() {
    if (this['room_key'] === undefined || $.trim(this['room_key']).length === 0)
      return;
    this.AjaxService.requestEntity('ly/room/interview/find.htm', {room_key: this.room_key}, (entity) => {
      this.initRoom = entity;
      this.currentRoom = entity.room;
      //this.score = this.initRoom.group.room_judge_num;
      this.inroom.ly_room_id = this.currentRoom.ly_room_id;
      this.timeArr = entity.timeArr;
      this.currentStep = 'Confirm';
      this.checkRoomStatus();
    }, {
      MsgType: 'Swal'
    });
  }

  //检测考场评委的状态
  checkRoomStatus() {
    if (this.currentRoom.exam_status === 'Judge') {
      this.checkJudgeLogin();
      // 等待评委登陆
      this.intervalId = setInterval(this.checkJudgeLogin.bind(this), 5000);
    }
  }


  //检查评委是否登录
  checkJudgeLogin() {
    this.AjaxService.requestEntity('ly/room/interview/judge/list.htm', {ly_room_id: this.currentRoom.ly_room_id}, (entity) => {
      this.currentRoom = entity.room;
      this.judgeArr = entity.judgeArr;
      //alert(this.currentRoom.exam_status);
      if (this.currentRoom.exam_status !== 'Judge') {
        clearTimeout(this.intervalId);
      }

      this.checkRommStatusByJudges(this.judgeArr);
    });
  }

  //检查所有评委登陆状态 更新考场状态
  checkRommStatusByJudges(judgeArray) {
    let isJudgesAllLogin = true;
    for (let i = 0; i < judgeArray.length; i++) {
      const item = judgeArray[i];
      //未登陆
      if (item.judge_status === 'Init') {
        isJudgesAllLogin = false;
      }
    }
    if (isJudgesAllLogin == true) {
      this.currentRoom.exam_status = 'Examing';
    }
  }

//开启考场
  startRoom() {
    if (this.timeArr !== undefined && this.timeArr.length > 0 && this.inroom.time_type === undefined) {
      this.MsgService.errorToastr('请选择面试时段！');
      return;
    }
    this.AjaxService.requestEntity('ly/room/interview/start.htm', {ly_room_id: this.currentRoom.ly_room_id}, (entity) => {
      this.currentRoom = entity;
      this.checkRoomStatus();
    }, {
      RequestWithLoading: true
    });
  }


//考生进场

  // private getLastButtonConf() {
  //   this.AjaxService.requestEntity('exam/video/room/exparam.htm', {
  //     school_id: this.currentRoom.school_id,
  //     paramName: "CanPlayLastVideo"
  //   }, (entity) => {
  //     this.canPlayLastVideo = entity;
  //   });
  // }
  stdInRoom(std, fc) {
    // 判断
    const fn = () => {
      this.inroom.requesting = true;
      this.AjaxService.requestArray('exam/video/room/std/inroom.htm',
        {ly_room_id: this.currentRoom.ly_room_id, std_id: std[0].std_id}, () => {
          this.totalRoom.real_inroom_total++;
          fc.call();
        }, {
          ErrorCallback: (response) => {
            if (response.errorMsg == '该考生已经进入过面试考场！') {
              fc.call();
            }
          }
        }
      );

    };
    if (this.initRoom.group.pack_flag !== 'Active') {
      fn.call(this);
    } else {
      if (this.infoStdArray.length !== this.initRoom.group.pack_std_num) {
        this.MsgService.confirmAlert(`该类型考试默认每组【${this.initRoom.group.pack_std_num}】个考生，该组目前有【${this.infoStdArray.length}】个考生，确定本组按照此数量进场考试吗？`, fn);
      } else
        fn.call(this);
    }
  }

  inRoom() {
    if (this.timeArr !== undefined && this.timeArr.length > 0 && this.inroom.time_type === undefined) {
      this.MsgService.errorToastr('请选择面试时段！');
      return;
    }


    this.AjaxService.requestEntity('exam/video/room/exparam.htm', {
      school_id: this.currentRoom.school_id,
      paramName: "CanPlayLastVideo"
    }, (entity) => {
      this.canPlayLastVideo = entity;
    });
    this.AjaxService.requestEntity('exam/judge/group/param.htm', {
      ly_group_id: this.currentRoom.ly_group_id
    }, (entity) => {
      this.lyGroupParam = entity;
    });
    // 进入考场，获取之前排队的考生
    this.AjaxService.requestArray('ly/room/interview/inroom/std/list.htm', {ly_room_id: this.currentRoom.ly_room_id}, (array) => {
      this.infoStdArray = array;
      this.currentStep = 'Examing';
      this.getRoomTotal()
      this.intervalId = setInterval(this.getRoomTotal.bind(this), 20000);
      this.scoreIntervalId = setInterval(this.requestScore.bind(this), 5000);
    });
  }

  private getRoomTotal() {
    this.AjaxService.requestEntity('exam/video/room/std/total.htm', {
      ly_room_id: this.currentRoom.ly_room_id
    }, (entity) => {
      this.roomTotal = entity;
    });
    this.AjaxService.requestEntity('ly/room/interview/std/total.htm', this.inroom, (entity) => {
      this.totalRoom = entity;
      if (this.real_exam_seq == 0) {
        this.real_exam_seq = this.totalRoom.real_inroom_total;
        if (this.real_exam_seq > 0) {
          this.real_exam_seq--;
        }
        this.nextGroupVideo();
      }
    });

  }

  initVideoPlayer() {
    let _this = this;
    //_this.currentStd[0].video_file_url = "//player.alicdn.com/video/editor.mp4"
    this.aliPlayer = aliPlayerUtil.init('aliPlayer', _this.currentStd[0].video_file_url);
    //第二机位
    this.video_relate_url = _this.currentStd[0].video_file_related;
    this.aliPlayer.on("ready", function () {
      _this.aliPlayer.seek(_this.currentStd[_this.gCurrIdx].skip_face_secs ? parseInt(_this.currentStd[_this.gCurrIdx].skip_face_secs) : 0);
    });
    if (this.lyGroupParam.display_screen === 'InActive') {
      let el = this.aliPlayer.el();
      const div = document.createElement("div");
      div.style.backgroundColor = "#0b3a58";
      div.style.position = "absolute";
      div.style.width = "100%";
      div.style.height = "100%";
      div.style.zIndex = String(9);
      div.innerText = "仅认许播放音频";
      div.style.fontSize = "xxx-large";
      div.style.color = "#fff";
      div.style.textAlign = "center";
      el.appendChild(div)
    }


    // 技术播放自动下一个
    this.aliPlayer.on("ended", function () {
      //console.log("skips out---->" + _this.gCurrIdx);
      //分组多个视频循环播放
      if (_this.gCurrIdx < _this.currentStd.length - 1) {
        _this.gCurrIdx++;
        aliPlayerUtil.changeSource(_this.aliPlayer, _this.currentStd[_this.gCurrIdx].video_file_url);
        //第二机位
        _this.video_relate_url = _this.currentStd[_this.gCurrIdx].video_file_related;

      } else {
        // _this.nextGroupVideo();
      }

    });


  }


  //一分组对应多视频-播放指定科目的视频
  playSubjectVideo(v, obj, idx) {
    this.gCurrIdx = idx;
    aliPlayerUtil.changeSource(this.aliPlayer, v.video_file_url);
    //第二机位
    this.video_relate_url = v.video_file_related;
  }

  requestScore() {
    if (this.real_exam_seq == 0) return;
    let param = {
      real_exam_seq: this.real_exam_seq,
      room_id: this.currentRoom.ly_room_id,
    };
    this.AjaxService.requestMap('exam/video/room/std/score.htm', param, (map) => {
      this.recCount = map['recCount'];
      this.subCount = map['subCount'];
    });
  }


  /*****************
   * 上一个考生视频
   */
  lastGroupVideo() {
    if (this.real_exam_seq == 1) return;

    this.AjaxService.requestArray('exam/video/room/std/last.htm', {
      real_exam_seq: this.real_exam_seq - 1,
      room_id: this.currentRoom.ly_room_id
    }, (array) => {
      if (array) {
        // this.currentStd = entity;
        this.currentStd = array;
        this.real_exam_seq = this.currentStd[0].real_exam_seq;
        this.gCurrIdx = 0;
        aliPlayerUtil.changeSource(this.aliPlayer, this.currentStd[0].video_file_url);
        //第二机位
        this.video_relate_url = this.currentStd[0].video_file_related;
      }
    });
  }

  /********************
   *  下一个考生视频
   */
  nextGroupVideo() {
    let param = {
      real_exam_seq: this.real_exam_seq + 1,
      room_id: this.currentRoom.ly_room_id,
    };
    this.AjaxService.requestMap('exam/video/room/std/next.htm', param, (map) => {
      if (map['error_code'] == 'minVideoPlayLimit') {
        this.MsgService.errorToastr("视频播放时间过短，请继续观看视频！");
        return;
      }
      if (map['error_code'] == 'ExistNoScoreRecord') {
        this.MsgService.errorToastr("有评委未对当前视频进行评分，请等待评委评分后进行播放！");
        this.recCount = map['score'];
        return;
      }
      if (map['error_code'] == 'ExceedSubmitLimit') {
        this.MsgService.errorToastr("评委未提交分数超出限制，请等待评委提交分数后进行播放！");
        return;
      }
      if (map["videos"] != null && map["videos"].length > 0) {

        this.stdInRoom(map["videos"], () => {
          this.currentStd = map["videos"]
          this.real_exam_seq = this.currentStd[0].real_exam_seq;
          this.gCurrIdx = 0;
          if (!this.aliPlayer) {
            this.initVideoPlayer();
          } else {
            this.aliPlayer = aliPlayerUtil.changeSource(this.aliPlayer, this.currentStd[0].video_file_url);
            //第二机位
            this.video_relate_url = this.currentStd[0].video_file_related;
          }
        });

      } else {
        this.MsgService.errorToastr("无下一个考生");
      }

    }, {RequestWithLoading: true});
  }


  ngOnDestroy(): void {
    clearTimeout(this.intervalId);
    clearTimeout(this.scoreIntervalId);
  }

  //打开第二机位
  openSecondCamera() {
    if (this.video_relate_url) {
      window.open('../../../../../../s/assets/video/play.html?video_url=' + this.video_relate_url, '_blank');
    }
  }


}
