var BT_OPER_ID = 1;
var BT_OPER_SENDDATAS = 2;

var BT_OPEN_CMD = 1;
var BT_CHHOICE_CMD = 2;
var BT_BEEP_CMD = 3;
var BT_MES_AUTO_CLEAN = 5000;
var bt_mes_count = 0;
var BTBtnTask_Busy = 0;
var BTMesgBox;
var BTMesgBoxCountLabel;
var BTMesgBoxErrorCountLable;
var BTMesScrollFlag = 1;
var BTChoiceDiaID = -1;
var BTRWRegDiaID = -1;
var es_qthandle = null;
var MesgType = {
	    MESG_TYPE_OK : 0,
      MESG_TYPE_WARING  : 1,
      MESG_TYPE_ERROR  : 2,
      MESG_TYPE_INFO  : 3,
      MESG_TYPE_BEATH  : 4,
	
};
var Error_count = 0;
var Info_count = 0;
var BtOper_Json={
	uid:"123456789",
	pwd:"12345678",
	setdelay:10,
	commaddr:21,
	recovertime:20000,
	opercmd:1,
	amendv:-1,
	waitack:true,
	waittimeout:1000,
	beguid:"123456789",
	state_str:"",
	state_v:[],
	cfir_v:0,//起爆电容电压
	bus_v:0,//总线电压
	bus_c:0,//总线电流
	bat_v:0,//电池电压
	busmode:2,//总线模式
	heartbeat:1,//心跳包
	inspect_buf:[],//巡检结果数组
	firmware:"",//固件版本号
	begaddr:21,//循环操作的起始地址
	begdelay:50,//循环设置延时的起始值
	delaysetp:50,//延时设置步进值
	groupcount:1,//单次循环个数
	rundelay:1000, //循环延时
	amendcount:400,
	inspectcount:400,
	cycletimes:50,
	netcount:400,
	cmdbuf:[],
	setparam:[],
	cycletest:0,
	
};



function BTErrorCount(count)
{
	Error_count += count;
	var obj = $("#btmeserrorcount")[0];
	obj.innerHTML = "错误："+Error_count;
}
function BTInfoCount(count)
{
	var obj = $("#btmescount")[0];
	Info_count += count;
	obj.innerHTML = "条目："+Info_count;
	
}
function BTChoice(json_info)
{


	var content ='';
	console.log(json_info);
	json_info = eval("("+json_info+")");;
	if(json_info ==null || json_info == undefined)
	{
		ShowCommMes("没有获取到设备信息");
		return;
	}
	json_info = json_info.btinfo_list;
	content += '<div style="padding: 5px; line-height: 25px; background-color: #393D49; color:#cdd4d3; ">';  
	content += '<ul class="layui-nav layui-nav-tree layui-inline" lay-filter="demo" style="margin-right: 10px;">'
	for(var i = 0; i < json_info.length;i++)
	{
		content += ' <li class="layui-nav-item"><a  href="javascript:;" rel="external nofollow"  style = "color: #10a9f3; font-size: medium"  onclick="BtItem(';
		content += i+')" >';
		content += json_info[i];
		content += '</a></li>';
	}
    content += '</ul></div>'; 
	if(BTChoiceDiaID > 0)
	{
		layer.close(BTChoiceDiaID);
	}
	BTChoiceDiaID = layer.open({
	type: 1, 
	content:content,
	title: "选择蓝牙设备",
	shade:0.6,
	moveType: 1,
	btnAlign: 'c',
	maxHeight:450,
	maxWidth:400,
	minWidth:350,
	});
}
function BtRWRegDia()
{
	var content = '<div style="padding: 5px; line-height: 25px; background-color: #393D49; color:#cdd4d3; ">';  
	content += '<div class="layui-row"  style="height: 1.8rem ; line-height: 1.8rem; padding-top: 2px;"> ';
	content += '<div class="layui-col-xs4"><div class="grid-demo grid-demo-bg1" style="text-align: left;">寄存器地址:</div></div> ';
	content += '<div class="layui-col-xs4"><div class="grid-demo grid-demo-bg1" style="text-align: left;">寄存器长度：</div></div>';
	content += '<div class="layui-col-xs4"><div class="grid-demo grid-demo-bg1" style="text-align: left;">通信地址</div></div>';
	content += '</div>';
	
	content += '<div class="layui-row"  style="height: 1.8rem ; line-height: 1.8rem; padding-top: 2px;">';
	content += '<div class="layui-col-xs4" style="padding-left:2px"><input type="text" name="title" lay-verify="title" autocomplete="off" value="3E00" class="layui-input" style="height: 1.8rem; line-height: 1.8rem;"></div> ';
	content += '<div class="layui-col-xs4" style="padding-left:2px"><input type="text" name="title" lay-verify="title" autocomplete="off" value="4" class="layui-input" style="height: 1.8rem; line-height: 1.8rem;"></div>';
	content += '<div class="layui-col-xs4"style="padding-left:2px"><input type="text" name="title" lay-verify="title" autocomplete="off" value="1" class="layui-input" style="height: 1.8rem; line-height: 1.8rem;"></div>';
	content += '</div>';
	
	content += '<div class="layui-row"  style="height: 1.8rem ; line-height: 1.8rem; padding-top: 2px; padding-bottom:2px">';
	content += '<div class="layui-col-xs4"  ><button type="button" class="layui-btn layui-btn-normal " style="height: 1.8rem; line-height: 1.8rem; padding: 0 0.8rem;margin-left:5px; margin-right:5px;">读寄存器</button></div> ';
	content += '<div class="layui-col-xs4" "><button type="button" class="layui-btn layui-btn-normal " style="height: 1.8rem; line-height: 1.8rem; padding: 0 0.8rem;width: 90%;">擦写寄存器</button></div>';
	content += '<div class="layui-col-xs4" > <button type="button" class="layui-btn layui-btn-normal " style="height: 1.8rem; line-height: 1.8rem; padding: 0 0.8rem;width: 90%;">写寄存器</button></div>';
	content += '</div>';
	
	content += '<div  style="height: 20rem; border: 1px solid #000000; overflow:scroll; background-color:#eeeeee; color:#000000" id = "btregmesarea" onclick="RegAreaStopScroll()">1234 </div>'
	//content += '<div class="layui-row"  style="height: 1.8rem ; line-height: 1.8rem; padding-top: 2px;">';
	//content += '<div class="layui-col-xs10"><div class="grid-demo grid-demo-bg1" style="text-align: left;"></div></div> ';
	//content += '<div class="layui-col-xs2 "><button type="button" class="layui-btn layui-btn-normal " style="height: 1.8rem; line-height: 1.8rem; padding: 0 0.8rem;width: 90%;">返回</button></div>';
	//content += '</div>';
	
	content += '</div>';
	
	if(BTRWRegDiaID > 0)
	{
		layer.close(BTRWRegDiaID);
	}
	BTRWRegDiaID = layer.open({
	type: 1, 
	content:content,
	title: "读写寄存器",
	shade:0.6,
	moveType: 1,
	btnAlign: 'c',
	maxHeight:550,
	minWidth:350,
	});
	
}
function StopScroll()
{
	if( BTMesScrollFlag < 1)
	{
		BTMesScrollFlag = 1;
	}else{
		BTMesScrollFlag = 0;
	}
}
//显示普通信息
function ShowCommMes(commmes , mestype, logflag)
{
	
	var log_time = getDateTime();
	commmes = log_time+" "+commmes;
	var para=document.createElement("p");
	var node=document.createTextNode(commmes);
	para.appendChild(node);
	bt_mes_count++;
	if(bt_mes_count > BT_MES_AUTO_CLEAN)
	{
		BTMesgBox.innerHTML = "";
		bt_mes_count = 0;
		return ;
	}
	if(mestype == undefined || mestype == null)
		para.style = "color: #0b71af; font-size: 18px; word-wrap: break-word;  word-break: break-all; overflow: hidden;";
	else{
		var style_str = "color: ";
		switch(mestype)
		{
			case MesgType.MESG_TYPE_INFO: style_str += "#0b71af ;";break;
			case MesgType.MESG_TYPE_ERROR: style_str += "#e60619 ;";break;
			case MesgType.MESG_TYPE_OK: style_str += "#138422 ;";break;
			default:style_str += "#0b71af ;";break;
		}
		style_str += " font-size: 18px; word-wrap: break-word;  word-break: break-all; overflow: hidden;"
		para.style = style_str ;
	}
	BTMesgBox.appendChild(para);
	if(BTMesScrollFlag > 0)
	{
		BTMesgBox.scrollTop  = BTMesgBox.scrollHeight;
	}

	if(!(logflag == undefined || logflag == null))	
	{
		
		if((es_qthandle != null) && (es_qthandle != undefined)&& (logflag > 0))
		{
			
			if(mestype == MesgType.MESG_TYPE_ERROR)
			{
				es_qthandle.WriteLogMes(1,commmes);
			}else{
				es_qthandle.WriteLogMes(0,commmes);
			}
		}
	}
	
}
function ShowJsonMes(commmes)
{
	var mes = JSON.parse(commmes);
	mes = String.fromCharCode.apply(null,mes);
	console.log("ShowJsonMes ");
	ShowCommMes(mes,MesgType.MESG_TYPE_INFO);
}
//选择蓝牙设备回调函数
function BtItem(index)
{
	var data = {
		"oper_id" : BT_OPER_ID,
		"oper_cmd" : BT_CHHOICE_CMD,
		"choice_index" :index
	};
	//关闭设备选择对话框
	layer.close(BTChoiceDiaID);
	BtTranstoAndroid(BT_OPER_ID,data);
	
}
function BtBeep()
{
	var data = {
		"oper_id" : BT_OPER_ID,
		"oper_cmd" : BT_BEEP_CMD,
	};
	BtTranstoAndroid(BT_OPER_ID,data);
}
function BtMesClean()
{
	BTMesgBox.innerHTML = "";
	var obj = $("#btmeserrorcount")[0];
	obj.innerHTML = "错误：0";
	 obj = $("#btmescount")[0];
	obj.innerHTML = "条目：0";
	Error_count = 0;
	Info_count = 0;
	bt_mes_count = 0;
	
}
function BtTranstoAndroid(opr_id,data)
{
	var json_str = JSON.stringify(data);
	console.log(json_str);
	if( typeof(window.EproCmd) != "undefined" && window.EproCmd != null )
	{	
		window.EproCmd.JstoAndroid(opr_id,json_str);
	}else if( typeof(es_qthandle) != "undefined"  && es_qthandle != null )
	{
		es_qthandle.JS2QtCmd_Str(opr_id,json_str);
	}
	
}
function BtSwitch()
{
	ShowCommMes("点击");
	var data = {
		"oper_id" : BT_OPER_ID,
		"oper_cmd" : BT_OPEN_CMD
	};
	BtTranstoAndroid(BT_OPER_ID,data)
}
function ShowRWRegDia()
{
	BtRWRegDia();
}

function BTCommInit()
{
	BTMesgBox = $("#btmesarea")[0];
	BTMesgBoxCountLabel = $("#btmescount")[0];
	BTMesgBoxErrorCountLable =  $("#btmeserrorcount")[0];
	console.log("BTCommInit  Begin ---");
	if(typeof(qchannel) != "undefined" &&  qchannel != null )
	{
			
               es_qthandle = qchannel.objects.es_qthandle;
			   eshot_qthandle = es_qthandle;
               if(es_qthandle != null)
               {
               	   console.log("BTCommInit  OK ---");
               	   console.log(es_qthandle);
               }else{
               	
               	console.log("BTCommInit  ERROR ---");
               }
              
              
               /*
               if((typeof(qthandle) != "undefined") && (qthandle != null) )
               {
               	console.log(" QWebChannel qthandle");
               	qthandle.ShowCommMes.connect(function(mesg,type){
               		ShowCommMes(mesg,type);
               		
               	});
               	qthandle.BTChoice.connect(function(jsoninfo){
               		console.log("qthandle BTChoice");
               		BTChoice(jsoninfo);
               	});
               	
               	qthandle.BtRecFrame.connect(function(jsoninfo){
               		console.log("qthandle BtRecFrame");
               		BtRecFrame(jsoninfo);
               	});

               }*/
				 if((typeof(eshot_qthandle) != "undefined") && (eshot_qthandle != null) )
				 {
					  eshot_qthandle.ShowCommMes.connect(function(mesg,type){
						ShowCommMes(mesg,type);
						
					  });
					  eshot_qthandle.LoadJsPlugin.connect(function(file_name,pluginfun){
						  console.log("eshot_qthandle.LoadJsPlugin  ---");
						  logJsPlugin(file_name,pluginfun);
					  });
				}
		
	}

}

async function  BtCmdBtn(cmd)
{
	if(BTBtnTask_Busy > 0)
	{
		ShowCommMes("继续上一个任务。。。",MesgType.MESG_TYPE_WARING);
		return ;
	}
	BTBtnTask_Busy = 1;
	if(cmd == 0xFFFF) //显示更多功能
	{
		BTBtnTask_Busy = 0;
		return;
	}else if(cmd > 0xFF)
	{
		var param = ((cmd >> 8) & 0x0FF) - 1;
		cmd &= 0xFF;
		BtOper_Json.setparam[0] = param;
		
	}
	BtOper_Json.opercmd = cmd;
	BtGetInputInfo();
	console.log("BtCmdBtn")
	await SendCmd(true);
	BTBtnTask_Busy = 0;
}

async function BtMoreFunBtn()
{
	/*
	if (typeof(eval(Local_More)) == "function") {
      Local_More();
    }*/
	var html_str = loadPage("./load_test.html");
	console.log(html_str);
}

function BtSendBytes(cmd_buf,logflag)
{
	var json_cmd =  JSON.stringify(cmd_buf);
	if( typeof(window.EproCmd) != "undefined" && window.EproCmd != null )
	{	
		window.EproCmd.JSBTSendBytes(json_cmd);
	}else if( typeof(qthandle) != "undefined"  && qthandle != null )
	{
		qthandle.JSBTSendBytes(json_cmd);
	}
	if(logflag)
	{
		var log_mes = Bytes2Str(cmd_buf);
		log_mes = "Tx: "+ log_mes;
		ShowCommMes(log_mes,MesgType.MESG_TYPE_INFO);
	}
}

function BtRecFrame(fram_json)
{
	console.log("BtRecFrame ########");
	console.log(fram_json)
	var frame = JSON.parse(fram_json);
	EShotCmdRecv(frame);
}
function  CycleTestBtn()
{
	var btnobj = $("#BtCycletest");
	if(BtOper_Json.cycletest > 0)
	{
		BtOper_Json.cycletest = 0;
		btnobj.removeClass("layui-btn-warm");
	}else{
		BtOper_Json.cycletest = 1;
		btnobj.addClass("layui-btn-warm");
	}
}
function  BtGetInputInfo()
{
	
	BtOper_Json.uid = $("#bt_input_uid").val();
	BtOper_Json.pwd = $("#bt_input_pwd").val();
	BtOper_Json.commaddr = parseInt($("#bt_input_addr").val());
	BtOper_Json.setdelay = parseInt($("#bt_input_delay").val());
	BtOper_Json.recovertime =parseInt($("#bt_input_delay").val());
	BtOper_Json.begaddr = parseInt( $("#bt_input_bgaddr").val());
	BtOper_Json.beguid = $("#bt_input_bguid").val();
	BtOper_Json.begdelay =  parseInt($("#bt_input_bgdelay").val());
	BtOper_Json.delaysetp =  parseInt($("#bt_input_delaystep").val());
	BtOper_Json.rundelay =  parseInt($("#bt_input_rundelay").val());
	BtOper_Json.amendcount = parseInt($("#bt_input_amendtotal").val());
	BtOper_Json.inspectcount = parseInt($("#bt_input_inspecttotal").val());
	BtOper_Json.groupcount = parseInt($("#bt_input_groupcount").val());
	//BtOper_Json.netcount = parseInt($("#bt_input_netcount").val());
	if(BtOper_Json.cycletest > 0)
		BtOper_Json.cycletimes = parseInt($("#bt_input_cycletimes").val());
	else
		BtOper_Json.cycletimes = 1;
	//console.log(BtOper_Json);
}
function ShowBtUID(uid)
{
	$("#bt_input_uid").val(uid);
}
function ShowBtPWD(pwd)
{
	$("#bt_input_pwd").val(pwd);
}
function ShowBtAddr(addr)
{
	$("#bt_input_addr").val(addr);
}
function ShowBtDelay(delay)
{
	$("#bt_input_delay").val(delay);
}
function ShowBtState(state_str)
{
	$("#bt_input_sysstate").val(state_str);
}
function ShowBtAmendV(amendv)
{
	$("#bt_input_amendv").val(amendv);
}
function ShowBtFirmware(firmware)
{
	$("#bt_input_firmware").val(firmware);
}
function ShowBtBusV(busv)
{
	$("#bt_input_busv").val(busv);
}
function SwitchBusMode(type)
{
	var btnobj = $("#busmodebtn");
	
	if(type == 1)
	{
		btnobj.text("关总线");
		btnobj.removeClass("layui-btn-normal");
	}else{
		btnobj.text("开总线");
		btnobj.addClass("layui-btn-normal");
	}
}
function SwitchHartBeat(type)
{
	var btnobj = $("#hartbeatbtn");
	
	if(type == 1)
	{
		btnobj.text("关心跳");
		btnobj.addClass("layui-btn-normal");
	}else{
		btnobj.text("开心跳");
		btnobj.removeClass("layui-btn-normal");
		
	}
}
