define(function (require, exports, module) {
    var global = require("../../js/global");
    var isFactoryReset = null;
    var isKeyChange = null;
	var result1 = [];
    
    function appendBodyLayout() {
        var toolsData = global.childToolMgrIns.getToolsInfoByTag();
        //		console.log(toolsData);
        appendToolView(toolsData['all'], $("#thirdApp"));
    }
    
    function appendToolView(datas, parent) {
        if (!datas) return;
        if (typeof datas["diag"] != "object") return;
        
        var len = datas.length;		//画虚线使用
        var $div = $("<div>");
        $div.attr("class", "cover_menu_sort clearfix");
        
        var $div2 = $("<div>");
        $div2.attr("class", "cover_menu_row");
        
        for (var j in datas["diag"]) {	//目前仅需用toolsData['all']['diag']中的内容
            var $div2_t = $("<div>");
            $div2_t.attr("class", "cover_main_menu");
            $div2_t.attr("id", datas["diag"][j].name);
            $div2_t.click(function () {
                global.childToolMgrIns.startTool(this.id, function () { }); // 返回 true or false 进程关闭时 调用callback
                statRecordClick("toolkit#" + this.id);
            });
            
            $div2_t.hover(function () {
                $(this).css("background-color", "#e8eefc");
            }, function () {
                $(this).css("background-color", "#fff");
            });
            
            var img_url = datas["diag"][j].icon.replace(/\\/g, '\/');
            var img_style = 'url(' + img_url + ') no-repeat 16px center transparent';
            $div2_t.css("background", img_style);
            $div2_t.css("background-size", "38px 38px");
            
            var $div2_t_2 = $("<div>");
            $div2_t_2.attr("class", "cover_menu_text");
            var $div2_t_2_1 = $("<div>");
            $div2_t_2_1.attr("class", "cover_menu_title");
            $div2_t_2_1.html(datas["diag"][j].title);
            var $div2_t_2_2 = $("<div>");
            $div2_t_2_2.attr("class", "cover_menu_desc_text");
            $div2_t_2_2.attr("title", datas["diag"][j].description);
            $div2_t_2_2.html(datas["diag"][j].description);
            $div2_t_2.append($div2_t_2_1).append($div2_t_2_2);
            
            $div2_t.append($div2_t_2);
            $div2.append($div2_t);
        }
        --len;
        $div.append($div2);
        parent.append($div);
        if (len >= 1) {
            var $div_bl = $("<div>");
            $div_bl.attr("class", "interval_line");
            parent.append($div_bl);
        }
    }

		function macIp(){
			function queryDevInfoCallback(error, result) {
				if (error == null) {
					for(var i=0;i<result.length;i++){
						result1 = result[i].deviceName;
						global.devicesIns.connectDeviceByDeviceName(result1);
					}
				}
			}
			global.devicesIns.getDeviceConfigInfoAll(queryDevInfoCallback);	
			var wanIntf2 = [];
			var rep = [];
			var rep1 = [];
			var m = 0;			
			global.devicesIns.on("deviceConnected", function(devName) {
					for (var i = 0; i < global.devicesIns.adminItems.length; i++) {
						var instance;
						if (global.devicesIns.adminItems[i].deviceName == devName) {
							instance = global.devicesIns.adminItems[i].instance;
						}else {
							continue;
						}
							instance.exec('show arp',function(response){
								var results = response.trim().split(/\r?\n/);
								for (var i = 2; i < results.length - 1; i++) {
									var item = results[i];
									var _arr = item.split(/\s+/);
									var b=_arr[1];
									var b1 = {};
									var c=_arr[3];
									rep.push(b);
									rep1.push(c);
									for(var j = 1; j<rep.length;j++){
										if((b==rep[j-1])&&(c==rep1[j-1])){
											m++;
										}
									}
									if(b.match(/\d/)!=null){
										b1.macAddress = c ;
									}   
									if((c.match(/\d/)!=null)&&(m==0)){
										b1.relateIp = b ;
										wanIntf2.push(b1);
									}
									if(m!=0){
										m=0;
									}
								}
								$('#macip').bootstrapTable('load', wanIntf2);
								global.devicesIns.closeDeviceLink(devName);
							}); 
					}				
				$('#macip').bootstrapTable({
					data: []
				});				
			});	
        }
 
    function init() {
        initPageStatistic();
        initVariable();
        initEvent();
        initDom();
        resize();
        initGlobalEvent();
        
        function initPageStatistic() {
            statRecordEle("softCenter#softCenter");
        }
        function initVariable() {
            isFactoryReset = null;
            isKeyChange = null;
        }
        function initEvent() {
            global.restoreIns.on("restoreFail", function (res) {
                $("#restoringPassword").hide();
                $("#closeRestore").show();
                $("#restorePassword").show();

                alert(undefined, res);
            });

            global.restoreIns.on("restoreSuccess", function (res) {
                console.log(res);

                $("#restoringPassword").hide();
                $("#restorePassword").show();
                $("#closeRestore").show();
                //				$("#keyChange").hide();
                //				$("#keyShow").show();
                //				$("#keychangeShow").show();				

                if (isFactoryReset) {
                    if (res == "10.") {
                        statRecordEle("softCenter#restorePassword#10XFactorySuccess");
                        alert(undefined, '恢复出厂设置成功<br />配置文件存储在flash中，输入如下命令查看。<br />查看原配置文件内容输入命令：Ruijie#more configtrt.bak');
                        return;
                    } else if (res == "11.") {
                        statRecordEle("softCenter#restorePassword#11XFactorySuccess");
                        alert(undefined, '您的设备已无密码启动(重启后密码将被恢复)，请立即连接串口线修改密码！');
                        return;
                    }
                }
                if (isKeyChange) {
                    statRecordEle("softCenter#restorePassword#changePwdSuccess");
                    alert(undefined, '密码重置成功！请用新密码登陆。<br />配置建存储在flash中，输入如下命令查看。<br />查看原配置文件内容输入命令：Ruijie#more configtrt.bak');
                    return;
                }
            });

            $("#robot").click(function () {
                statRecordEle("softCenter#robot");
                var gui = window.require('nw.gui');
                gui.Shell.openExternal("http://webchat.ruijie.com.cn/live800/chatClient/chatbox.jsp?companyID=8933&configID=17&enterurl=robot&live800_ud_invite=robot");
            });

            $("#factoryReset").click(function () {
                $("#keyChangeContent").hide();
                $("#factoryResetContent").show();
            });

            $("#keyChange").click(function () {
                $("#factoryResetContent").hide();
                $("#keyChangeContent").show();
            });

            $("#checkEnable").click(function () {
                statRecordEle("softCenter#restorePassword#checkEnable");
                if ($("#inputEnable").is(":visible")) {
                    $("#inputEnable").hide();
                } else {
                    $("#inputEnable").show();
                }
            });

            $("#checkTelnet").click(function () {
                statRecordEle("softCenter#restorePassword#checkTelnet");
                if ($("#inputTelnet").is(":visible")) {
                    $("#inputTelnet").hide();
                } else {
                    $("#inputTelnet").show();
                }
            });

            $("#checkConsole").click(function () {
                statRecordEle("softCenter#restorePassword#checkConsole");
                if ($("#inputConsole").is(":visible")) {
                    $("#inputConsole").hide();
                } else {
                    $("#inputConsole").show();
                }
            });

            $("#Key").click(function () {
                statRecordEle("softCenter#restorePassword");
                function getComListCbk(res) {
                    //添加串口
                    $("#factoryResetCom").children().remove();
                    $("#keyChangeCom").children().remove();

                    if (res.length == 0) {
                        global.addOption("无", "无", "factoryResetCom");
                        global.addOption("无", "无", "keyChangeCom");
                    } else {
                        res = res.sort();
                        for (var i = 0; i < res.length; ++i) {
                            global.addOption(res[i], res[i], "factoryResetCom");
                            global.addOption(res[i], res[i], "keyChangeCom");
                        }
                    }
                }

                global.restoreIns.getComList(getComListCbk);
            });
			
			 $("#mac_connect").click(function () {
				macIp(); 
			 });
				

            $("#restorePassword").click(function () {

                statRecordEle("softCenter#restorePassword#restore");
                var params = {};
                params.restoreWay = null;
                params.password = {};

                //选择恢复方式
                isFactoryReset = $("#factoryReset").is(':checked');
                isKeyChange = $("#keyChange").is(':checked');

                if (!isFactoryReset && !isKeyChange) {
                    alert(undefined, "请至少选择一种恢复方式！");
                    return;
                }
                if (isFactoryReset) {
                    params.restoreWay = "factoryReset";
                    params.baudrate = $('#factoryResetBand option:selected').text();
                    params.comNum = $('#factoryResetCom option:selected').text();
                }
                if (isKeyChange) {
                    params.restoreWay = "keyChange";
                    params.baudrate = $('#keyChangeBand option:selected').text();
                    params.comNum = $('#keyChangeCom option:selected').text();

                    var isCheckEnable = $("#checkEnable").is(':checked');
                    var isCheckTelnet = $("#checkTelnet").is(':checked');
                    var isCheckConsole = $("#checkConsole").is(':checked');

                    if (!isCheckEnable && !isCheckTelnet && !isCheckConsole) {
                        alert(undefined, "请至少选择恢复一种密码！");
                        return;
                    }

                    if (isCheckEnable) {
                        var key_enable = $("#inputEnable").val();
                        if (key_enable != "") {
                            params.password.enable = key_enable;
                        } else {
                            alert(undefined, "请输入enable密码！");
                            return;
                        }
                    }
                    if (isCheckTelnet) {
                        var key_telnet = $("#inputTelnet").val();
                        if (key_telnet != "") {
                            params.password.Telnet = key_telnet;
                        } else {
                            alert(undefined, "请输入telnet/ssh密码！");
                            return;
                        }
                    }
                    if (isCheckConsole) {
                        var key_console = $("#inputConsole").val();
                        if (key_console != "") {
                            params.password.console = key_console;
                        } else {
                            alert(undefined, "请输入console密码！");
                            return;
                        }
                    }
                }

                alert(undefined, "请连接好串口线，关闭其他会占用串口的软件如超级终端等，先点击确定后，再进行手动下电重启设备", function () {
                    setTimeout(function () {
                        global.restoreIns.restorePassword(params);
                    }, 1000);

                    // 界面显示
                    $("#closeRestore").hide();
                    $("#restorePassword").hide();
                    $("#restoringPassword").show();
                });
//				}
//				global.restoreIns.getComList(getComListCbk);
            });
            var softCenter_IsPingResultEnd = 0;
            var softCenter_HostsTotalCount = 0;
            $("#softCenter_PingModalClear").click(function () {
                if ($("#softCenter_PingModalStart").html() == "正在Ping...")
                    return;
                InitSoftCenterPingResultTableBody();
            });
            function InitSoftCenterPingResultTableBody() {
                $("#softCenter_PingResultTable tbody").html("<tr style=\"display:none\"><td> </td><td> </td></tr>");
            }

            function AddSoftCenterPingResultTableBody(ip, rate) {
                var m_alertColor = "";
                if (rate == "100")
                    m_alertColor = " style='color: red;'";
                $("<tr><td " + m_alertColor + ">" + ip + "</td><td " + m_alertColor + ">" + rate + "</td></tr>").insertAfter($("#softCenter_PingResultTable tr:eq(1)"));
            }

            function getipvalue(obj1, obj2, obj3, obj4) {
                return obj1.val() + "." + obj2.val() + "." + obj3.val() + "." + obj4.val();
            }

            $("#softCenter_PingModalStart").click(function () {
                if ($("#softCenter_PingModalStart").html() == "正在Ping...")
                    return;
                statRecordEle("softCenter#Ping#ButtonStart");
                var m_startIp = getipvalue($("#softCenter_inputIP1"), $("#softCenter_inputIP2"), $("#softCenter_inputIP3"), $("#softCenter_inputIP4"));
                var m_endIp = getipvalue($("#softCenter_inputIP1"), $("#softCenter_inputIP2"), $("#softCenter_inputIP3"), $("#softCenter_inputEndIP4"));
                if (global.pingToolIns.IsPingIPv4(m_startIp) == false) {
                    alert(undefined, '起始IP不是有效的IP格式！' + m_startIp);
                    return;
                }
                if (global.pingToolIns.IsPingIPv4(m_endIp) == false) {
                    alert(undefined, '结束IP不是有效的IP格式！' + m_endIp);
                    return;
                }
                if (Number($("#softCenter_inputIP4").val()) > Number($("#softCenter_inputEndIP4").val())) {
                    alert(undefined, '开始IP应小于结束IP！' + m_startIp + " < " + m_endIp);
                    return;
                }
                var m_startIpAray = global.pingToolIns.GetPingArray(m_startIp, m_endIp);
                softCenter_IsPingResultEnd = 0;
                $("#softCenter_PingModalStart").html("正在Ping...");
                InitSoftCenterPingResultTableBody();
                var softCenter_Hosts = m_startIpAray;
                softCenter_HostsTotalCount = softCenter_Hosts.length;
                global.pingToolIns.PingOperation(softCenter_Hosts, PingToolResultShow);
            });
            function PingToolResultShow(res) {
                console.log("PingToolResultShow-->"+res);
                softCenter_IsPingResultEnd += 1;
                var ping_result = res.output.split('\n');
                var ttl_count = 0;
                for (var ps in ping_result) {
                    if (ping_result[ps].indexOf("TTL") > 0)
                        ttl_count++;
                }
                var ping_lost_rate = ttl_count > 0 ? 0 : 100;

                 var ping_show_rate= res.output.split('%');
                 var ping_show_rate_result= ping_show_rate[0].split('(');
                 if(ttl_count!=0) {
                 ping_lost_rate = ping_show_rate_result[1];
                 }
                AddSoftCenterPingResultTableBody(res.host, ping_lost_rate);
                if (softCenter_IsPingResultEnd == softCenter_HostsTotalCount) {
                    softCenter_PingResultTableSort();
                    $("#softCenter_PingModalStart").html("开始检测");
                }
            }
            //重新对于Ping的结果排序
            //按照有问题的排在最前面，IP按照由小到大排序
            function softCenter_PingResultTableSort()
            {
                var m_ipArray=new Array();
                var m_objData=new Object();
                $("#softCenter_PingResultTable tr").each(function() {
                    var ipData_ip=$(this).children().eq(0).text();
                    var ipData_rate=$(this).children().eq(1).text();
                    if(ipData_ip.indexOf('.')>0) {
                        m_objData=new Object();
                        m_objData.ip = ipData_ip;
                        m_objData.endip=ipData_ip.split('.')[3];
                        m_objData.rate = ipData_rate;
                        m_ipArray.push(m_objData);
                    }
                });
                m_ipArray.sort(function(a,b){
                    var m_rateResult=Number(a.rate)-Number(b.rate);
                    var m_ipResult=Number(b.endip)-Number(a.endip);
                    if(m_rateResult!=0)
                        return m_rateResult;
                    return m_ipResult;
                });
                InitSoftCenterPingResultTableBody();
                $.each( m_ipArray, function(index, content) {
                    AddSoftCenterPingResultTableBody(content.ip,content.rate);
                });
            }
        }
        function initDom() {
            //第三方工具
            appendBodyLayout();
            
            //常用链接
            $(".link_menu").hover(function () {
                $(this).css("background-color", "#e8eefc");
            }, function () {
                $(this).css("background-color", "#fff");
            });
            
            $('#restoreModal').modal({
                backdrop: 'static',
                show: false
            });
        }
        function resize() {

        }
        function initGlobalEvent() {
            global.exitPageCallback.exitFun = function () {
                return true;
            }
        }
    }
    exports.init = init;
});