let tokens;
let start = [];

function hint() {
    layer.msg('视频播放失败，请检查网络！！！', {
        icon: 2,
        time: 2000 //2秒关闭（如果不配置，默认是3秒）
    });
}

// 执行一次函数的定时器
let time = setTimeout(hint, 1000 * 30);

// $(function () {
//     if (isNumber(puId)) {
//         createVideo();
//         connect();
//     } else {
//         alert("puId错误!!!")
//     }
// });

/**
 * post 请求
 * @param router
 * @param params
 * @param callback
 */
function requestPost(router, params, callback) {
    $.ajax({
        type: 'post',
        url: _cf.q2http_url + router,
        data: params,
        traditional: true,
        dataType: 'json',
        async: false,
        complete: function (rv) {
            $('#hint').show();
            setTimeout(" $('#hint').hide();", 3000);
            if (typeof callback == 'function') callback(rv)
        }
    })
}

/**
 * 创建平台连接
 */
function connect() {
	var allDataParams="address="+_cf.connParams.address+"&port="+_cf.connParams.port+
	"&user="+ _cf.connParams.user+"&password="+_cf.connParams.password+"&epid="+_cf.connParams.epid+"&fixaddr="+_cf.connParams.bfix;
	let params = {
	    "params":videoEncrypt(allDataParams)
	}
	console.log(params)
    requestPost('login2', params, function (rv) {
        let result = {
            errcode: -1,
            token: ''
        }
        let respJSON = JSON.parse(rv.responseText);
        if (respJSON.hasOwnProperty('errcode')) {
            result.errcode = respJSON.errcode;
        }
        if (respJSON.hasOwnProperty('token')) {
            result.token = respJSON.token;
            result.errcode = 0;
            tokens = result.token;
            if (!isEmpty(tokens)) {
                playVideo(puId, "0");
            }else{
				  alert("平台登录失败!!!")
			}
        }
    });


}

/**
 *  播放视频
 * @param puId
 * @param idx
 */
function playVideo(puId, idx) {
    //播视频接口
    let url = _cf.q2http_url + "stream.flv?puid=" + puId + "&idx=" + idx + "&stream=0&token=" + tokens;
	if (flvjs.isSupported()) {
        let videoElement = document.getElementById('video_html5_api');
		        // fullScreenOfAndroid();  
		 flvPlayer = flvjs.createPlayer({
		    type: 'flv',
		    url: url,
		    isLive: true,
		    hasAudio: false
		}, {
		    enableWorker: false,
		    autoCleanupSourceBuffer: true, //清理缓冲区
		    enableStashBuffer: false,
		    stashInitialSize: 128, // 减少首桢显示等待时长
		    statisticsInfoReportInterval: 600
		});
        flvPlayer.attachMediaElement(videoElement);
        flvPlayer.load();
    }else if(typeof(flvjs.isSupported())=='undefined'){
		 let videoElement = document.getElementById('video_html5_api');
		flvPlayer = flvjs.createPlayer({
		    type: 'mp4',
		    url: url,
		    isLive: true,
		    hasAudio: false
		}, {
		    enableWorker: false,
		    autoCleanupSourceBuffer: true, //清理缓冲区
		    enableStashBuffer: false,
		    stashInitialSize: 128, // 减少首桢显示等待时长
		    statisticsInfoReportInterval: 600
		});
		 flvPlayer.attachMediaElement(videoElement);
		 flvPlayer.load();
	}else{
		let videoElement = document.getElementById('video_html5_api');
		flvPlayer = flvjs.createPlayer({
		    type: 'fly',
		    url: url,
		    isLive: true,
		    hasAudio: false
		}, {
		    enableWorker: false,
		    autoCleanupSourceBuffer: true, //清理缓冲区
		    enableStashBuffer: false,
		    stashInitialSize: 128, // 减少首桢显示等待时长
		    statisticsInfoReportInterval: 600
		});
		flvPlayer.attachMediaElement(videoElement);
		flvPlayer.load();
	}
		flvPlayer.on(flvjs.Events.STATISTICS_INFO, (res) => {
			if (this.leaveRouter || this.changeLampPost) { // 离开路由或切换设备
				destoryVideo(flvPlayer);
			}
		});
}

function createVideo() {
	
    let play = videojs('video', {
        muted: true,
        controls: false,
        loop: true,
        preload: "auto",
        autoplay: true,
    });
    play.play();
    $('.vjs-loading-spinner').hide();
    $('.vjs-big-play-button').hide();
    $('.vjs-poster').removeAttr("class");
    var elevideo = document.getElementById("video_html5_api");
    elevideo.addEventListener('play', function () { //播放开始执行的函数
        console.log(time);
        clearTimeout(time);
    });
}

// Android平台的视频全屏旋转  
/* var fullScreenOfAndroid = function() {  
         if(true) {  
        // 最新5+API的支持  
        var self = plus.webview.currentWebview();  
        self.setStyle({  
            videoFullscreen: 'landscape'  
        });  
    } else {  
                 document.addEventListener('webkitfullscreenchange', function() {  
                    var el = document.webkitFullscreenElement; //获取全屏元素  
                    if(el) {  
                        plus.screen.lockOrientation('landscape'); //锁死屏幕方向为横屏  
                    } else {  
                        plus.screen.lockOrientation('portrait-primary'); //锁死屏幕方向为竖屏  
                    }  
                });  
        }  
}; */
function shot() {
    screenshot($('#video_html5_api'));
}
/**
 * 销毁断流方法
 * @param flvPlayer
 */
function destoryVideo(flvPlayer) {
		if(flvPlayer!=null){
			flvPlayer.destroy();
			flvPlayer.unload();
			flvPlayer.detachMediaElement();
		}
}
//缩放功能
function zoomcontrol(option) {
    let params = {
        puid: puId,
        idx: "0"
    }
    switch (option) {
        case "stop":
            //停止缩放接口
            requestPost('PTZ/C_PTZ_StopPictureZoom?token=' + tokens, params, rv => {
            })
            break;
        case "zoomin":
            //放大图像接口
            requestPost('PTZ/C_PTZ_ZoomInPicture?token=' + tokens, params, rv => {
            })
            break;
        default:
            //缩小图像接口
            requestPost('PTZ/C_PTZ_ZoomOutPicture?token=' + tokens, params, rv => {
            })
            break;
    }
}

//远近焦点功能
function focuscontrol(option) {
    let params = {
        puid: puId,
        idx: "0"
    }
    switch (option) {
        case "near":
            requestPost('PTZ/C_PTZ_MakeFocusNear?token=' + tokens, params, rv => {
                console.log(rv)
            })
            break;
        case "faraway":
            requestPost('PTZ/C_PTZ_MakeFocusFar?token=' + tokens, params, rv => {
                console.log(rv)
            })
            break;
        default:
            requestPost('PTZ/C_PTZ_StopFocusMove?token=' + tokens, params, rv => {
                console.log(rv)
            })
            break;
    }
}

function aperture(option) {
    let camera = {
        puid: puId,
        idx: "0"
    };
    let xml = "";
    switch (option) {
        case "augment":
            xml = `<?xml version="1.0" encoding="UTF-8"?>
                        <M Type="ComReq">
                            <C Type="G" Prio="1" EPID="${_cf.connParams.epid}" Lang="zh_CN">
                                <Res Type="IV" Idx="${camera.idx}" OptID="C_PTZ_AugmentAperture" Stream="0"><Param></Param></Res>
                            </C>
                        </M>`;
            requestPost(`RawRequest?dstType=201&dstID=${camera.puid}&token=${tokens}`, {xml: xml}, rv => {
                console.log(rv);
            });
            break;
        case "minish":
            xml = `<?xml version="1.0" encoding="UTF-8"?>
                        <M Type="ComReq">
                            <C Type="G" Prio="1" EPID="${_cf.connParams.epid}" Lang="zh_CN">
                                <Res Type="IV" Idx="${camera.idx}" OptID="C_PTZ_MinishAperture" Stream="0"><Param></Param></Res>
                            </C>
                        </M>`;
            requestPost(`RawRequest?dstType=201&dstID=${camera.puid}&token=${tokens}`, {xml: xml}, rv => {
                console.log(rv)
            });
            break;
        default:
            xml = `<?xml version="1.0" encoding="UTF-8"?>
                        <M Type="ComReq">
                            <C Type="G" Prio="1" EPID="${_cf.connParams.epid}" Lang="zh_CN">
                                <Res Type="IV" Idx="${camera.idx}" OptID="C_PTZ_StopApertureZoom" Stream="0"><Param></Param></Res>
                            </C>
                        </M>`;
            requestPost(`RawRequest?dstType=201&dstID=${camera.puid}&token=${tokens}`, {xml: xml}, rv => {
                console.log(rv);
            });
            break;
    }
}

//旋转平台功能
async function turncontrol(option) {
    let params = {
        puid: puId,
        idx: "0",
        motion: option
    };
    if (!isEmpty(option)) {
        requestPost('PTZ/C_PTZ_Turn?token=' + tokens, params, (rv) => {
        });
    }
}

function control(key) {
    switch (key) {
        case 0:
            turncontrol('stop');
            break;
        case 1:
            turncontrol('up');
            break;
        case 2:
            turncontrol('down');
            break;
        case 3:
            turncontrol('left');
            break;
        case 4:
            turncontrol('right');
            break;
        case 5:
            zoomcontrol('zoomin');
            break;
        case 6:
            zoomcontrol('zoominout');
            break;
        case 7:
            focuscontrol('near');
            break;
        case 8:
            focuscontrol('faraway');
            break;
        case 9:
            zoomcontrol('stop');
            break;
        case 10:
            focuscontrol('stop');
            break;
        default:
            break;
    }

}
