<!DOCTYPE html>
<html lang="en">

<head>
	<meta charset="UTF-8">
	<meta name="viewport"
		content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no">
	<title>唐庄变屏位图</title>
	<link rel="stylesheet" type="text/css" href="../css/mui_min.css" />
	<link rel="stylesheet" type="text/css" href="../css/font_awesome_min.css" />
	<link rel="stylesheet" href="../css/bootstrap_min.css">
	<link rel="stylesheet" type="text/css" href="../css/api.css" />
	<script type="text/javascript" src="../script/api.js"></script>
	<style>
	/* 唐庄变频位图 */
		.tick {
			/* position: relative; */
			position: absolute;
			display: block;
			top: 10px;
			left: 83px;
			width: 30px;
			height: 30px;
		}

		.bj {
			width: 1335px;
			height: 100%;
			background: rgb(3, 154, 219);
			background-size: 100%;
		}
		.groove_dark {
			position: relative;
			background: rgb(31, 110, 160);
			height: 130px;
			border: 1px solid #fff;
			float: left;
			text-align: center;
			padding-top: 20px;
			
		}
		.mui-btn {
			background-color: #31D295FF;
			width: 115px;
			height: 45px;
			margin-left: 50px;
			margin-top: 10px;
			border: none;
			border-radius: 5px;

		}
		.mui-btn2 {
			background-color: rgb(250, 85, 85);
			width: 115px;
			height: 45px;
			margin-left: 36px;
			margin-top: 10px;
			border: none;
			border-radius: 5px;
		}
		.mui-btn3 {
			background-color: rgb(240, 143, 46);
			width: 115px;
			height: 45px;
			margin-left: 36px;
			margin-top: 10px;
			border: none;
			border-radius: 5px;
		}
		.row {
			width: 1230px;
			margin: 0 auto;
			padding-top: 10px;
		}
		.cn_light {
			padding-top: 18px;
			color: #fff;
		}
		.btn {
			background-color: rgb(134, 155, 182);
			color: #fff;
			width: 115px;
			height: 45px;
			border-radius: 5px;
			margin-top: 10px;
			float: right;
			margin-right: 60px;
			border: none;
		}
		.text1 {
			display: inline-block;
			margin-top: 69px;
			margin-bottom: 33px;
			color: #fff;
		}
		.text2 {
			display: inline-block;
			margin-top: 69px;
			margin-bottom: 33px;
			margin-left: 50px;
			color: #fff;
		}
	</style>
</head>

<body class="bj">
	<div class="" id="content1">
		<div class="row" id="row">
			<div class="col-sm-4 col-xs-3 col-md-2 groove_dark" id="1" onclick="choose()">
				<input id="v1" type="hidden" value="0">
				<!-- 蒙版 -->
				<div class="masking" id="masking1" style="display: none;"></div>
				<!-- 对钩 -->
				<div class="tick" id="tickAc1" style="display: none;">
					<img src="../icon/tickActive.png" style="width: 100%;height: 100%;">
				</div>
				<div class="tick" id="tickun1">
					<img src="../icon/tick.png" style="width: 100%;height: 100%;">
				</div>
				<p id="n" class="cn_light">综合配线屏</p>
				<p id="s" class="cn_light">当前状态:未知</p>
			</div>
			
		</div>
	</div>
	<button class="mui-btn mui-btn-success mui-btn-loading" onclick="chooseall()">全选</button>
	<button class="mui-btn2 mui-btn-success mui-btn-loading" onclick="protection()">布防</button>
	<span class="text1">点击后除选择的为布防,其余的改为撤防</span>
	<span class="text2">点击之后除选择的为撤防,其余的为布防</span>
	<button class="mui-btn3 mui-btn-success mui-btn-loading" onclick="removal()">撤防</button>
	<button class="mui-btn3 mui-btn-success mui-btn-loading" onclick="back()" style="width:50px;height:50px;">
		<img src="../image/back.png" style="width:100%;height:100%;">
	</button>
</body>
<script type="text/javascript" src="../script/mui.min.js"></script>
<script type="text/javascript" src="../script/jquery-1.8.3.js"></script>
<script type="text/javascript" src="../script/command.js"></script>
<script type="text/javascript" src="../script/common.js"></script>
<script type="text/javascript" src="../script/crc.js"></script>
<script type="text/javascript" src="../script/cache.js"></script>

<script type="text/javascript">

	var SocketServerClient = null;
	var db = null;
	var socketManager = null;
	var ipadd = '';
	var port = 0;

	//全选第一次初始化判断,目的只执行一次
	var cfflag = true;

	

	apiready = function () {
		db = api.require('db');
		socketManager = api.require('socketManager');
		initSB();
		jian();
		ipconfig();
	};

	function initSB(){
		select(db, 'SELECT * FROM Sb WHERE Slt = "2"', function (ret, err) {		
			if(ret.status && ret.data.length > 0){
				//需要根据设备图片,对设备名称进行完善
				var arr = ret.data;
				var html = "";
				for(var index = 0; index < arr.length; index ++){
					html += '<div class="col-sm-4 col-xs-3 col-md-2 groove_dark" id="'+arr[index].Code+'" onclick="choose()">';
					html += '	<input id="v'+arr[index].Code+'" type="hidden" value="0">                                    ';
					html += '	<!-- 蒙版 -->                                                              ';
					html += '	<div class="masking" id="masking'+arr[index].Code+'" style="display: none;"></div>           ';
					html += '	<!-- 对钩 -->                                                              ';
					html += '	<div class="tick" id="tickAc'+arr[index].Code+'" style="display: none;">                     ';
					html += '		<img src="../icon/tickActive.png" style="width: 100%;height: 100%;">   ';
					html += '	</div>                                                                     ';
					html += '	<div class="tick" id="tickun'+arr[index].Code+'">                                            ';
					html += '		<img src="../icon/tick.png" style="width: 100%;height: 100%;">         ';
					html += '	</div>                                                                     ';
					html += '	<p id="n'+arr[index].Code+'" class="cn_light">'+arr[index].Name+'</p>     ';
					if(arr[index].Status == "0"){
						html += '	<p id="s'+arr[index].Code+'" class="cn_light">当前状态:未知</p> ';    
					}else if(arr[index].Status == "1"){
						html += '	<p id="s'+arr[index].Code+'" class="cn_light">当前状态:升<i class="fa fa-arrow-up" style="color: red;" aria-hidden="true"></i></p> ';    
					}else if(arr[index].Status == "2"){
						html += '	<p id="s'+arr[index].Code+'" class="cn_light">当前状态:降<i class="fa fa-arrow-down" style="color: green;" aria-hidden="true"></i></p> ';    
					}
					html += '</div>                                                                        ';
				}
				$("#row").html(html);
			}
		});
	}

	//返回
	function back() {
		openHtml('frame1', 'frame1.html');
	}
	

	function ipconfig() {
		//查询ip数据库
		select(db, 'SELECT * FROM Ipconfig;', function (ret, err) {
			var iparray = ret.data;
			if (iparray != '' && iparray != null) {
				ipadd = iparray[0].ipadd;
				port = iparray[0].port;
			}else{
				alert("未初始化配置,请先用管理员账号登录进行初始化配置")
			}
		})
	}

	//监听
	function jian() {
		api.addEventListener({
			name: 'myEvent'
		}, function (ret, err) {
			if (ret.value.state == 'no') {
				abc();
			}
		});     //放的位置无限制,写在apiready最开始即可
	}

	function abc() {
		window.location.reload();//刷新页面
	}

	function openHtml(name, url, params) {
		api.openWin({
			name: name,
			reload: true,
			url: url,
			pageParam: params
		});
	}
	
	//全选
	function chooseall() {
		if(cfflag){
			$('#row>div').each(function(){
				$(this).css("background","rgb(31, 110, 160)")
				$(this).children("div:eq(0)").css('display', 'none');
				$(this).children("div:eq(1)").css('display', 'none');
				$(this).children("div:eq(2)").css('display', 'block');
			});
			cfflag = false;
		}
		
		$('#row>div').each(function(){
			//未选中
			if($(this).children('div:eq(1)').css('display')=='none'){
				$(this).css("background","#07b32c")
				$(this).children("div:eq(0)").css('display', 'block');
				$(this).children("div:eq(1)").css('display', 'block');
				$(this).children("div:eq(2)").css('display', 'none');
			}else{
				$(this).css("background","rgb(31, 110, 160)")
				$(this).children("div:eq(0)").css('display', 'none');
				$(this).children("div:eq(1)").css('display', 'none');
				$(this).children("div:eq(2)").css('display', 'block');
			}
		});

	}

	//单独选择
	function choose() {
		cfflag = true;

		var flag = $(event.currentTarget).children("div:eq(2)").css("display");
		if(flag == 'none'){
			$(event.currentTarget).css("background","rgb(31, 110, 160)")
			$(event.currentTarget).children("div:eq(0)").css('display', 'none');
			$(event.currentTarget).children("div:eq(1)").css('display', 'none');
			$(event.currentTarget).children("div:eq(2)").css('display', 'block');
		}else{
			$(event.currentTarget).css("background","#07b32c")
			$(event.currentTarget).children("div:eq(0)").css('display', 'block');
			$(event.currentTarget).children("div:eq(1)").css('display', 'block');
			$(event.currentTarget).children("div:eq(2)").css('display', 'none');
		}
		
	}

	var bytes = new Array();
	//字符串转byte数组
	function stringToByte(str) {

		var len, c;
		bytes.length = 0;
		len = str.length / 2;
		for (var i = 0; i < len; i++) {
			c = str.charCodeAt(i);
			var num1, num2, num3;
			num1 = str.charCodeAt(2 * i);
			num2 = str.charCodeAt(2 * i + 1);
			if ((num1 >= 65) & (num1 <= 70)) {

				num1 = num1 - 65 + 10
			} else if ((num1 >= 48) & (num1 <= 57)) {
				num1 = num1 - 48
			}
			if ((num2 >= 65) & (num2 <= 70)) {

				num2 = num2 - 65 + 10
			} else if ((num2 >= 48) & (num2 <= 57)) {
				num2 = num2 - 48
			}
			num3 = num1 * 16 + num2;
			bytes.push(num3);
		}
		return bytes;
	}

	//字符串转base64
	function encode(str) {
		// 对字符串进行编码
		var encode = encodeURI(str);
		// 对编码的字符串转化base64
		var base64 = btoa(encode);
		return base64;
	}

	//解码
	var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="
	function base64_decode(input) {
		var output = new Array();
		var chr1, chr2, chr3;
		var enc1, enc2, enc3, enc4;
		var i = 0;

		var orig_input = input;
		input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
		if (orig_input != input)
			alert("Warning! Characters outside Base64 range in input string ignored.");
		if (input.length % 4) {
			alert("Error: Input length is not a multiple of 4 bytes.");
			return "";
		}

		var j = 0;
		while (i < input.length) {

			enc1 = keyStr.indexOf(input.charAt(i++));
			enc2 = keyStr.indexOf(input.charAt(i++));
			enc3 = keyStr.indexOf(input.charAt(i++));
			enc4 = keyStr.indexOf(input.charAt(i++));

			chr1 = (enc1 << 2) | (enc2 >> 4);
			chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
			chr3 = ((enc3 & 3) << 6) | enc4;

			output[j++] = chr1;
			if (enc3 != 64)
				output[j++] = chr2;
			if (enc4 != 64)
				output[j++] = chr3;

		}
		return output;
	}

	var hD = '0123456789ABCDEF';
	function dec2hex(d) {
		var h = hD.substr(d & 15, 1);
		while (d > 15) {
			d >>= 4;
			h = hD.substr(d & 15, 1) + h;
		}
		return h;
	}

	const replaceStr1 = (str, index, char) => {
		const strAry = str.split('');
		strAry[index] = char;
		return strAry.join('');
	}

	//修改状态表数据库
	function updatastate(ide, str) {
		select(db, 'SELECT * FROM Sb WHERE Slt="2" and Code ="' + ide + '"', function (ret, err) {
			//如果查到
			if (ret.data.length > 0) {
				//插入数据库
				execute(db, "update Sb set Status = '"+str+"' where Slt = '2' and Code = '"+ret.data[0].Code+"'", function (ret, err) { })
			}
		})
	}

/*
 * 显示loading遮罩层
 */
 function loading() {
    var mask_bg = document.createElement("div");
    mask_bg.id = "mask_bg";
    mask_bg.style.position = "absolute";
    mask_bg.style.top = "0px";
    mask_bg.style.left = "0px";
    mask_bg.style.width = "100%";
    mask_bg.style.height = "130%";
    mask_bg.style.backgroundColor = "#777";
    mask_bg.style.opacity = 0.6;
    mask_bg.style.zIndex = 10001;
    document.body.appendChild(mask_bg); 
    var mask_msg = document.createElement("div");
    mask_msg.style.position = "absolute";
    mask_msg.style.top = "45%";
    mask_msg.style.left = "40%";
    mask_msg.style.backgroundColor = "white";
    mask_msg.style.border = "#336699 1px solid";
    mask_msg.style.textAlign = "center";
    mask_msg.style.fontSize = "1.1em";
    mask_msg.style.fontWeight = "bold";
    mask_msg.style.padding = "0.5em 3em 0.5em 3em";
    mask_msg.style.zIndex = 10002;
    mask_msg.innerText = "正在执行,请稍后...";
    mask_bg.appendChild(mask_msg);
}
/*
 * 关闭遮罩层
 */
 function loaded() {
    var mask_bg = document.getElementById("mask_bg");
    if (mask_bg != null){
		mask_bg.parentNode.removeChild(mask_bg);
	}
        
}


	//布防
	function protection() {
		loading();
		var str2 = '11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111';
		//根据选择替换字符
		$('#row>div').each(function(index){
			var temp = $(this).attr("id");
			//未选中
			if($(this).children('div:eq(1)').css('display')=='none'){
				$("#s"+temp).html("当前状态:升" + "<i class='fa fa-arrow-up' style='color: red;' aria-hidden='true'></i>");
				updatastate(temp, 1);
			}else{
				str2 = replaceStr1(str2, index, '0')
				$("#s"+temp).html("当前状态:降" + "<i class='fa fa-arrow-down' style='color: green;' aria-hidden='true'></i>");
				updatastate(temp, 2);
			}
		});

		console.log(str2)
		
		//sendStr为要发送的数据
		var sendStr = bin_to_hex(str2).slice(0, 2) + " "
			+ bin_to_hex(str2).slice(2, 4) + ' '
			+ bin_to_hex(str2).slice(4, 6) + ' '
			+ bin_to_hex(str2).slice(6, 8) + ' '
			+ bin_to_hex(str2).slice(8, 10) + ' '
			+ bin_to_hex(str2).slice(10, 12) + ' '
			+ bin_to_hex(str2).slice(12, 14) + ' '
			+ bin_to_hex(str2).slice(14, 16) + ' '
			+ bin_to_hex(str2).slice(16, 18) + ' '
			+ bin_to_hex(str2).slice(18, 20) + ' '
			+ bin_to_hex(str2).slice(20, 22) + ' '
			+ bin_to_hex(str2).slice(22, 24) + ' '
			+ bin_to_hex(str2).slice(24, 26) + ' '
			+ bin_to_hex(str2).slice(16, 18) + ' '
			+ bin_to_hex(str2).slice(28, 30) + ' '
			+ bin_to_hex(str2).slice(30, 32);
		//需要效验的数据
		var intended = '00 17 03 00 01 ' + sendStr + ' 01 00 00 00 ';
		//组装数据
		var sendmess = 'FE FE FE 7C 00 17 03 00 01 ' + sendStr + '01 00 00 00' + CRCdata(intended) + ' 16';
		var v4 = sendmess.replace(/\s*/g, "");
		createTcp(socketManager, ipadd, port, function (ret, err) {
			if (ret.state == 102) {
				var sid1 = ret.sid;
				var Cr1 = '00 17 03 00 01 ' + sendStr + ' 01 00 00 00 ';
				var v1 = 'FE FE FE 7C 00 17 03 00 01 ' + sendStr + ' 01 00 00 00 ' + CRCdata(intended) + ' 16';
				var v4 = v1.replace(/\s*/g, "").toUpperCase();
				stringToByte(v4);
				var v5 = window.btoa(String.fromCharCode(...new Uint8Array(bytes)))
				witeTcp(socketManager, sid1, v5, function (ret, err) { })
			}
			if (ret.state == 103) {
				var sid1 = ret.sid;
				var output = base64_decode(ret.data).toString();
				var m = output.split(",");
				var v22 = ''
				for (var u = 0; u <= m.length; u++) {
					if (m[u] != undefined) {
						var v20 = Number(m[u])
						var v21 = v20.toString(16).toUpperCase()
						v22 += v21
					}
				}
				close(socketManager, sid1, function (ret, err) { });
				loaded();
			}
		})
	}

	//撤防
	function removal() {
		loading();
		var str2 = '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000';
		//根据选择替换字符
		$('#row>div').each(function(index){
			var temp = $(this).attr("id");
			//未选中
			if($(this).children('div:eq(1)').css('display')=='none'){
				
				$("#s"+temp).html("当前状态:降" + "<i class='fa fa-arrow-down' style='color: green;' aria-hidden='true'></i>");
				updatastate(temp, 2);
			}else{
				str2 = replaceStr1(str2, index, '1')
				$("#s"+temp).html("当前状态:升" + "<i class='fa fa-arrow-up' style='color: red;' aria-hidden='true'></i>");
				updatastate(temp, 1);
			}
		});

		console.log(str2)
		
		//sendStr为要发送的数据
		var sendStr = bin_to_hex(str2).slice(0, 2) + " "
			+ bin_to_hex(str2).slice(2, 4) + ' '
			+ bin_to_hex(str2).slice(4, 6) + ' '
			+ bin_to_hex(str2).slice(6, 8) + ' '
			+ bin_to_hex(str2).slice(8, 10) + ' '
			+ bin_to_hex(str2).slice(10, 12) + ' '
			+ bin_to_hex(str2).slice(12, 14) + ' '
			+ bin_to_hex(str2).slice(14, 16) + ' '
			+ bin_to_hex(str2).slice(16, 18) + ' '
			+ bin_to_hex(str2).slice(18, 20) + ' '
			+ bin_to_hex(str2).slice(20, 22) + ' '
			+ bin_to_hex(str2).slice(22, 24) + ' '
			+ bin_to_hex(str2).slice(24, 26) + ' '
			+ bin_to_hex(str2).slice(16, 18) + ' '
			+ bin_to_hex(str2).slice(28, 30) + ' '
			+ bin_to_hex(str2).slice(30, 32);
		//需要效验的数据
		var intended = '00 17 03 00 01 ' + sendStr + ' 00 00 00 00 ';
		//组装数据
		var sendmess = 'FE FE FE 7C 00 17 03 00 01 ' + sendStr + '00 00 00 00' + CRCdata(intended) + ' 16';
		var v4 = sendmess.replace(/\s*/g, "");
		createTcp(socketManager, ipadd, port, function (ret, err) {
			if (ret.state == 102) {
				var sid1 = ret.sid;
				var Cr1 = '00 17 03 00 01 ' + sendStr + ' 00 00 00 00 ';
				var v1 = 'FE FE FE 7C 00 17 03 00 01 ' + sendStr + ' 00 00 00 00 ' + CRCdata(intended) + ' 16';
				var v4 = v1.replace(/\s*/g, "").toUpperCase();
				stringToByte(v4);
				var v5 = window.btoa(String.fromCharCode(...new Uint8Array(bytes)))
				witeTcp(socketManager, sid1, v5, function (ret, err) { })
			}
			if (ret.state == 103) {

				var sid1 = ret.sid;
				var output = base64_decode(ret.data).toString();
				var m = output.split(",");
				var v22 = ''
				for (var u = 0; u <= m.length; u++) {
					if (m[u] != undefined) {
						var v20 = Number(m[u])
						var v21 = v20.toString(16).toUpperCase()
						v22 += v21
					}
				}
				close(socketManager, sid1, function (ret, err) { });
				loaded();
			}
		})
	}

	//二进制转为十六进制
	function bin_to_hex(str) {
		let hex_array = [{ key: 0, val: "0000" }, { key: 1, val: "0001" }, { key: 2, val: "0010" }, { key: 3, val: "0011" }, { key: 4, val: "0100" }, { key: 5, val: "0101" }, { key: 6, val: "0110" }, { key: 7, val: "0111" },
		{ key: 8, val: "1000" }, { key: 9, val: "1001" }, { key: 'a', val: "1010" }, { key: 'b', val: "1011" }, { key: 'c', val: "1100" }, { key: 'd', val: "1101" }, { key: 'e', val: "1110" }, { key: 'f', val: "1111" }]
		let value = ''
		let list = []
		if (str.length % 4 !== 0) {
			let a = "0000"
			let b = a.substring(0, 4 - str.length % 4)
			str = b.concat(str)
		}
		while (str.length > 4) {
			list.push(str.substring(0, 4))
			str = str.substring(4);
		}
		list.push(str)
		for (let i = 0; i < list.length; i++) {
			for (let j = 0; j < hex_array.length; j++) {
				if (list[i] == hex_array[j].val) {
					value = value.concat(hex_array[j].key)
					break
				}
			}
		}
		return value
	}
</script>

</html>