let dataUrl = "http://sgwpdm.ah.sgcc.com.cn/basfs/";
let puId = 201115203158708879 //new GetRequest().puid;
let token=new GetRequest().token;
console.log("token===="+token);
let type;
let connparam={};
let _cf ={
	ver:'debug',
	q2http_url: '',
	websocket_url:'',
	// - 配置登录参数
	connParams : {
		// - 登录平台IP
		address : "",
		port : "",
		// - 登录平台用户名
		user : "",
		// - 登录平台密码
		password :"",
		// - 登录平台企业ID
		epid : "",
		// - 登录平台是否通过网闸模式
		bfix :1
	}
}


export const initPlate = async () => {
    if (isNumber(puId)) {
        let num = puId.indexOf("15");
        type = num === 0 ? '1' : '2'
    } else {
         alert("puId错误!!!")
    }
    $.ajax({
        url: dataUrl + "proteam/api/ballrisk/getDeviceState?token="+token,
        type: "POST",
        data: {
            puid: encrypt(puId),
            type: encrypt(type)
        },
        success: function (data) {
			var configData=data.config;
			if(typeof(configData)!='undefined'){
				_cf.q2http_url=configData.q2httpUrl;
				_cf.websocket_url=configData.websocketUrl;
				_cf.connParams.address=configData.videoIp;
				_cf.connParams.port=configData.videoPort;
				_cf.connParams.user=configData.videoUser;
				_cf.connParams.password=configData.videoPassword;
				_cf.connParams.epid=configData.epid;
				_cf.connParams.bfix=configData.bfix*1;
			}else{
				_cf.q2http_url='http://220.248.250.3:29605/icvs2/';
				_cf.websocket_url='ws://220.248.250.3:29605/wss';
				_cf.connParams.address="10.138.219.3";
				_cf.connParams.port="29988";
				_cf.connParams.user="bns4";
				_cf.connParams.password="";
				_cf.connParams.epid="system";
				_cf.connParams.bfix=1;
			}
			console.log(_cf);
            introduce("videoQX.js")
            console.log(data);
            if (data.code === "1") {
                if (data.status !== "1") {
                    layer.msg("球机不在线", {
                        icon: 2,
                        time: 2000 //2秒关闭（如果不配置，默认是3秒）
                    });
                } else {
                }
            } else {
                layer.msg("服务链接异常", {
                    icon: 2,
                    time: 2000 //2秒关闭（如果不配置，默认是3秒）
                });
            }
        },
        error: function (error) {
			introduce("videoQX.js");
			_cf.q2http_url='http://220.248.250.31:29605/icvs2/';
			_cf.websocket_url='ws://220.248.250.31:29605/wss';
			_cf.connParams.address="10.138.219.3";
			_cf.connParams.port="29988";
			_cf.connParams.user="bns4";
			_cf.connParams.password="";
			_cf.connParams.epid="system";
			_cf.connParams.bfix=1;
            layer.msg('服务链接异常', {
                icon: 2,
                time: 2000 //2秒关闭（如果不配置，默认是3秒）
            });
        }
    });
    $('#return').on('click', function () {
        window.close();
        window.history.back(-1);
    });
    $('.div').height($('.div').width())
};


/***引入 js / css 文件
 @param {string}  url js/css文件路径
 @example: aui.import('js/aui.picker.js')
 @example: aui.import(['js/aui.picker.js', 'css/aui.picker.css'])
 */
function introduce(url) {
    switch (url.constructor) {
        case Array:
            for (const [index, item] of url.entries()) {
                creat(item);
            }
            break;
        case String:
            creat(url);
            break;
        default:
            break;
    }
}

function creat(file) {
    if (/^.+?\.js$/.test(file)) { //JS文件引入
        let script = document.createElement("script");
        script.setAttribute("type", "text/javascript");
        script.setAttribute("src", file);
        document.querySelector('head').appendChild(script);
    }
    if (/^.+?\.css$/.test(file)) { //CSS文件引入
        let css = document.createElement('link');
        css.rel = 'stylesheet';
        css.type = 'text/css';
        css.href = file;
        document.querySelector('head').appendChild(css);
    }
}

/**
 * 获取链接中的参数
 * @returns {Object}
 * @constructor
 */
function GetRequest() {
    let theRequest = {};
    let param = filterJS(location.hash); //获取url中"?"符后的字串
	if(param){
		param=param.substr(1);
		 params=param.split("&");
		for (var i = 0; i < params.length; i++) {
		  theRequest[params[i].split("=")[0]] = (params[i].split("=")[1]);
		}
		  return theRequest;
	}else{
		alert("请求参数异常");
	}
	 return theRequest;
}

/**
 * 判断字符是否为空的方法
 * @param obj
 * @returns {boolean}
 */
function isEmpty(obj) {
    if (typeof obj == "undefined" || obj == null || obj == "") {
        return true;
    } else {
        return false;
    }
}


function isNumber(val) {
    let regPos = /^\d+(\.\d+)?$/;
    if (regPos.test(val)) {
        return true;
    } else {
        return false;
    }
}

function screenshot(videos) {
    let image = new Image();
    let video = videos[0];
    let canvas = $('#canvas')[0];
    let ctx = canvas.getContext('2d');
    let H = window.innerHeight;
    let W = window.innerWidth;
    const pixelRatio = window.devicePixelRatio || 1;
    const backingStoreRatio = ctx.webkitBackingStorePixelRatio ||
        ctx.mozBackingStorePixelRatio ||
        ctx.msBackingStorePixelRatio ||
        ctx.oBackingStorePixelRatio ||
        ctx.backingStorePixelRatio || 1;
    const ratio = pixelRatio / backingStoreRatio;
    canvas.width = videos.width() * ratio;
    canvas.height = videos.height() * ratio;
    canvas.style.width = W + 'px';
    canvas.style.height = H + 'px';
    ctx.scale(ratio, ratio);
    ctx.drawImage(video, 0, 0, videos.width(), videos.height());  // 将video中的数据绘制到canvas里
    image.src = canvas.toDataURL('image/jpg')/*.replace('image/jpg', 'image/octet-stream')*/;
    popUps(image)

}
/**
 * @param {Object} param
 */
function filterJS(param){
    if(param==null ||param==""){
        return null;
    }
    var filteArr = 'script,alert,console';
    var splitArr = filteArr.split(',');
    for(var i=0;i<splitArr.length;i++){
        console.log(splitArr[i]);
        if(param.indexOf(splitArr[i])== -1){
            return param
        }else{
            return '*****';
        }
    }
}
function popUps(image) {
    let height = '30%';
    let width = '90%';
    layer.open({
        title: ['截屏(长按保存图片)', 'font-size:18px;align-items: center;'],
        type: 1,
        content: '<img src="' + image.src + '" width="100%" height="100%" alt="' + '" />',
        area: [width, height]
    });

}

function videoFullscreen() {
    window.open('video.html?puid=' + puId+"&token="+token, '_self');
}

$(document).ready(function(){
    let up = $('#up');
    let time;
    up.mousedown(function () {
        control(1);
        time = setInterval(function () {//启动内层定时器每隔30毫秒重复执行事件函数
            control(1);
        }, 1000);
    });
    up.mouseup(function () {
        clearInterval(time);
        setTimeout("control(0)", 1000);
    });
    let down = $('#down');
    down.mousedown(function () {
        control(2);
        time = setInterval(function () {//启动内层定时器每隔30毫秒重复执行事件函数
            control(2);
        }, 1000);
    });
    down.mouseup(function () {
        clearInterval(time);
        setTimeout("control(0)", 1000);
    });
    let left = $('#left');
    left.mousedown(function () {
        control(3);
        time = setInterval(function () {//启动内层定时器每隔30毫秒重复执行事件函数
            control(3);
        }, 1000);
    });
    left.mouseup(function () {
        clearInterval(time);
        setTimeout("control(0)", 1000);

    });
    let right = $('#right');
    right.mousedown(function () {
        control(4);
        time = setInterval(function () {//启动内层定时器每隔30毫秒重复执行事件函数
            control(4);
        }, 1000);
    });
    right.mouseup(function () {
        clearInterval(time);
        setTimeout("control(0)", 1000);
    });
    let zoomin = $('#zoomin');
    zoomin.mousedown(function () {
        control(5);
        time = setInterval(function () {//启动内层定时器每隔30毫秒重复执行事件函数
            control(5);
        }, 1000);
    });
    zoomin.mouseup(function () {
        clearInterval(time);
        setTimeout("control(9)", 1000);
    });
    let zoominout = $('#zoominout');
    zoominout.mousedown(function () {
        control(6);
        time = setInterval(function () {//启动内层定时器每隔30毫秒重复执行事件函数
            control(6);
        }, 1000);
    });
    zoominout.mouseup(function () {
        clearInterval(time);
        setTimeout("control(9)", 1000);
    });
    let near = $('#near');
    near.mousedown(function () {
        control(7);
        time = setInterval(function () {//启动内层定时器每隔30毫秒重复执行事件函数
            control(7);
        }, 1000);
    });
    near.mouseup(function () {
        clearInterval(time);
        setTimeout("control(10)", 1000);
    });
    let faraway = $('#faraway');
    faraway.mousedown(function () {
        control(8);
        time = setInterval(function () {//启动内层定时器每隔30毫秒重复执行事件函数
            control(8);
        }, 1000);
    });
    faraway.mouseup(function () {
        clearInterval(time);
        setTimeout("control(10)", 1000);
    });
});

function hintPopUps(str) {
    let height = '30%';
    let width = '90%';
    layer.open({
        title: ['提示', 'font-size:18px;align-items: center;'],
        type: 1,
        content: str,
        area: [width, height]
    });

}

