// import Toasted from 'vue-toasted';

var PLAY = "Play";
var PAUSE = "Pause";


var ispringPresentationConnector = {};
var playbackController;

var slidesCount;
var isPlayedPresentation;
var docWithBoard = {};
var curDocIndex;
var curBoarddata;
var curApp;
var subVideoConponent = null;
var subVideoCanvas = null;
var isPlaying = true;
var lastVideoPos = -1;


jsonData = {}
jsonData["user_id"] = g_data.userId;
jsonData["time"] = new Date().getMilliseconds();
jsonData["type"] = "Doc_H5";
jsonData["role"] = "teacher";
jsonData["seq"] = 0;


var boardData = {
  data: {
    current: null,
    list: []
  },
  page: {
    current: 0,
    total: 0
  }
};

// Vue.use(Toasted);
// 初始化白板
function initBoardSdk() {

  $('#board_iframe').attr('src', `../web-content/index-electron.html#/${g_data.sdkAppId}/${g_data.classId}/${g_data.userId}/${g_data.userSig}/${g_data.token}?t=${Date.now()}`);
  // $('#board_iframe').attr('src', `../web-content/index-electron.html#/${g_data.classId}/${g_data.sdkAppId}/${g_data.userId}/${g_data.userSig}/${g_data.token}?t=${Date.now()}`);
  $('#board_iframe').get(0).onload = function () {
    //g_data.classInfo["custom_datas"] = g_data.classInfo.custom_data;
    // log.info("[TAG-CLASS] initBoardSdk setdata classInfo : " + JSON.stringify(g_data.classInfo));
    log.info("[TAG-CONTAINER] initBoardSdk data : " + JSON.stringify(g_data.classInfo))
    curApp = document.getElementById('board_iframe').contentWindow.initApp(g_data.classInfo);

    if ('ing' == g_data.classInfo.class_status) {
      curApp.start();
    }
    curApp.renderIM();
    reportTime();
  }

}



// 收到控制消息
ipcRenderer.on('recv-ctrlmsg', (e, data) => {
  log.info("[TAG-CLASS] [TAG-BOARD]recv-ctrlmsg->data: " + data);
  var recvObj = JSON.parse(data);
  if (recvObj.user_id != g_data.userId) {
    if (recvObj.type == "Doc_H5") {
      if (recvObj.data.action == "page_next") {
        playbackController.gotoNextSlide();
      }
      if (recvObj.data.action == "page_prev") {
        playbackController.gotoPreviousSlide();
      }
      if (recvObj.data.action == "content_hide") {
        if (recvObj.data.content == "whiteboard") {
          $("#board").hide();
        }
      }
      if (recvObj.data.action == "content_show") {
        if (recvObj.data.content == "whiteboard") {
          $('#board .tic_board_bg').addClass('opacity_bg')
          $("#board").show();
        }
      }
    }
  }
})

function proBoardData(data) {
  boardData.data.current = data.current;
  boardData.data.list = data.list;
  boardData.page = {
    current: boardData.data.list.indexOf(data.current) + 1,
    total: boardData.data.list.length
  }
  $("#slide-index").html("当前页: " + (this.boardData.page.current) + " 总页数： " + this.boardData.page.total);
}


function uploadFile() {
  // alert("uploadFile");
  // debugger
  var file = document.getElementById('file_input').files[0];
  var boardSdk = document.getElementById('board_iframe').contentWindow.boardSDK;
  // this.showTip('文件正在上传，请等待');
  boardSdk.addFile(file, (total, data) => {
    // this.showTip('文件上传成功，共' + total + '页
    document.getElementById('file_input').value = '';
  }, (err) => {
    console.error(err);
    // this.showErrorTip('文件上传失败，请重试');
    document.getElementById('file_input').value = '';
  });

}

function addClassDoc(doc) {
  // log.info("[TAG-CLASS] [TAG-BOARD]  addClassDoc->add doc: " + url + ", pages: " + size);
  var comWin = document.getElementById('board_iframe').contentWindow;
  log.info("[TAG-CLASS] [TAG-BOARD]  addClassDoc->add doc: " + JSON.stringify(doc));
  comWin.addFile(doc);
  //let files = boardSdk.getFileInfoList();
  //for (let i = 0; i < files.length; ++i) {
  //  if (files[i].downloadURL === url) {
  //    classroom_app.showAlertMsg("同一个文件只能添加一次");
  //    return;
  //  }
  //}
  //if (url.substr(-4) == "html") {
  //  boardSdk.addH5PPTFile(url);
  //}else if (url.substr(-1) == "/"){
  //  boardSdk.addTransCodeFile({
  //   name: name,
  //   width: width,
  //   height: height,
  //   url: url,
  //   pageCount: size
  // });
  //} else {
  //  boardSdk.addFile(url);
  //}
}


function sendChannel(type, data) {
  log.info("sendChannel text: " + data + "  type " + type);
  var ext;
  if (type == "CHAT") {
    if (g_data.sendMsg) {
      //文本聊天消息
      sendTextMessage(g_data.classInfo.chat_group_id, data);
    } else {
      showAlertMsg("您已被禁言!");
    }
  } else if (type == "Ctrl") {
    //控制信令
    ext = "CTRL";
    sendCustomMessage(g_data.classInfo.cmd_group_id, data, ext);
  } else if (type == "BOARD") {
    //白板数据
    ext = "TXWhiteBoardExt";
    sendCustomMessage(g_data.classInfo.cmd_group_id, data, ext);
  } else if (type == "CONTAINER") {
    //容器数据
    log.info("sendChannel [TAG-CONTAINER]  data : " + data + "  type " + type);
    ext = "CONTAINER";
    sendCustomMessage(g_data.classInfo.cmd_group_id, data, ext);
  }else if (type == "TRTC") {
    //容器数据
    log.info("sendChannel TRTC data : " + data + "  type " + type);
    liteav.sendCustomCmdMsg(parseInt(data),"test",true,true);
  }
}

function initVideoStyle(componentDom) {
  //var canvas = componentDom.getElementsByClassName('canvas_video')[0];

  var videoControl = componentDom.getElementsByClassName('video_control')[0];
  videoControl.style.position = 'relative';
  videoControl.style.top = '-50px';
  videoControl.style.width = "100%";
  videoControl.style.height = "50px";
  videoControl.style.backgroundColor = "#000";
  videoControl.style.textAlign = 'left';
  videoControl.style.opacity="0";

  componentDom.addEventListener('mouseenter', function(){
    videoControl.style.opacity="1";
  })
  componentDom.addEventListener('mouseleave', function(){
    videoControl.style.opacity="0";
  })

  var videoBtn = componentDom.getElementsByClassName('video_play')[0];
  videoBtn.style.position = 'relative';
  videoBtn.style.verticalAlign = 'top';
  videoBtn.style.top = '-5px';
  videoBtn.style.marginLeft = '30px';
  videoBtn.style.marginRight = '30px';
  videoBtn.onclick = function () {
    if (isPlaying) {
      pausePlayVideo();
      videoBtn.setAttribute("src", "../img/video_play.png");
    } else {
      resumePlayVideo();
      videoBtn.setAttribute("src", "../img/video_pause.png");
    }
    isPlaying = !isPlaying;
  }

  var videoInfo = componentDom.getElementsByClassName('video_info')[0];
  videoInfo.style.position = 'relative';
  videoInfo.style.top = '-1px';
  videoInfo.style.marginLeft = "5px";
  videoInfo.style.marginRight = "5px";
  videoInfo.style.marginTop = "5px";
  videoInfo.style.color = "#FFF";
  videoInfo.style.fontSize = "12px";

  var videoSeek = componentDom.getElementsByClassName('video_seek')[0];
  videoSeek.style.width = "calc(100% + 20px)";
  videoSeek.style.verticalAlign = "top";
  videoSeek.style.left = "-10px";
  videoSeek.style.right = "-10px";
}

function getTimeInfo(seconds) {
  var mins = Math.floor(seconds / 60);
  var secs = Math.floor(seconds % 60);
  return (mins > 9 ? mins : '0' + mins) + ':' + (secs > 9 ? secs : '0' + secs);
}

function setVideoLength(pos, total) {
  //log.info("[XX] setVideoLength->length: "+pos+"/"+total);
  try {
    if (pos == 0 && total == 0) {
      isPlaying = false;
      var videoBtn = subVideoConponent.$content.getElementsByClassName('video_play')[0];
      videoBtn.setAttribute("src", "../img/video_play.png");
    }else if (pos == 0 && total != 0){
      isPlaying = true;
      var videoBtn = subVideoConponent.$content.getElementsByClassName('video_play')[0];
      videoBtn.setAttribute("src", "../img/video_pause.png");
    }
    if (pos != 0 && pos != total && Math.abs(pos - lastVideoPos) < 1000)
      return;
    lastVideoPos = pos;
    var videoSeek = subVideoConponent.$content.getElementsByClassName('video_seek')[0];
    var videoInfo = subVideoConponent.$content.getElementsByClassName('video_info')[0];
    var posSecs = pos / 1000;
    var totalSecs = total / 1000;
    videoInfo.textContent = getTimeInfo(posSecs) + " / " + getTimeInfo(totalSecs);
    if (0 == videoSeek.max) {
      videoSeek.min = 0;
      videoSeek.max = totalSecs;
      videoSeek.addEventListener('input', function () {
        log.info("[TAG-BOARD] setVideoPos: " + (this.value));
        $(this).css('background', 'linear-gradient(to right, #0A818C ' + (this.value * 100 / this.max) + '%, #737882 1%, #737882)');
        setVideoPos(this.value * 1000);
      });
    }else if (videoSeek.max != totalSecs){
      videoSeek.max = totalSecs;
    }
    videoSeek.value = posSecs;
    $(videoSeek).css('background', 'linear-gradient(to right, #0A818C ' + (videoSeek.value * 100 / videoSeek.max) + '%, #737882 1%, #737882)');
  } catch (err) {
    log.error("[TAG-BOARD] setVideoLength->err: " + err);
  }
}

function addVideoFrame(name, id, needControl = false) {
  var component = curApp.container.getNodes().find((item) => {
    log.info("[TAG-CONTAINER]  addVideoFrame: " + component + " item.type " + item.type);
    return item.type == 'videoCtn' && item.action != 'remove';
  });
  if (null != subVideoConponent) {
    subVideoConponent.remove();
  } else if (typeof (component) != 'undefined') {
    component.remove();
  }
  subVideoConponent = curApp.container.createNode({
    title: name,
    width: '400px',
    height: '300px',
    left: '10px',
    top: '10px',
    background: '#fff',
    type: 'videoCtn',
    present: true
  })

  // subVideoConponent.show();

  subVideoConponent.on("close", function () {
    subVideoConponent.remove()
  })

  subVideoConponent.on("remove", function (e, data) {
    log.info("[TAG-CONTAINER] teacher conponent removed");
    g_data.subvideo = false;
    stopPlayVideo();
    stopScreenShare();
    subVideoConponent = null;
  });

  if (needControl) {
    subVideoConponent.$content.innerHTML =
      '<canvas class="canvas_video" style="width:100%; height:100%;background-color:black;"></canvas>'
      + '<div class="video_control">'
      + '<input type="range" class="video_seek" value="0" /><br /><img class="video_play" src="../img/video_pause.png" /><span id="video_pos" class="video_info">00:00/00:00</span>'
      + '</div>';
    initVideoStyle(subVideoConponent.$content);
  } else {
    subVideoConponent.$content.innerHTML = '<canvas class="canvas_video" style="width:100%; height:100%;background-color:black;"></canvas>';
  }

  subVideoCanvas = subVideoConponent.$content.getElementsByClassName('canvas_video')[0];
  log.info("[XX][TAG-CONTAINER]  addVideoFrame->add sub video for " + id + ", control: " + needControl);
}

function removeVideoFrame() {
  subVideoConponent.remove();
  subVideoConponent = null;
}

function getSubVideoCanvas() {
  if (null == subVideoCanvas) {
    var component = curApp.container.getNodes().find((item) => {
      log.info("[XX][TAG-CONTAINER]  find Nodes type :" + item.type);
      return item.type == 'videoCtn' && item.action != 'remove';
    });
    if (typeof (component) != 'undefined') {
      component.show();
      component.$content.innerHTML =
        '<canvas class="canvas_video" style="width:100%; height:100%;background-color:black;"></canvas>'
      subVideoCanvas = component.$content.getElementsByClassName('canvas_video')[0];
      component.on("remove", function (e, data) {
        log.info("[TAG-BOARD] [TAG-CONTAINER] studeng conponent removed");
        g_data.subvideo = false;
        subVideoConponent = null;
        subVideoCanvas = null;
      });
    } else {
      log.info("[XX] [TAG-CONTAINER] getSubVideoCanvas->node not found");
    }
  }
  return subVideoCanvas;
}

window.sendChannel = sendChannel;
