/**
 *  报警的推送
 *  目前只需要在小区后台调用
 */

/**
 * 与云巴推送服务器建立连接
 */
var yunba = null;
var __count_jq = 0;
$(function () {
	var appkey = $(':input[name=appkey][type=hidden]').val();
	var customId = $(':input[name=sessionId][type=hidden]').val();
	var feedback_alias = $(':input[name=feedbackAlias][type=hidden]').val();
	var apn_id = $(':input[name=communityId][type=hidden]').val();
	var feedback_topic = $(':input[name=feedbackTopic][type=hidden]').val();
	if (window.location.protocol === 'https:') {
		yunba = new Yunba({server: 'https://sock.yunba.io', port: 443, appkey: appkey});
	} else {
		yunba = new Yunba({appkey: appkey});
	}
	yunba.init(function (success) {
		if (success) {
			console.log('yunba.init初始化成功');
			mqtt_connect(customId, function () {
				console.log('工单别名:' + feedback_alias);
				feedback(feedback_alias, apn_id);
				if (typeof(apn_id) != "undefined") {
					setApn(apn_id);
					setFeedbackTopic(feedback_topic);
				}
			});
			setAlias(loginName);
		}
	}, function () {
		mqtt_connect(customId, function () {
			console.log('工单别名:' + feedback_alias);
			feedback(feedback_alias, apn_id);
			if (typeof(apn_id) != "undefined") {
				setApn(apn_id);
				setFeedbackTopic(feedback_topic);
			}
		});
	});
});

/**
 * 建立与云巴消息服务器的连接
 */
function mqtt_connect(customId, callback) {
	var cid = customId;
	var connected = function (success, msg, sessionid) {
		if (success) {
			console.log('建立与云巴消息服务器的连接:' + success);
			callback(success, msg, sessionid);
		} else {
			console.log(msg);
			// 暂时禁掉弹出
			// alert(msg);
		}
	};
	if (!cid || cid.length === 0) {
		alert('请输入自定义ID');
	} else {
		yunba.connect_by_customid(cid, connected);
	}
}

/**
 * 关闭与云巴消息服务器的连接
 */
function mqtt_disconnect() {
	yunba.disconnect(function (success, msg) {
		debugger;
		if (success) {
			console.log('关闭与云巴消息服务器的连接:' + success);
		} else {
			alert(msg);
		}
	});
}

/**
 * 设置别名
 */
function setAlias(alias) {
	yunba.set_alias({'alias': alias}, function (data) {
		if (!data.success) {
			console.log(data.msg);
		}
	});
}

/**
 * 设置安防推送关注的主题
 */
function setApn(apn_id) {
	console.log('安防频道列表:' + apn_id);
	var apn_ids = apn_id.split(",");
	for (var i = 0; i < apn_ids.length; i++) {
		console.log('安防频道:' + apn_ids[i] + '_alert');
		yunba.subscribe({'topic': apn_ids[i] + '_alert'}, function (success, msg) {
			if (!success) {
				console.log(msg);
			}
		});
	}
}

/**
 * 设置工单推送关注的主题
 */
function setFeedbackTopic(topic_id) {
	if (topic_id === "s_feedback" || topic_id.indexOf("adf_") === 0) {//总后台标签主题 广告后台 工单推送标签主题adf_广告商id
		console.log('工单频道:' + topic_id);
		yunba.subscribe({'topic': topic_id}, function (success, msg) {
			if (!success) {
				console.log(msg);
			}
		});
	} else {//物业后台 工单推送标签主题cf_小区id
		console.log('工单频道列表:' + topic_id);
		var topic_ids = topic_id.split(",");
		for (var i = 0; i < topic_ids.length; i++) {
			console.log('工单频道:' + 'cf_' + topic_ids[i]);
			yunba.subscribe({'topic': 'cf_' + topic_ids[i]}, function (success, msg) {
				if (!success) {
					console.log(msg);
				}
			});
		}
	}
}

/**
 * 设置收到消息时调用的回调函数
 */
function setMsgCallback(fun) {
	yunba.set_message_cb(fun);
}

/**
 * 获取工单
 */
function feedback(alias, apn_id) {
	setAlias(alias);
	var cb = function (data) {
		console.log('接收消息:' + JSON.stringify(data));
		if (data.hasOwnProperty('topic') && (data.topic == alias)) {
			//弹出对话框 
			popTask('你有新的工单,请及时处理');
		} else if (data.hasOwnProperty('topic') && (data.topic != alias)) {
			var apn_ids = apn_id.split(",");
			for (var i = 0; i < apn_ids.length; i++) {
				if (data.topic === apn_ids[i] + '_alert') {
					var str = data.msg;
					var json = eval('(' + data.msg + ')');
					console.log('接收消息xx-yy:' + json.c);
					console.log('count1:' + json.ex.t);
					if (json.ex.a == 'plus' && json.ex.m == 'push' && json.ex.p.t <= 28) {//广州 安居宝 摄像头
						var msgArr = json.c.split("-");
						var msg = {};
						var adr = msgArr[0];
						for (var j = 1; j < msgArr.length - 1; j++) {
							adr = adr + '-' + msgArr[j];
						}
						msg.title = msgArr[msgArr.length - 1];
						msg.adr = adr;
						msg.content = json.c;
						msg.time = json.ex.p.time;
						popApn(msg);
					} else if (json.ex.t == 2) {//珠海 安居宝 网关
						//popApn(json.c);
						console.log('count2:' + json.ex.t);
						getApnInfo(json);
						//开始播放音频文件mp4
					}
				}
			}
		}
	};
	setMsgCallback(cb);
}

/**
 * 获取警情提示
 */
function getApnInfo(json) {
	var data = {};
	data['cellId'] = json.ex.cl;
	$.ajax({
		type: "POST",
		url: ctx + "/common/cell/info",
		cache: true,
		data: data,
		async: false,
		success: function (repJson) {
			if (isOK(repJson)) {
				var msg = {};
				msg.title = json.c;
				msg.adr = repJson.msg;
				msg.content = json.ex.m;
				msg.time = json.ex.tm;
				popApn(msg);
			}
		}
	});

//	var msg = {};
//	msg.title = json.c;
//	msg.adr = "地址========";
//	msg.content = json.ex.m;
//	msg.time = json.ex.tm;
//	popApn(msg);
}


/**
 * 弹出工单
 * @param content
 */
function popTask(content) {
	var str = '<div style="width:250px;height:100px; text-align:center;color:#fff;font-family:Arial;font-size:20px;line-height:100px; ">' + content + '</div>';
	var wi = $(window).width() - 300;
	var he = 60;
	layer.open({
		type: 1,//页面层
		title: false, //不显示标题
		time: 5000,//自动关闭时间 3秒
		area: ['auto', 'auto'], //大小
		offset: [he + 'px', wi + 'px'],//坐标
		skin: 'tips-layerdialog', //样式类名
		closeBtn: 0, //不显示关闭按钮
		shift: 2,//动画从下往上弹出
		shade: 0,//不显示遮罩
		// shadeClose: true, //开启遮罩关闭
		content: str
	});
}


/**
 * popApn(msg);
 */
function popApn(msg) {
	__count_jq++;
	console.log('++__count_jq:' + __count_jq);
	play(__count_jq > 0);
	var wi = $(window).width() - 450;
	var he = 60;
	var str = "<ul id='jqts' class='layer_notice layui-layer-wrap' style='padding:0px 18px'>" +
		"<li>" + msg.adr + "</li>" +
		"<li>" + msg.content + "</li>" +
		"<li>" + msg.time + "</li>" +
		"</ul>";
	var alertTips = layer.open({
		type: 1,
		shade: false,
		title: msg.title, //不显示标题
		offset: [he + 'px', wi + 'px'],
		content: str,//捕获的元素
		//time: 5000
		cancel: function () {
			__count_jq--;
			console.log('--__count_jq:' + __count_jq);
			play(__count_jq > 0);
		}
	});
	layer.style(alertTips, {background: '#ff5555'});
	var divTitle = $('.layui-layer-title');
	$(divTitle).css({'background-color': '#ff5555', 'color': '#fff', 'font-family': 'Arial', 'font-size': '20px'});
}

/**
 * 播放音频文件
 * flag true表示播放,false表示停止
 */
function play(flag) {
	var audio_controls = document.getElementById('video_jqts');
	if (flag) {
		audio_controls.loop = -1;
		audio_controls.play();
	} else {
		audio_controls.loop = 0;
		audio_controls.pause();
	}
}
 