/**
 * 与云巴推送服务器建立连接
 */
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 feedback_topic = $(':input[name=feedbackTopic][type=hidden]').val();
	var apn_id = $(':input[name=communityId][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);
				setAlias(loginName);
				setFeedbackTopic(feedback_topic);
				setApn(apn_id);
			});
		}
	}, function () {
		mqtt_connect(customId, function () {
			console.log('工单别名:' + feedback_alias);
			feedback(feedback_alias, apn_id);
			setAlias(loginName);
			setFeedbackTopic(feedback_topic);
			setApn(apn_id);
		});
	});
});

/**
 * 建立与云巴消息服务器的连接
 */
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);
		}
	};
	if (!cid || cid.length === 0) {
		alert('请输入自定义ID');
	} else {
		yunba.connect_by_customid(cid, connected);
	}
}

/**
 * 关闭与云巴消息服务器的连接
 */
function mqtt_disconnect() {
	yunba.disconnect(function (success, msg) {
		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) {
	//1接收警情提示并弹窗 0不弹窗
	var alarmSee=$(':input[name=alarmSee][type=hidden]').val();
	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 json = eval('(' + data.msg + ')');
					console.log('接收消息msg:' + json.c);
					if (json.ex.a === 'web_alarm_push') {
						if(alarmSee==1){
                            var tamperAlarmId = json.ex.p;
                            alertMsgByAlarmId(tamperAlarmId);
						}


						// var msg = {};
						// msg.title = '设备报警信息'; // 这个字段写死
						// msg.adr = '城市名';
						// msg.community = '小区名称';
						// msg.build = '楼栋名称';
						// msg.door = '门名称';
						// msg.mac = '设备MAC';
						// msg.errMsg = '错误类型（对应0~8的错误名称）';
						// popApn(msg);
					}
					break;
				}
			}
		}
	};
	setMsgCallback(cb);
}

/**
 * 弹出工单
 * @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() - 250 + $('div.viewFramework-sidebar').width())/2;
	var wi = $(window).width() - 300;
	//var he=$(window).height() / 2 - 50;
	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
	});
}


function alertMsgByAlarmId(alarmId) {
    var data = {};
    data['alarmId'] = alarmId;
    $.ajax({
        type: "POST",
        url: ctx + "/common/alarm/info",
        cache: true,
        data: data,
        async: false,
        success: function (repJson) {
            if (isOK(repJson)) {
                var msg = {};
                msg.title = '设备报警信息'; // 这个字段写死
                msg.adr = repJson.data.adr;
                msg.community = repJson.data.community;
                msg.build = repJson.data.build;
                msg.door = repJson.data.door;
                msg.mac = repJson.data.mac;
                msg.errMsg =repJson.data.errMsg;
                popApn(msg);

            }
        }
    });
}
/**
 * popApn(msg);
 */
function popApn(msg) {
	__count_jq++;
	console.log('++__count_jq:' + __count_jq);
	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.community + "</li>" +
		"<li>" + msg.build + "</li>" +
		"<li>" + msg.door + "</li>" +
		"<li>" + msg.mac + "</li>" +
		"<li>" + msg.errMsg + "</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();
	}
}