//接口地址
var apiUrl = "http://121.36.134.218:8010";

//组织code，获取token所用
var orgCode = "6038a10d-de0c-4a8c-951d-35342c5fbad8";

var tokenApi = "/core/auth/authByCode";

var videoIp = "";
var loginIp = "";
var currIp = "";
var lanIp = "";
var sysConfUrl = "/publics/sysconf/get";
var sysCode = "env-variable";

function getSysconf() {
	var sysConfParam = {
		code: sysCode
	};
	getData(sysConfUrl, sysConfParam).then(res => {

		var data = JSON.parse(res.conf.data);

		for (var i = 0; i < data.length; ++i) {
			if (data[i].key == "currIp") {
				currIp = data[i].val;
				sessionStorage.setItem("currIp", data[i].val);
				continue;
			}
			if (data[i].key == "lanIp") {
				lanIp = data[i].val
				sessionStorage.setItem("lanIp", data[i].val);
				continue;
			}
		}

	})
}
getSysconf()
//刷新IP
var t1 = setInterval(getSysconf, 30000);

function getToken() {

	$.ajax({
		type: "POST",
		url: apiUrl + tokenApi,
		data: {
			code: orgCode
		},
		dataType: "json",
		success: function(d) {
			loginIp = d.loginIp;
			localStorage.setItem("token", d.token);
			sessionStorage.setItem("loginIp", d.loginIp);
			return d.token;
		},
		error: function(d) {
			return false;
		}
	})
}
getToken();
//刷新token
var t = setInterval(getToken, 7000000);

function getData(url, param, type = "POST") {
	return new Promise(function(resolve, reject) {
		var token = localStorage.getItem("token");
		if (!token) {
			getToken();
			token = localStorage.getItem("token");
		}

		$.ajax({
			type: type,
			url: apiUrl + url,
			data: param,
			dataType: "json",

			headers: {
				"x-auth-token": token
			},
			success: function(res) {
				resolve(res)
			},
			error: function(res) {
				reject(res)
			}
		})
	})
}

//播放视频
function play(i, rtsp, videoSize) {
	var box = document.getElementById('play-box-' + i)

	var canvas = document.createElement("canvas")
	box.appendChild(canvas)
	var url = 'ws://' + videoIp + ':8088/?rtsp=' + encodeURIComponent(rtsp) + '&videoSize=' + videoSize

	return new JSMpeg.Player(url, {
		canvas: canvas,
		autoplay: true
	})
}
