define(function(require, exports, module) {
    require('bootstrapTable');
    require('bootstrapTableCn');

	var global = require("../../js/global");
	var jGlobal = require("./oneUpgradeGlobal");
	var deviceManage = require("../../deviceManage/js/deviceManage");
    var commonAddDevice = require("../../../all/js/commonAddDevice");
    var oneAcUpgrade = window.require("../../common/js/oneAcUpgrade");
	
	//无线升级页面变量
	var acSelectDevice = [];
	var selectDevInfo = {};
	var isNewAcVersion = true;
	var gotoNextPageFlag = true;
	
	function getAndShowDevInfo() {
	    function queryDevInfoCallback(error, result) {
	        if (error == null) {
	            addDevInfoToTable(result);
	        } else {
	            alert(undefined, "读取设备数据失败！");
	        }
	    }
	    global.devicesIns.getDeviceConfigInfoAll(queryDevInfoCallback);
	}
	
	function addDevInfoToTable(devInfo) {
        $("#guideTip").text("");
		if (devInfo.length == 0) {
            $("#guideTip").text("您还没添加过AC哦，请前往“设备管理”添加设备!");
            return;
        }

		// console.log(devInfo);
		var acDevInfo = [];
		
	    for (var i = 0; i < devInfo.length; ++i) {	
			var type = devInfo[i].deviceType;
	        if (!type || type == '-' || type.match("Wireless") != null) {
				acDevInfo.push(devInfo[i]);
	        }
	    }  
		// console.log(acDevInfo);
		
		for (var j = 0; j < acDevInfo.length; ++j){
			if (acDevInfo[j].protocal == "serial") {
					acDevInfo[j].conne_type = acDevInfo[j].protocal;
					acDevInfo[j].host_com = acDevInfo[j].comNum;
					acDevInfo[j].port = acDevInfo[j].baudrate;
				} else{
					acDevInfo[j].conne_type = acDevInfo[j].protocal;
					acDevInfo[j].host_com = acDevInfo[j].host;
					acDevInfo[j].port = acDevInfo[j].port;
				}
			if (acDevInfo[j].groupName === null || acDevInfo[j].groupName === undefined || acDevInfo[j].groupName === '') {
				acDevInfo[j].groupName = "未分组";
			}
		}
		console.log(acDevInfo);
		
		$('#selectDeviceTable').bootstrapTable('load', acDevInfo);
	    return;
	}
	
	function operateStyle(value) {
        return '<div class="table-btn edit" style="float: left;">编辑</div>';
	}
	
//	function deleteSelectedDev(row, index) {		
//		var selectedDeviceCopy = acSelectDevice;
//		acSelectDevice = [];
//		for (var i = 0; i < selectedDeviceCopy.length; i++) {
//			if (row.deviceName !== selectedDeviceCopy[i].deviceName) {
//				acSelectDevice.push(selectedDeviceCopy[i]);
//			}
//		}
//		$('#selectedDeviceTable').bootstrapTable('load', acSelectDevice);
//		
//		addCssForTable();
//	}
	
//	function addCssForTable() {
//		$(".delete").hover(function() {
//			$(this).css("color", "#f5224c");
//	    }, function() {
//	    	$(this).css("color", "#b8b8b8");
//	    });
//		
//		$("[data-toggle='tooltip']").tooltip();
//	}
	
	function initAndConnectAllDevice(result) {
		/* 初始化 */
		jGlobal.oneUpgrade.multiDevConnectStatus = {};
		jGlobal.oneUpgrade.connectDevNum = result.length;
		jGlobal.oneUpgrade.connectDevNum_getInfo = 0;
		jGlobal.oneUpgrade.connectDevNum_disconnect = 0;
		jGlobal.oneUpgrade.batchConnectFlag = true;
		jGlobal.oneUpgrade.multiDevRcmndVersion = {};
		
		for (var i = 0; i < result.length; i++) {
			jGlobal.oneUpgrade.multiDevConnectStatus[result[i].deviceName] = "init";
		}
//	    console.log(jGlobal.oneUpgrade.multiDevConnectStatus);
		
	    /* 连接所有设备，获取所有设备的设备型号、硬件版本、软件版本 */	    
	    for (var key in jGlobal.oneUpgrade.multiDevConnectStatus) {
	    	global.devicesIns.connectDeviceByDeviceName(key);
	    	// 当前正常状态init
	    	jGlobal.oneUpgrade.multiDevConnectStatus[key] = jGlobal.changeDevStatus(key, jGlobal.oneUpgrade.multiDevConnectStatus[key], 'connecting');
	    	jGlobal.oneUpgrade.connectDevNum_disconnect++;
	    }
	}
	
	// 当前正常状态init connecting connected closing
	function cancelConnectAllDev(msg) {
		jGlobal.oneUpgrade.connect_forcedCancelFlag = true;
    	var msg = " 正在断开所有设备的连接，请稍候…";
    	
		for (var key in jGlobal.oneUpgrade.multiDevConnectStatus) {
			if (jGlobal.oneUpgrade.multiDevConnectStatus[key] != "init") {  //处于init状态下断开连接无法收到deviceConnected消息
	    		global.devicesIns.closeDeviceLink(key);
	    		jGlobal.oneUpgrade.multiDevConnectStatus[key] = jGlobal.changeDevStatus(key, jGlobal.oneUpgrade.multiDevConnectStatus[key], 'closing');
	    	}
	    }
		alert(undefined, msg);
	}
	
	function closeDeviceLinkByName(devName) {
		//断开设备
		jGlobal.oneUpgrade.multiDevConnectStatus[devName] = jGlobal.changeDevStatus(devName, jGlobal.oneUpgrade.multiDevConnectStatus[devName], 'closing');
		global.devicesIns.closeDeviceLink(devName);
	}
	
	function determinRecommendedVersionCallback(res) {
		// console.error("--------------------------------------------");
		// console.error(res);
		
		jGlobal.oneUpgrade.multiDevRcmndVersion[res.addParams] = res.retParams;
		
//		var objectTmp = {};
//		if (res.retParams.softwareVersion == null || res.retParams.fileName == null) {
//			jGlobal.oneUpgrade.multiDevUpgradeVersion[res.addParams] = "";
//		} else {
//			objectTmp.versionCode = res.retParams.softwareVersion;
//			objectTmp.versionName = res.retParams.fileName;
//			objectTmp.fileMd5 = res.retParams.fileMd5;
//			jGlobal.oneUpgrade.multiDevUpgradeVersion[res.addParams] = objectTmp;
//		}
		
		var devName = res.addParams;
		var softVer = selectDevInfo.softVer;
		if (softVer.match(/Mid/i) != null) {
			jGlobal.oneUpgrade.originAcVersion = "mid";
//			alert(undefined, "AC版本太旧，请先升级AC！当前版本是否是运营商版本？", function() {
//				jGlobal.oneUpgrade.isOperators = true;
//			}, true, function() {
//				jGlobal.oneUpgrade.isOperators = false;
//			});
			closeDeviceLinkByName(devName);
		} else if (softVer.indexOf("10.") != -1) {
			jGlobal.oneUpgrade.originAcVersion = "10.";
			if (softVer.match(/1T8/i) != null || softVer.match(/2B17/i) != null) { //判断是否运营商版本
				jGlobal.oneUpgrade.isOperators = true;
				console.log("10.x是中间版本");
			} else {
				jGlobal.oneUpgrade.isOperators = false;
				console.log("10.x不是中间版本");
			}
			alert(undefined, "AC版本太旧，请先升级AC！");
			closeDeviceLinkByName(devName);
		} else if (softVer.indexOf("11.") != -1) {			
			jGlobal.oneUpgrade.originAcVersion = "11.";
			global.devicesIns.execCmd(devName, "show version", function(res) {
				//判断是否运营商版本
				var reg = res.match(/System software version\s*:\s*(.+)\r?\n/i);
				if (reg[1].match(/1T8/i) != null || reg[1].match(/2B17/i) != null) {
					jGlobal.oneUpgrade.isOperators = true;
					console.log("11.x是中间版本");
				} else {
					jGlobal.oneUpgrade.isOperators = false;
					console.log("11.x不是中间版本");
				}
				
				//获取所有的ap信息				
    			var apCmdList = [];
    			var _10xApList = [];
    			var _11xApList = [];
    			
    			var apCmd1 = {name:'config', value: function() {}, args:''};
    			apCmdList.push(apCmd1);
    			var apCmd2 = {name:'no wlan diag enable', value: function() {}, args:''};
    			apCmdList.push(apCmd2);
    			var apCmd3 = {name:'wlan diag enable', value: function() {}, args:''};
    			apCmdList.push(apCmd3);
    			var apCmd4 = {name:'end', value: function() {}, args:''};
    			apCmdList.push(apCmd4);
    			
    	    	var apCmd5 = {name:'show ap-config product', value: function(res) { //11x ap的信息
    	    		_11xApList = parseApInfo(res, "11.x");
    	    	}, args:''};
    	    	apCmdList.push(apCmd5);
    	    	var apCmd6 = {name:'show ap-config rgos10-ap-list', value: function(res) { //10x ap的信息
    	    		_10xApList = parseApInfo(res, "10.x");
    	    		if (isNewAcVersion) {
    	    			jGlobal.oneUpgrade.apInfo = _11xApList.concat(_10xApList);
        	    		console.error("所有的ap信息为: ", jGlobal.oneUpgrade.apInfo);
    	    		} else {
    	    			jGlobal.oneUpgrade.apInfo = [];
    	    		}
    	    		
    	    		closeDeviceLinkByName(devName);
    	    	}, args:''};
    	    	apCmdList.push(apCmd6);
    	    	global.devicesIns.execCmdList(devName, apCmdList);
    	    	
//    	    	/* 无用,纯测试代码，暂不删除 */
//    	    	var apCmd5 = {name:'show wlan diag network', value: function(res) {
//    	    		var tmp1 = res.split(/Online AP Version:\r?\n/i);
//    	    		var tmp2 = tmp1[1].split(/\r?\nWlan information:/i);
//    	    		var str = tmp2[0];
//    	    		var apInfoArr = _parse11xApInfo(str);
//    	    	}, args:''};
//    	    	apCmdList.push(apCmd5);
//    	    	global.devicesIns.execCmdList(devName, apCmdList);
			});
		}
	}
	
//	/* 解析show wlan diag network命令并存储到数组中 */
//    function _parse11xApInfo(res) {
//    	console.log(res);		
//		var apInfoArr = [];
//		var resArr = res.split(/\r?\n/);
//		for (var i = 2; i < resArr.length; i++) {
//			var apInfo = {};
//			var fieldArr = resArr[i].trim().split(/\s{2,}/g);
//			
//			if (fieldArr.length == 4) { //正常情况
//				apInfo.pId = fieldArr[0];
//				apInfo.hwVer = fieldArr[1];
//				apInfo.swVer = fieldArr[2];
//				apInfo.num = fieldArr[3];
//			} else if (fieldArr.length == 3) { //软件版本号太长
//				apInfo.pId = fieldArr[0];
//				apInfo.hwVer = fieldArr[1];
//				var len = fieldArr[2].length;
//				apInfo.swVer = fieldArr[2].substring(0, len - 1).trim();
//				apInfo.num = fieldArr[2].substring(len - 1, len);
//			}
//			apInfoArr.push(apInfo);
//		}
//		
//		console.log(apInfoArr);
//		return apInfoArr;
//    }
	
	//解析命令返回的ap信息并存储
	function parseApInfo(res, version) {
		if (res.match(/Invalid input/i) != null) {
			isNewAcVersion = false;
			alert(undefined, "AC版本太旧，无法正确获取全部的AP信息，请先升级AC！");
			return [];
		}
		
		var resArr = res.split(/\r?\n/g);
		var apInfoStartIndex = 0;
		var apInfo = [];
		var apInfoFilter = [];
		
		//10.x Ac判断是否支持新命令
		if (version == "10.x") {
			if (resArr[1].match(/Cnt/i) == null) {
				isNewAcVersion = false;
				alert(undefined, "AC版本太旧，无法正确获取全部的AP信息，请先升级AC！");
				return [];
			}
		}
		
		for (var i = 1; i <= resArr.length - 2; i++) {
			if (resArr[i].match(/^-+\s+-+/) != null) {
				apInfoStartIndex = i + 1;	//从----- ----行起下一行到倒数第二行是当前上线ap的信息
				break;
			}
		}
		
		for (var i = apInfoStartIndex; i <= resArr.length - 2; i++) {
			var tmp_apInfo = {};
			var resField = resArr[i].split(/\s{2,}/g);
			tmp_apInfo.name = resField[0];
			tmp_apInfo.hw_ver = resField[1];
			tmp_apInfo.soft_ver = version;
			tmp_apInfo.num = resField[2];
			apInfo.push(tmp_apInfo);
		}
		
		//剔除数组中相同的项(这里好像并不会重复)	
		for (var i = 0; i < apInfo.length; i++) {
			var exist = false;
			for (var j = 0; j < apInfoFilter.length; j++) {
				if (apInfo[i].name == apInfoFilter[j].name && apInfo[i].hw_ver == apInfoFilter[j].hw_ver) {
					exist = true;
					break;
				}
			}
			if (exist == false) {
				apInfoFilter.push(apInfo[i]);
			}
		}
		
		return apInfoFilter;
	}
	
//	//解析show ver all返回的ap信息并存储
//	function parseApInfo_10x(res) {
//		if (res.match(/Invalid input/i) != null) {
//			jGlobal.oneUpgrade.apInfo = [];
//			return;
//		}
//		
//		var resArr = res.split(/\r?\n/g);
//		var apInfoStartIndex = 0;
//	
//		var tmp_ID = [];
//		var tmp_Version = [];
//		var apInfo = [];
//		var apInfoFilter = [];
//		
//		for (var i = 1; i <= resArr.length - 2; i++) {
//			if (resArr[i].match("Product ID") != null) {
//				var tmpArr = resArr[i].split(/\s+/);
//				var tmpArr = tmpArr[4];
//				tmp_ID.push(tmpArr);
//				apInfoStartIndex = apInfoStartIndex + 1;
//			} else if (resArr[i].match("Hardware version") != null) {
//				var tmpArr = resArr[i].split(/\s+/);
//				var tmpArr = tmpArr[4];
//				tmp_Version.push(tmpArr);
//			}
//		}
////		console.error(tmp_ID);
////		console.error(tmp_Version);
//		for (var i = 0; i < apInfoStartIndex; i++) {
//			var tmp_apInfo = {};
//			tmp_apInfo.name = tmp_ID[i];
//			tmp_apInfo.hw_ver = tmp_Version[i];
//			apInfo.push(tmp_apInfo); 
//		}
////		console.error(apInfo);
//		for (var i = 0; i < apInfo.length; i++) {
//			var num = false;
//			for(var j = 0; j < apInfoFilter.length; j++){
//				if (apInfoFilter[j].name == apInfo[i].name && apInfoFilter[j].hw_ver == apInfo[i].hw_ver){
//					num = true;
//					break;
//				}
//			}
//			if (num == false) {
//				apInfoFilter.push(apInfo[i]);
//			}
//		}
////		console.error(apInfoFilter);
//		jGlobal.oneUpgrade.apInfo = apInfoFilter;
//	}
	
	function upgradeOperation(operation) {
		var selectAc = $("#selectDeviceTable").bootstrapTable('getSelections');
		if (selectAc.length < 1) {
			alert(undefined, "请选择一台设备来进行升级！");
			return;
		}

		jGlobal.oneUpgrade.upgradeMode = operation;

		$("#progress_connectAllDev").text('0%');
        $("#progressBar_connectAllDev").css('width', '0%');
        $("#dlg_connectAllDevProgress").modal('show');

        selectDevInfo = {};
        initAndConnectAllDevice(selectAc);
	}

	function init() {
		initWindowEvent();
		initPageStatistic();
		initVariable();
		removeGlobalEvent();
		initTable();
		initEvent();
		initDom();
		resize();
		initGlobalEvent();
		
		function initWindowEvent() {
			window.operateStyle = operateStyle;

			window.cancelConnectAllDev = cancelConnectAllDev;
		}
		function initPageStatistic() {
			statRecordEle("oneUpgrade#acSelectDevice");
		}
		function initVariable() {
			jGlobal.oneUpgrade.apInfo = [];
			jGlobal.oneUpgrade.isOperators = false;
			jGlobal.oneUpgrade.originAcVersion = null;
			
			acSelectDevice = [];
			selectDevInfo = {};
			isNewAcVersion = true;
            gotoNextPageFlag = true;
		}
		function removeGlobalEvent() {
			global.devicesIns.removeAllListeners("deviceConnected");
			global.devicesIns.removeAllListeners("deviceError");
			global.devicesIns.removeAllListeners("deviceDisconnected");
		}
		function initTable() {
			$('#selectDeviceTable').bootstrapTable({
		        data: [],
		        onCheck: function(row) {		        	
					if ($.inArray(row, acSelectDevice) === -1) {	
						acSelectDevice = [];
						acSelectDevice.push(row);
//						$("#selectedDevBtn").text("已选设备(" + acSelectDevice.length + "台)");
					}
				
				}
//				onCheckAll: function(rows) {
////					jGlobal.oneUpgrade.selectedDevice = []; 	//不能置空
////					jGlobal.oneUpgrade.selectedDevice = rows;
//					for (var i = 0; i < rows.length; i++) {
//						if ($.inArray(rows[i], acSelectDevice) === -1) {
//							acSelectDevice.push(rows[i]);
//						}
//					}
//					$("#selectedDevBtn").text("已选设备(" + acSelectDevice.length + "台)");
//				}
		    });
			$('#selectedDeviceTable').bootstrapTable({
		        data: []
		    });
			
			$(".fixed-table-body").addClass('custom-scroll');
			$("#selectDeviceTable").show();
			
			getAndShowDevInfo();
		}
		function initEvent() {
		    $("#addDevBtn").click(function () {
                var groupId = $('#selectGroup').val();
                    groupId = groupId.split(':')[0];
                if (groupId == "null") {
                    groupId = null;
                }

		        var cb = function (err, res) {
                    if (err != null) {
                        alert(undefined, "设备添加失败!失败原因: " + err.toString());
                        return;
                    }
                    addDevInfoToTable(deviceManage.searchDeviceByGroupId(groupId));
                };

                var CommonAddDevice = new commonAddDevice('add', {"groupId": groupId}, cb);
                CommonAddDevice.init();
            });

			$("#selectGroup").change(function() {		    	
		    	var groupId = $('#selectGroup').val();
		    	groupId = groupId.split(':')[0];
		    	if (groupId == "null") {
		    		groupId = null;
		    	}

		    	addDevInfoToTable(deviceManage.searchDeviceByGroupId(groupId));
		    });
			
//			$('#selectedDeviceModal').on('show.bs.modal', function() {				
//				$('#selectedDeviceTable').bootstrapTable('load', acSelectDevice);
//				$('#selectedDeviceTable').bootstrapTable('resetView', {height : 400});
//				
//				addCssForTable();
//			});
//			
//			$('#selectedDeviceModal').on('hide.bs.modal', function () {
//				$("#selectedDevBtn").text("已选设备(" + acSelectDevice.length + "台)");
//			});

            window.operateEvents = {
                'click .edit': function (e, value, row, index) {
                    var groupId = $('#selectGroup').val();
                    groupId = groupId.split(':')[0];
                    if (groupId == "null") {
                        groupId = null;
                    }

                    var cb = function (err, res) {
                        if (err != null) {
                            alert(undefined, "设备编辑失败!失败原因: " + err.toString());
                            return;
                        }
                        addDevInfoToTable(deviceManage.searchDeviceByGroupId(groupId));
                    }

                    var CommonAddDevice = new commonAddDevice('edit', row, cb);
                    CommonAddDevice.init();
                },
                // 'click .immediateUpgrade': function (e, value, row, index) {
                //     $("#progress_connectAllDev").text('0%');
                //     $("#progressBar_connectAllDev").css('width', '0%');
                //     $("#dlg_connectAllDevProgress").modal('show');

                //     selectDevInfo = {};
                //     initAndConnectAllDevice([row]);
                // }
            };

            // 立即升级
            $("#immediateUpgradeBtn").click(function() {
				upgradeOperation('immediate');
            });

            // 定时升级
            $("#scheduleUpgradeBtn").click(function() {
				upgradeOperation('schedule');
            });
			
			$("#batchConnect").click(function() {
                var acSelect = $("#selectDeviceTable").bootstrapTable('getSelections');
                if (acSelect.length == 0) {
                    alert(undefined, "请选择一台设备！");
                    return;
                }
			    
			    $("#progress_connectAllDev").text('0%');
	            $("#progressBar_connectAllDev").css('width', '0%');
			    $("#dlg_connectAllDevProgress").modal('show');

                selectDevInfo = {};
			    initAndConnectAllDevice(acSelect);
			});
			
//		    (当前正常状态是connecting)
		    global.devicesIns.on("deviceConnected", function(devName) {
		    	if (jGlobal.oneUpgrade.batchConnectFlag == true) { //批量连接时，连接上某台设备后，再断开当前连接的设备,修改状态为closing
//		        	console.error("deviceConnected", devName);
		        	
		        	if (jGlobal.oneUpgrade.multiDevConnectStatus[devName] != 'connecting') {
			    		return;
			    	} else {
			    		jGlobal.oneUpgrade.multiDevConnectStatus[devName] = jGlobal.changeDevStatus(devName, jGlobal.oneUpgrade.multiDevConnectStatus[devName], 'connected');
			    		
			    		// 连接上ac设备,先解析获取ap的信息,再获取推荐版本
			    		selectDevInfo = global.devicesIns.getDeviceInfoByDeviceName(devName);
			    		console.log('设备信息: ', selectDevInfo);

			    		if (!selectDevInfo.deviceType) {
                            gotoNextPageFlag = false;
                            alert(undefined, '未知设备，暂不支持使用工具升级！');
                            closeDeviceLinkByName(devName);
			    		    return;
                        }

                        if (selectDevInfo.deviceType != "Wireless") {
                            gotoNextPageFlag = false;
                            alert(undefined, '该设备不是无线设备，暂不支持使用工具升级！');
                            closeDeviceLinkByName(devName);
                        } else {
                            if (selectDevInfo.deviceModel.search(/AP/i) != -1 || selectDevInfo.softVer.search(/AP/i) != -1) { // 无线AP设备
                                gotoNextPageFlag = false;
                                alert(undefined, 'AP需要通过AC来升级，请前往设备管理菜单添加AC设备。');
                                closeDeviceLinkByName(devName);
                            } else { // 无线AC设备
                                if (selectDevInfo.softVer.indexOf("10.") != -1 || selectDevInfo.softVer.search(/Mid/i) != -1) {
                                    gotoNextPageFlag = false;
                                    alert(undefined, '10.x版本的AC暂不支持使用工具升级！');
                                    closeDeviceLinkByName(devName);
                                    return;
                                }

                                var oneAcUpgradeIns = new oneAcUpgrade(global.devicesIns, false);
                                if (!oneAcUpgradeIns.checkIfCanUpgrade(selectDevInfo.deviceName)) {
                                    gotoNextPageFlag = false;
                                    alert(undefined, '这款型号的AC暂不支持使用工具升级！');
                                    closeDeviceLinkByName(devName);
                                    return;
                                }

                                gotoNextPageFlag = true;
                                var params = {};
                                params.deviceName = devName;
                                global.oneUpgradeIns.determinRecommendedVersion(params, determinRecommendedVersionCallback, devName); //连接上一台设备后，获取该设备的升级版本

                                // determinRecommendedVersionCallback(devName);
                            }
                        }
			    	}
		    	}
		    });
		    
		  // 1.设备端因为故障主动断开,会收到error消息,再收到disconnect消息; 2.连接设备无法连上,会收到error消息,再收到disconnect消息. (当前正常状态是connecting connected upgrade restart)
		    global.devicesIns.on("deviceError", function(res) {
		    	var errMsg = res.errInfo;
		    	if (res.errInfo.indexOf("超时") != -1) {
		    		errMsg += "。可能原因是密码错误，请尝试将密码改为admin后重试。";
		    	}
		    	if (res.errInfo.indexOf("密码错误") != -1) {
		    		errMsg += "。请输入正确的密码，如果忘记密码，可以尝试将密码改为admin后重试。";
		    	}

	            setTimeout(function() {
                    alert(undefined, errMsg);
                }, 300);

		    	if (jGlobal.oneUpgrade.batchConnectFlag == true) {
//		    		console.error("deviceError", res.deviceName);

		        	if (jGlobal.oneUpgrade.multiDevConnectStatus[res.deviceName] == 'connecting') { //若当前设备处于connecting状态,说明该设备已尝试连接但无法连上,主动调用接口断开连接
						global.devicesIns.closeDeviceLink(res.deviceName);
						jGlobal.oneUpgrade.multiDevConnectStatus[res.deviceName] = jGlobal.changeDevStatus(res.deviceName, jGlobal.oneUpgrade.multiDevConnectStatus[res.deviceName], 'closing');       	    	                    
			    		return;
					} else if (jGlobal.oneUpgrade.multiDevConnectStatus[res.deviceName] == 'connected') { //原则上批量连接时不会处于该状态,批量升级时有可能处于该状态
						global.devicesIns.closeDeviceLink(res.deviceName);
						jGlobal.oneUpgrade.multiDevConnectStatus[res.deviceName] = jGlobal.changeDevStatus(res.deviceName, jGlobal.oneUpgrade.multiDevConnectStatus[res.deviceName], 'closing');
						return;
					} else if (jGlobal.oneUpgrade.multiDevConnectStatus[res.deviceName] == 'closing' || jGlobal.oneUpgrade.multiDevConnectStatus[res.deviceName] == 'init') {
						return;
					} else if (jGlobal.oneUpgrade.multiDevConnectStatus[res.deviceName] == 'upgrade') { //原则上批量连接时不会处于该状态,批量升级时有可能处于该状态
						jGlobal.oneUpgrade.multiDevConnectStatus[res.deviceName] = jGlobal.changeDevStatus(res.deviceName, jGlobal.oneUpgrade.multiDevConnectStatus[res.deviceName], 'closing');
						alert(undefined, '设备(' + res.deviceName + ')升级失败！错误信息: ' + res.errInfo);
						return;
					} else if (jGlobal.oneUpgrade.multiDevConnectStatus[res.deviceName] == 'restart') { //原则上批量连接时不会处于该状态,批量升级时有可能处于该状态
						jGlobal.oneUpgrade.multiDevConnectStatus[res.deviceName] = jGlobal.changeDevStatus(res.deviceName, jGlobal.oneUpgrade.multiDevConnectStatus[res.deviceName], 'closing');
						alert(undefined, '设备(' + res.deviceName + ')重启失败！错误信息: ' + res.errInfo);
						return;
					}
		    	}
		    });

		    /* 1.设备端因为故障主动断开,会收到error消息,再收到disconnect消息; 2.设备端正常断开,不发送error消息,只会接收到disconnect消息;
			   3.程序主动断开,不发送error消息,只会接收到disconnect消息(调用断开连接接口后都会置为closing);
			   4.连接设备无法连上,会收到error消息,再收到disconnect消息.
			   (当前正常状态是closing) (注:connecting upgrade restart原则上不会跑到, 因为升级或重启时若出错状态已被置为closing, connected在批量连接时，连接上设备后断开连接，状态置为closing;
			   	批量升级时，连接上设备后调用升级接口，状态置为upgrade) */
		    global.devicesIns.on("deviceDisconnected", function(devName) {
		    	if (jGlobal.oneUpgrade.batchConnectFlag == true) {
//		        	console.error("deviceDisconnected", devName);
		        	
		        	if (jGlobal.oneUpgrade.multiDevConnectStatus[devName] == "connecting") { //原则上不会跑到, 连接不上或程序主动断开状态均已被置为closing
			            return;
			    	} else if (jGlobal.oneUpgrade.multiDevConnectStatus[devName] == "connected") { //原则上不会跑到。批量连接时，连接上设备后断开连接，状态置为closing;批量升级时，连接上设备后调用升级接口，状态置为upgrade
			    		return;
			    	} else if (jGlobal.oneUpgrade.multiDevConnectStatus[devName] == "closing") {
		    			if (jGlobal.oneUpgrade.connect_forcedCancelFlag == false) { //说明该closing状态不是由强制取消改变的
		    				jGlobal.oneUpgrade.connectDevNum_getInfo++;
			    			
			    			/* 更新连接设备进度条 */
		        	        var percent = Math.floor((jGlobal.oneUpgrade.connectDevNum_getInfo / jGlobal.oneUpgrade.connectDevNum) * 100);
		        	        $("#progress_connectAllDev").text(percent + '%');
		    	            $("#progressBar_connectAllDev").css('width', percent + '%');
			    		}
		    			jGlobal.oneUpgrade.connectDevNum_disconnect--;
		    			jGlobal.oneUpgrade.multiDevConnectStatus[devName] = jGlobal.changeDevStatus(devName, jGlobal.oneUpgrade.multiDevConnectStatus[devName], 'init');
			    	} else if (jGlobal.oneUpgrade.multiDevConnectStatus[devName] == "upgrade") { //原则上不会跑到, 升级或重启时若出错状态已被置为closing
			    		jGlobal.oneUpgrade.multiDevConnectStatus[devName] = jGlobal.changeDevStatus(devName, jGlobal.oneUpgrade.multiDevConnectStatus[devName], 'init');
			    		alert(undefined, '设备(' + devName + ')升级失败！');
			    		return;
			    	} else if (jGlobal.oneUpgrade.multiDevConnectStatus[devName] == "restart") { //原则上不会跑到, 升级或重启时若出错状态已被置为closing
			    		jGlobal.oneUpgrade.multiDevConnectStatus[devName] = jGlobal.changeDevStatus(devName, jGlobal.oneUpgrade.multiDevConnectStatus[devName], 'init');
			    		alert(undefined, '设备(' + devName + ')重启失败！');
			    		return;
			    	} else if (jGlobal.oneUpgrade.multiDevConnectStatus[devName] == "init") {
			    		return;
			    	}
		        	
		        	/* 所有设备均已尝试过连接 */
		        	if (jGlobal.oneUpgrade.connectDevNum_getInfo == jGlobal.oneUpgrade.connectDevNum) {
		        		$("#dlg_connectAllDevProgress").modal('hide');
		        		
						// /* 刷新表格 */
						// var groupId = $('#selectGroup').val();
						// groupId = groupId.split(':')[0];
						// if (groupId == "null") {
						// 	groupId = null;
						// }
						// addDevInfoToTable(deviceManage.searchDeviceByGroupId(groupId));
						
						// 断开设备后,如果是无线产品,进入下一页面;否则提示用户
						if ($.isEmptyObject(selectDevInfo)) {
                            // setTimeout(function() {
                            //     alert(undefined, '连接不上设备，无法升级！');
                            // }, 300);
						} else {
                            if (gotoNextPageFlag) {
                                setTimeout(function() {
                                    var curElement = ".main_content", nextPageUrl = "./oneUpgrade/html/acSelectVersion.html";
                                    global.enterPageCallback(curElement, nextPageUrl);
                                }, 300);
                            }
                        }
		        	}
		        	
		        	console.error("connectDevNum_disconnect", jGlobal.oneUpgrade.connectDevNum_disconnect);
		        	/* 尝试过连接的设备均已断开连接 */
		        	if (jGlobal.oneUpgrade.connectDevNum_disconnect == 0) {
		        		jGlobal.oneUpgrade.batchConnectFlag = false;
		        		if (jGlobal.oneUpgrade.connect_forcedCancelFlag == true) {
		        			alert(undefined, "所有设备均已断开连接!", function() {
		        				jGlobal.oneUpgrade.connect_forcedCancelFlag = false;
		        			});
		        		}
		        	}
		    	}
		    });
		}
		function initDom() {
			$('#connectDevModal').modal({
				backdrop: 'static',
				show: false,
                keyboard: false
			});
			// $('#selectedDeviceModal').modal({
			// 	backdrop: 'static',
			// 	show: false
			// });
			$('#dlg_connectAllDevProgress').modal({
				backdrop: 'static',
				show: false,
                keyboard: false
			});
			
			//查询当前分组
			var select_id = "selectGroup";
	    	$("#" + select_id).children().remove();
	    	var $option = $("<option>");
	    	$option.val("null:全部分组");
	    	$option.text("全部分组");
	    	$("#" + select_id).append($option);
			global.devicesIns.queryAllSubGroups("selectGroup", deviceManage.queryAllSubGroupsCbk);
		}
		function resize() {
			var client_h = document.documentElement.clientHeight;
			var head_h = $(".main_menu").height();
			var body_h = client_h - head_h;
			
			$('#selectDeviceTable').bootstrapTable('resetView', {height : body_h - 80});
		}
		function initGlobalEvent() {
			global.exitPageCallback.exitFun = function () {
				removeGlobalEvent();
				return true;
			}
		}
	}
	exports.init = init;
});