define(function (require, exports, module) {
    var global = require("../../js/global");
    var jGlobal = require("./oneUpgradeGlobal");
    var deviceManage = require("../../deviceManage/js/deviceManage");
    var getCompileNum = 0;

    function getAndShowDevInfo() {
        function queryDevInfoCallback(error, result) {
            if (error == null) {
                addDevInfoToTable(result);
            } else {
                alert(undefined, "读取设备数据失败！");
            }
        }
        global.devicesIns.getDeviceConfigInfoAll(queryDevInfoCallback);
    }

    function addDevInfoToTable(devInfo) {
        //		console.log(devInfo);
        for (var i = 0; i < devInfo.length; ++i) {
            if (devInfo[i].protocal == "serial") {
                devInfo[i].conne_type = devInfo[i].protocal;
                devInfo[i].host_com = devInfo[i].comNum;
                devInfo[i].port = devInfo[i].baudrate;
            } else {
                devInfo[i].conne_type = devInfo[i].protocal;
                devInfo[i].host_com = devInfo[i].host;
                devInfo[i].port = devInfo[i].port;
            }

            if (devInfo[i].groupName === null || devInfo[i].groupName === undefined || devInfo[i].groupName === '') {
                devInfo[i].groupName = "未分组";
            }
        }

        $('#selectDeviceTable').bootstrapTable('load', devInfo);
        return;
    }

    function operateStyle(value) {
        return '<div class="delete" style="cursor: pointer; font-size: 18px; color: #b8b8b8; margin-top: -5px;" data-toggle="tooltip" data-placement="right" title="点击将删除此设备">&times;</div>';
    }

    function deleteSelectedDev(row, index) {
        var selectedDeviceCopy = jGlobal.oneUpgrade.selectedDevice;
        jGlobal.oneUpgrade.selectedDevice = [];
        for (var i = 0; i < selectedDeviceCopy.length; i++) {
            if (row.deviceName !== selectedDeviceCopy[i].deviceName) {
                jGlobal.oneUpgrade.selectedDevice.push(selectedDeviceCopy[i]);
            }
        }
        $('#selectedDeviceTable').bootstrapTable('load', jGlobal.oneUpgrade.selectedDevice);

        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);
    }

    //云端只会推荐大版本的升级包，热补丁的升级包通过下载数据库json文件匹配后再下载来实现
    function determinRecommendedVersionCallback(res) {
        var devName = res.addParams;

        console.error("--------------------------------------------");
        console.error("设备: " + devName + " 的云端信息: ", res);

        /* 		var objectTmp = {};
                if (res.retParams.softwareVersion == null || res.retParams.fileName == null) {
                    jGlobal.oneUpgrade.multiDevUpgradeVersion[devName] = "";
                } else {
                    objectTmp.versionCode = res.retParams.softwareVersion;
                    objectTmp.versionName = res.retParams.fileName;
                    objectTmp.fileMd5 = res.retParams.fileMd5;
                    jGlobal.oneUpgrade.multiDevUpgradeVersion[devName] = objectTmp;
                } */

        /* 原大版本升级参数 */
        jGlobal.oneUpgrade.multiDevRcmndVersion[devName] = res.retParams;
        jGlobal.oneUpgrade.multiDevUpgradeVersion[devName] = "";

        /* 新增热补丁参数 */
        jGlobal.oneUpgrade.multiDevRcmndHotFix[devName] = [];
        jGlobal.oneUpgrade.multiDevHotFix[devName] = [];

        // XXX 屏蔽热补丁升级 断开设备
        //jGlobal.oneUpgrade.multiDevConnectStatus[devName] = jGlobal.changeDevStatus(devName, jGlobal.oneUpgrade.multiDevConnectStatus[devName], 'closing');
        //global.devicesIns.closeDeviceLink(devName);
        //return;

        var setProjectIdCbk = function (err, curDevInfo) {
            if (err != null) {
                getCompileNum++;
                console.error("设备: " + devName + " 有板卡获取编译分支失败, 失败原因: " + err);

                //断开设备
                jGlobal.oneUpgrade.multiDevConnectStatus[devName] = jGlobal.changeDevStatus(devName, jGlobal.oneUpgrade.multiDevConnectStatus[devName], 'closing');
                global.devicesIns.closeDeviceLink(devName);

                if (jGlobal.oneUpgrade.selectedDevice.length == getCompileNum) {
                    alert(undefined, "所有的设备获取编译分支均失败！无法进行下一步操作！");
                }

                return;
            }
            console.error("设备: " + devName + " 的信息: ", curDevInfo.moduleInfo);
            var upgradeVersion = {};
            var moduleInfoArry = [];
            var moduleArry = [];
            for (var i = 0; i < curDevInfo.moduleInfo.length; i++) {
                //构造数组，用于获取补丁信息
                var moduleInfo = {};
                moduleInfo.compileVer = curDevInfo.moduleInfo[i].compileVer;
                moduleInfo.moduleModel = curDevInfo.moduleInfo[i].moduleModel;
                moduleInfo.moduleSoftVer = curDevInfo.moduleInfo[i].moduleSoftVer;

                var tmp = curDevInfo.moduleInfo[i].moduleSoftNum;
                var tmp1 = tmp.substring(tmp.length - 4);
                var tmp2 = tmp.substring(tmp.length - 8, tmp.length - 6);
                var tmp3 = tmp.substring(tmp.length - 6, tmp.length - 4);
                moduleInfo.moduleSoftNum = tmp1 + '-' + tmp2 + '-' + tmp3;

                moduleInfo.moduleHardVer = curDevInfo.moduleInfo[i].moduleHardVer;
                moduleInfoArry.push(moduleInfo);

                //构造数组，用于下载数据库补丁到本地
                var module = {};
                module.deviceModel = moduleInfo.compileVer;
                module.softVersion = moduleInfo.moduleSoftVer;
                moduleArry.push(module);
            }
            upgradeVersion.devName = devName;
            upgradeVersion.moduleInfoArry = moduleInfoArry;  //单个设备的板卡信息【用于获取补丁信息】
            upgradeVersion.moduleArry = moduleArry;          //单个设备的板卡信息【用于下载数据库补丁到本地】
            upgradeVersion.deviceInfo = curDevInfo; // 把所有的设备信息都存这里了

            //所有板卡基线版本是否一致
            var isModuleVerAllSame = true;

            //XXX 暂时先不判断不一致情况
            /*             for (var i = 0; i < moduleInfoArry.length; i++) {
                           if (curDevInfo.softVer != moduleInfoArry[i].moduleSoftVer) {
                               isModuleVerAllSame = false;
                               break;
                           }
                        } */

            if (isModuleVerAllSame == true) {
                var hotFixBinInfoArry = []; 	//hotFixBinInfoArry的结构: [[{},{}], [{},{}], [{},{}]]
                var noHotFixJson = [];
                var needLoadFixJson = {};
                upgradeVersion.judgeASID = true;

                var _checkASIDFunc = function (res, keyword) {
                    console.log(res);
                    if (upgradeVersion.judgeASID == true) {
                        if ((typeof res === 'string') && res.replace(keyword).indexOf(keyword) === -1) {
                            upgradeVersion.judgeASID = false;
                        }
                    }
                };

                // 过滤ASID补丁
                var asidCmdList = [
                    {
                        name: 'run-system-shell',
                        value: function (res) {
                        },
                        args: ''
                    },
                    {
                        name: 'lsmod | grep rg_hm_path',
                        value: function (res) {
                            _checkASIDFunc(res, 'rg_hm_path');
                        },
                        args: ''
                    },
                    {
                        name: 'lsmod | grep mips_cpu_asid_patch',
                        value: function (res) {
                            _checkASIDFunc(res, 'mips_cpu_asid_patch');
                        },
                        args: ''
                    },
                    {
                        name: 'lsmod | grep test_asid',
                        value: function (res) {
                            _checkASIDFunc(res, 'test_asid');
                        },
                        args: ''
                    },
                    {
                        name: 'exit',
                        value: function (res) {
                            // 这里添加扫尾操作
                            console.log('upgradeVersion.judgeASID:', upgradeVersion.judgeASID);
                            jGlobal.oneUpgrade.multiDevVersion.push(upgradeVersion);

                            //断开设备
                            jGlobal.oneUpgrade.multiDevConnectStatus[devName] = jGlobal.changeDevStatus(devName, jGlobal.oneUpgrade.multiDevConnectStatus[devName], 'closing');
                            global.devicesIns.closeDeviceLink(devName);
                        },
                        args:''
                    }

                ];


                //过滤掉设备上之前已经打过的补丁
                global.devicesIns.execCmd(devName, "show sp-upgrade status", function (res) {
                    console.error(res);
                    upgradeVersion.res1 = res;
                    global.devicesIns.execCmd(devName, "show sp-patch slot all", function (response) {
                        console.error(response);
                        upgradeVersion.res2 = response;

						
						//判断旧框架已经打上相关ASID补丁
                        global.devicesIns.execCmdList(devName, asidCmdList);
                    });
                });
            } else {
                console.log("设备: " + devName + " 有板卡的基线版本和其他的板卡不一致!!!");
                //断开设备
                jGlobal.oneUpgrade.multiDevConnectStatus[devName] = jGlobal.changeDevStatus(devName, jGlobal.oneUpgrade.multiDevConnectStatus[devName], 'closing');
                global.devicesIns.closeDeviceLink(devName);
            }
        }

        var devInfo = global.devicesIns.getDeviceInfoByDeviceName(devName);
        var devTypeDetail = global.jsUtil.getDeviceTagsByModel(devInfo.deviceModel, devInfo.softVer).join();
        if (devTypeDetail.indexOf('11xSwitchBigBox') != -1 && devInfo.hasLc == true) {
            //var hotFixUpgrade = window.require("../../common/js/hotFixUpgrade");
            jGlobal.oneUpgrade.has11xBigBoxSwitch = true;
            var hotFixUpgradeIns = new global.hotFixUpgrade(global.devicesIns, false);
            hotFixUpgradeIns.setProjectId(devName, setProjectIdCbk);
        } else {
            //断开设备
            console.log('设备:', devName, ' 不支持热补丁升级', ' 设备类型:', devTypeDetail, ' 是否有线卡:', (devInfo.hasLc ? '有' : '无'));
            jGlobal.oneUpgrade.multiDevConnectStatus[devName] = jGlobal.changeDevStatus(devName, jGlobal.oneUpgrade.multiDevConnectStatus[devName], 'closing');
            global.devicesIns.closeDeviceLink(devName);
        }
    }

    function loadFixPage() {
        //从云端下载本地不能获取到补丁数据库		
        var multiDevVersion = jGlobal.oneUpgrade.multiDevVersion;   //批量设备的设备名和每个设备的所有板卡信息
        console.error("热补丁升级的设备信息: ", multiDevVersion);
        var cnt = 0;      //下载完成个数
        var loadFixFinish = [];     //本地有的补丁

        var operFn = function (err, results) {
            cnt++;
            console.error(results);
            var percent = Math.floor((cnt / results.hotfixes.length) * 100);

            $("#progress_loadFix").text(percent + '%');
            $("#progressBar_loadFix").css('width', percent + '%');
            if (err == null) {
                loadFixFinish.push(results.cur)
            }
        };

        var fixLoadSucess = function (err, results) {

            // 即使err != null 也要执行
            if (err == null) {
                console.error("云端未下载成功的补丁信息：", results);
                var obj = jGlobal.oneUpgrade.multiDevRcmndHotFix;
                var existenceLoadFix = {};
                for (var s in obj) {
                    var arr1 = obj[s];
                    var finishOneDevHotFix = [];
                    for (var j = 0; j < arr1.length; j++) {
                        var flag = false;
                        for (var i = 0; i < results.length; i++) {
                            if (arr1[j].name == results[i].name) {
                                flag = true;
                                break;
                            }
                        }
                        if (flag == false) {
                            finishOneDevHotFix.push(arr1[j])
                        }
                    }
                    jGlobal.oneUpgrade.multiDevRcmndHotFix[s] = finishOneDevHotFix;
                }
            } else {
                console.error('in fixLoadSucess error:', err);
                for (var i in jGlobal.oneUpgrade.multiDevRcmndHotFix) {
                    jGlobal.oneUpgrade.multiDevRcmndHotFix[i] = [];
                }
            }

            console.error("云端下载后设备所存在的补丁信息：", jGlobal.oneUpgrade.multiDevRcmndHotFix);

            // 这里要遍历每一个设备,找出无需推荐的补丁

            multiDevVersion.forEach(function (device) {
                //moduleInfoArry
                console.log('正在设备:', device.devName, ' 过滤额外禁止打上的补丁');
                if (Array.isArray(jGlobal.oneUpgrade.multiDevRcmndHotFix[device.devName])) {
                    jGlobal.oneUpgrade.multiDevRcmndHotFix[device.devName] = global.hotfixMgr.ignore(device.deviceInfo, device.judgeASID, jGlobal.oneUpgrade.multiDevRcmndHotFix[device.devName]);
                }
            });


            $("#loadFixProgress").modal('hide');
            setTimeout(function () {
                //		        	    	$(".main_content").load("./oneUpgrade/html/selectVersion.html");

                var curElement = ".main_content", nextPageUrl = "./oneUpgrade/html/selectVersion.html";
                global.enterPageCallback(curElement, nextPageUrl);
            }, 300);
        };

        var ruturnHotFix = function (err) {
            console.error(err);

            // 即使err != null，也要执行
            var multiDevHotFixFile = [];                 //批量设备的补丁信息
            for (var m = 0; m < multiDevVersion.length; m++) {
                var devName = multiDevVersion[m].devName;
                var moduleInfoArry = multiDevVersion[m].moduleInfoArry;                 //一台设备的所有板卡信息
                var res1 = multiDevVersion[m].res1;                     //用来过滤已打过补丁的命令
                var res2 = multiDevVersion[m].res2;                     //用来过滤已打过补丁的命令
                var hotFixBinInfoArry = [];
                for (var i = 0; i < moduleInfoArry.length; i++) {
                    var hotFixBinInfo = global.hotfixMgr.getHotfix(moduleInfoArry[i].compileVer, moduleInfoArry[i].moduleSoftVer, moduleInfoArry[i].moduleSoftNum, moduleInfoArry[i].moduleHardVer);
                    hotFixBinInfoArry.push(hotFixBinInfo);
                }
                console.error("设备" + devName + "上的补丁信息", hotFixBinInfoArry);
                //过滤掉相同的补丁版本
                var hotFixBinInfoFilter = [];
                for (var i = 0; i < hotFixBinInfoArry.length; i++) {
                    var tmpArry = hotFixBinInfoArry[i];
                    for (var j = 0; j < tmpArry.length; j++) {
                        var flag = false;
                        for (var k = 0; k < hotFixBinInfoFilter.length; k++) {
                            if (tmpArry[j].name == hotFixBinInfoFilter[k].name) {
                                flag = true;
                                break;
                            }
                        }
                        if (!flag) {
                            hotFixBinInfoFilter.push(tmpArry[j]);
                        }
                    }
                }

                //过滤掉设备上之前已经打过的补丁
                var hotFixBinInfoFinal = [];
                var needPatchFrame = false
                if (!global.hotfixMgr.hasUpgradeFrame(res1, moduleInfoArry.length)) {
                    // 说明补丁框架没有打成功，因此需要重新打补丁框架
                    needPatchFrame = true;
                }
                if (res2.match(/Invalid input/i) != null) { //没有该命令说明是旧框架无需过滤
                    hotFixBinInfoFinal = hotFixBinInfoFilter;
                } else {
                    hotFixBinInfoFinal = global.hotfixMgr.findFailedHotfixes(res2, hotFixBinInfoFilter, !needPatchFrame);
                }

                //hotFixBinInfoFinal = hotFixBinInfoFilter;
                //对补丁版本进行排序,升级补丁放在前面
                var sortHotFixBinInfoFinal = [];
                var tmp_upgradePatch = [];
                var tmp_commonPatch = [];
                for (var i = 0; i < hotFixBinInfoFinal.length; i++) {
                    if (hotFixBinInfoFinal[i].isUpgradeFrame == true) {
                        tmp_upgradePatch.push(hotFixBinInfoFinal[i]);
                    } else {
                        tmp_commonPatch.push(hotFixBinInfoFinal[i]);
                    }
                }
                sortHotFixBinInfoFinal = tmp_upgradePatch.concat(tmp_commonPatch);
                jGlobal.oneUpgrade.multiDevRcmndHotFix[devName] = sortHotFixBinInfoFinal;
                multiDevHotFixFile = multiDevHotFixFile.concat(hotFixBinInfoFinal);
            }
            console.log("所有设备的补丁信息：", jGlobal.oneUpgrade.multiDevRcmndHotFix);

            //过滤批量设备的补丁信息
            var hotFixBinInfoFilterFinish = [];
            for (var i = 0; i < multiDevHotFixFile.length; i++) {
                var flag = false;
                for (var j = 0; j < hotFixBinInfoFilterFinish.length; j++) {
                    if (multiDevHotFixFile[i].name == hotFixBinInfoFilterFinish[j].name) {
                        flag = true;
                        break;
                    }
                }
                if (!flag) {
                    hotFixBinInfoFilterFinish.push(multiDevHotFixFile[i]);
                }
            }

            console.error("过滤后，需要去云端批量下载的补丁信息：", hotFixBinInfoFilterFinish);
            //检测本地是否有补丁文件，若没有则去云端下载
            global.hotfixMgr.saveHotfixFiles(hotFixBinInfoFilterFinish, true, operFn, fixLoadSucess);
        };

        var args = [];
        for (var i = 0; i < multiDevVersion.length; i++) {
            var moduleArry = multiDevVersion[i].moduleArry;
            args = args.concat(moduleArry);
        }
        console.error("热补丁数据库下载参数: ", args);
        global.hotfixMgr.requestDatabase(args, false, undefined, ruturnHotFix);
    }

    //用户点击时不添加相同IP的设备
    function filterSameIP(ele, array) {
        var flag = true;
        for (var i = 0; i < array.length; i++) {
            if (ele.host == array[i].host) {
                flag = false;
                break;
            }
        }

        return flag;
    }

    function init() {
        initWindowEvent();
        initPageStatistic();
        initVariable();
        removeGlobalEvent();
        initTable();
        initEvent();
        initDom();
        resize();
        initGlobalEvent();

        function initWindowEvent() {
            window.operateStyle = operateStyle;
            window.operateEvents = {
                'click .delete': function (e, value, row, index) {
                    deleteSelectedDev(row, index);
                }
            };
            window.cancelConnectAllDev = cancelConnectAllDev;
        }
        function initPageStatistic() {
            statRecordEle("oneUpgrade#selectDevice");
        }
        function initVariable() {
            jGlobal.oneUpgrade.selectedDevice = [];

            jGlobal.oneUpgrade.multiDevVersion = [];
            jGlobal.oneUpgrade.has11xBigBoxSwitch = false;
            getCompileNum = 0;
        }
        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, jGlobal.oneUpgrade.selectedDevice) === -1) {
                        if (filterSameIP(row, jGlobal.oneUpgrade.selectedDevice)) { //过滤掉相同的ip(对同一台设备不能同时重复升级)
                            jGlobal.oneUpgrade.selectedDevice.push(row);
                            $("#selectedDevBtn").text("已选设备(" + jGlobal.oneUpgrade.selectedDevice.length + "台)");
                        }
                    }
                },
                onCheckAll: function (rows) {
                    for (var i = 0; i < rows.length; i++) {
                        if ($.inArray(rows[i], jGlobal.oneUpgrade.selectedDevice) === -1) {
                            if (filterSameIP(rows[i], jGlobal.oneUpgrade.selectedDevice)) { //过滤掉相同的ip(对同一台设备不能同时重复升级)
                                jGlobal.oneUpgrade.selectedDevice.push(rows[i]);
                            }
                        }
                    }
                    $("#selectedDevBtn").text("已选设备(" + jGlobal.oneUpgrade.selectedDevice.length + "台)");
                }
            });
            $('#selectedDeviceTable').bootstrapTable({
                data: []
            });

            $(".fixed-table-body").addClass('custom-scroll');
            $("#selectDeviceTable").show();

            getAndShowDevInfo();
        }
        function initEvent() {
            $("#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', jGlobal.oneUpgrade.selectedDevice);
                $('#selectedDeviceTable').bootstrapTable('resetView', { height: 400 });

                addCssForTable();
            });

            $('#selectedDeviceModal').on('hide.bs.modal', function () {
                $("#selectedDevBtn").text("已选设备(" + jGlobal.oneUpgrade.selectedDevice.length + "台)");
            });

            $("#batchConnect").click(function () {
                if (jGlobal.oneUpgrade.selectedDevice.length == 0) {
                    alert(undefined, "请至少选择一台设备！");
                    return;
                }

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

                initAndConnectAllDevice(jGlobal.oneUpgrade.selectedDevice);
            });


            $('#syncBtn').click(function () {
                $('#recommandProcess').html('0/0');
                $("#doSync").modal('show');

                var cnt = 0;
                var _processFunc = function (err, results) {
                    if (!err) {
                        cnt++;
                        $('#recommandProcess').html(cnt + '/' + results.hotfixes.length);
                    }

                };
                global.hotfixMgr.sync(_processFunc, function (err, results) {
                    $("#doSync").modal('hide');
                    if (err) {
                        alert(undefined, '有补丁尚未同步成功,请重试');
                    } else {
                        if (results.length == 0) {
                            alert(undefined, '同步成功!所有补丁（' + cnt + '个)已同步');
                        } else {
                            alert(undefined, '成功同步' + cnt + '个补丁,但还有', results.length, '个补丁未能同步,请稍后重试');
                        }

                    }
                });
            });

            //		    (当前正常状态是connecting)
            global.devicesIns.on("deviceConnected", function (devName) {
                if (jGlobal.oneUpgrade.batchConnectFlag == true) { //批量连接时，连接上某台设备后，再断开当前连接的设备,修改状态为closing

                    if (jGlobal.oneUpgrade.multiDevConnectStatus[devName] != 'connecting') {
                        return;
                    } else {
                        jGlobal.oneUpgrade.multiDevConnectStatus[devName] = jGlobal.changeDevStatus(devName, jGlobal.oneUpgrade.multiDevConnectStatus[devName], 'connected');

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

                        //			    		devicesIns.closeDeviceLink(devName);
                        //			    		multiDevConnectStatus[devName] = changeDevStatus(devName, multiDevConnectStatus[devName], 'closing');
                        //		    	    	
                        //			            return;
                    }
                }
            });

            // 1.设备端因为故障主动断开,会收到error消息,再收到disconnect消息; 2.连接设备无法连上,会收到error消息,再收到disconnect消息. (当前正常状态是connecting connected upgrade restart)
            global.devicesIns.on("deviceError", function (res) {
                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');

                        // 这里要确定果真有11.X的箱式交换机设备时,才会去下载补丁。
                        // 否则，不执行下载动作
                        if (jGlobal.oneUpgrade.has11xBigBoxSwitch) {
                            $("#progress_loadFix").text('0%');
                            $("#progressBar_loadFix").css('width', '0%');
                            $("#loadFixProgress").modal('show');
                            setTimeout(function () {
                                loadFixPage();    //批量下载补丁
                            }, 300);
                        } else {
                            // 跳转到其它页面
                            setTimeout(function () {
                                var curElement = ".main_content", nextPageUrl = "./oneUpgrade/html/selectVersion.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
            //			});
            $('#selectedDeviceModal').modal({
                backdrop: 'static',
                show: false
            });
            $('#dlg_connectAllDevProgress').modal({
                backdrop: 'static',
                show: false
            });
            $('#loadFixProgress').modal({
                backdrop: 'static',
                show: 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 - 55 - 65 });
        }
        function initGlobalEvent() {
            global.exitPageCallback.exitFun = function () {
                removeGlobalEvent();
                return true;
            }
        }
    }
    exports.init = init;
});