import zlplayer from '';

let webServer = {
    host: 'localhost',
    port: 7890
}

let isLive = true;          //是否为实时视频

zlplayer.resPath = '';

//去后端获取预览视频地址
function getRealUrlByToken() {
    isLive = true;
    let elevatorSn = document.getElementById('elevatorSn').value;
    let xhr = new XMLHttpRequest();
    let reqUrl = `http://${webServer.host}:${webServer.port}/getElevatorMonitolUrlByToken?elevatorSn=${elevatorSn}`;
    xhr.open('GET', reqUrl, false);
    xhr.send();
    if (xhr.status == 200) {
        let res = JSON.parse(xhr.responseText);
        if (res && res.monitorUrl) {
            document.getElementById('url').value = res.monitorUrl;
        }
        return;
    }
    console.error(`getElevatorMonitolUrl error ${xhr.status}`);
}


//去后端获取报警录像地址
function getAlarmRecordUrlByToken() {
    isLive = false;
    let elevatorSn = document.getElementById('elevatorSn').value;
    let alarmId = document.getElementById('alarmId').value;
    let xhr = new XMLHttpRequest();
    let reqUrl = `http://${webServer.host}:${webServer.port}/getAlarmRecordUrlByToken?elevatorSn=${elevatorSn}&alarmId=${alarmId}`;
    xhr.open('GET', reqUrl, false);
    xhr.send();
    if (xhr.status == 200) {
        let res = JSON.parse(xhr.responseText);
        if (res && res.recordUrl) {
            document.getElementById('url').value = res.recordUrl;
        }
        return;
    }
    console.error(`getAlarmRecordUrlByToken error ${xhr.status}`);
}

//去后端获取视频地址
function getTimeRecordUrlByToken() {
    isLive = false;
    let elevatorSn = document.getElementById('elevatorSn').value;
    let beginTime = parseInt(document.getElementById('beginTime').value);
    let endTime = parseInt(document.getElementById('endTime').value);
    let xhr = new XMLHttpRequest();
    let reqUrl = `http://${webServer.host}:${webServer.port}/getElevatorRecordUrlByToken?elevatorSn=${elevatorSn}&beginTime=${beginTime}&endTime=${endTime}`;
    xhr.open('GET', reqUrl, false);
    xhr.send();
    if (xhr.status == 200) {
        let res = JSON.parse(xhr.responseText);
        if (res && res.recordUrl) {
            document.getElementById('url').value = res.recordUrl;
        }
        return;
    }
    console.error(`getTimeRecordUrlByToken error ${xhr.status}`);
}

let player = null;

//开始播放
function startPlay() {
    stopPlay();

    let videoElement = document.getElementById('myvideo');
    let urlElement = document.getElementById("url");

    let config = {
        url: urlElement.value,                   //资源地址
        isLive: isLive,                          //实时预览：true ， 回放：false
        enableFullScreen: true,                  //是否双击全屏
        enableFillWindow: true                   //是否视频铺满窗口
    };

    player = zlplayer.createPlayer(videoElement, config);
    player.on('error', onPlayerError);
    player.play();
}

//停止播放
function stopPlay() {
    if ( player ) {
        player.stop();
        player = null;
    }
}

//抓图
function capture() {
    if (player) {

        let img = player.capture();            //抓图，返回image

        if (img) {
            let now = new Date();
            let filename = `capture_${now.toLocaleDateString()}_${now.toLocaleTimeString()}.png`;

            let save_link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
            save_link.href = img;
            save_link.download = filename;

            let event = document.createEvent('MouseEvents');
            event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
            save_link.dispatchEvent(event);
        }
    }
}

//开始录像
function startRecord() {
    if (player) {
        player.startRecord();
    }
}

//停止录像
function stopRecord() {
    if (player) {
        let blob = player.stopRecord();              //停止录像返回 blob
        if ( blob ) {
            let url = window.URL.createObjectURL(blob);
            let now = new Date();

            let filename = `record_${now.toLocaleDateString()}_${now.toLocaleTimeString()}.webm`;

            let a = document.createElement('a');
            a.style.display = 'none';
            a.href = url;
            a.download = filename;
            document.body.appendChild(a);
            a.click();
            setTimeout(function() {
                document.body.removeChild(a);
                window.URL.revokeObjectURL(url);
            }, 100);
        }
    }
}

//旋转视频
function rotate(deg) {
    if (player) {
        player.rotate(deg);
    }
}

//清理创建过的播放器
function clearPlayer() {
    zlplayer.clearPlayer();
}

//播放器错误event
function onPlayerError(type, reason, desc) {
    switch(type){
        case 'NetworkError':
            if ( desc.code == -1 ) {
                alert("网络错误");
            }
            else if ( desc.code == -999 ) {
                alert("网络错误， 流中断");

                let urlElement = document.getElementById("url");
                player.flvSrc.url = urlElement.value;    //这里应该是重新去获取新的url
                player.resume();
            }else if ( desc.code == 401 ) {
                console.log(`${desc.msg} : 鉴权失败`);
            }
            else if ( desc.code == 404 ) {
                alert("资源不存在, 设备不在线");
            };
            break;
        case 'MediaError':
            if ( reason == 'NeedReplay' ) {
                console.log("媒体异常，自动重新播放");

                let urlElement = document.getElementById("url");
                player.flvSrc.url = urlElement.value;    //这里应该是重新去获取新的url
                player.resume();
            };
            break;
    }
}
