define(function(require, exports, module) {
    var global = require("../../js/global");
	
	//日志诊断页面需用到的变量
	var DIAG_CONF_PATH = 'db/diagConf';
	var DIAG_RULE_CONF = 'offlineDiagrules.json';
	var warnCount = 0;
	var logDiagResult = "";
	var startTime_logDiag = 0;
	var endTime_logDiag = 0;
	var db;
	var ids = new Array();
	var productTypes = new Array();
	var keywords = new Array();
	var problems = new Array();
	var solutions = new Array();
	var minVersions = new Array();
	var maxVersions = new Array();
	var results = new Array();
	
	function importFile(name) {
		var text_srcVendorConf = "";
	    var import_file = $(name);	    
	    import_file.unbind('change');
	    import_file.change(function(evt) {
	    	var file_path = $(this).val();    	
	    	var array_file_path = file_path.split(';');
	    	
	    	global.configMgrIns.writeConfig('srcPath', array_file_path[0].substring(0, array_file_path[0].lastIndexOf('\\')));
	    	$("#importConfFileDialog")[0].nwworkingdir = global.configMgrIns.readConfig('srcPath');

    		text_srcVendorConf = global.cmdMigrationIns.readFile(file_path);
    		if (text_srcVendorConf == null) {
    			alert(undefined, '读取文件出错');
    			text_srcVendorConf = '';
    		}
    		$("#srcVendorConf").val(text_srcVendorConf);
	    	
	    	$(this).val("");
	    });
	    import_file.trigger('click');
	}
	
	/*创建数据库以及表 测试使用*/

	/*执行诊断*/
	function doDiag() {
	    results.splice(0,results.length);
	    $("#div_dstVendorConf").empty();
	    var text_srcVendorConf = $("#srcVendorConf").val();
	    for (var i = 0; i < keywords.length; i++) {
	        var keywordTmpArr = keywords[i].trim().split(/\\n/);
	        var j = 0;   
	        var isWarn = true;         
	        while (j < keywordTmpArr.length) {
	            if (text_srcVendorConf.indexOf(keywordTmpArr[j]) == -1) {
	                isWarn = false;
	                break;
	            } else {
	                //去除已经匹配过得文本，防止key中含有相同的重复的文本
	                text_srcVendorConf = text_srcVendorConf.replace(keywordTmpArr[j],"");
	                console.log("每次匹配后的字符" + text_srcVendorConf);
	            }
	            j++;
	        }
	        if (isWarn) {
	            var result = {};
	            result.level = "warn";
	            result.subTitle = keywords[i];
	            result.problems = [{"desc"   : problems[i],
	                                "advice" : solutions[i] }];
	            results.push(result);
	        }
	    }
	    if (results.length == 0) {
	        var result = {};
	        result.level = "success";
	        result.subTitle = "诊断完成：当前日志未诊断出异常，若设备仍有异常，建议提供更详细故障日志进行诊断或者联系400工程师处理";
	        checkResult(result);
	    }
	    for (var i = 0; i < results.length; i++) {
	        checkResult(results[i]);
	    }
	    
	    var uploadParam = {};
	    endTime_logDiag = global.moment();
        uploadParam.dataType = "faultDiagnose";
        uploadParam.curAction = "offline";
        uploadParam.actionResult = logDiagResult;
        uploadParam.duration = parseInt((endTime_logDiag - startTime_logDiag) / 1000);
	    if (warnCount == 0) {
	        uploadParam.hasProblem = false;
	    } else {
	    	uploadParam.hasProblem = true;
	    }
	    uploadParam.isResolved = "F";			//与故障诊断一致，上传F表示完整的走完一次诊断
	    uploadLogDiagInfoToCloud(uploadParam);
	    
	    if (warnCount == 0) {
	        uploadParam.isResolved = "N";
	    } else {
	    	uploadParam.isResolved = "Y";
	    }
	    uploadLogDiagInfoToCloud(uploadParam);
	}

	function clearLog() {
	    $("#srcVendorConf").val('');
	    $("#div_dstVendorConf").empty();
	}


	function checkResult(result) {
		if(!$("#offlineDiag_warn").length > 0) {
			var $div_warn = "";
		    $div_warn += '<div id="offlineDiag_warn" class="panel-group" style="margin-bottom: 10px;">';
		    $div_warn += '</div>';
		    $("#div_dstVendorConf").append($div_warn);
		    
		    var $div_success = "";
		    $div_success += '<div id="offlineDiag_success" class="panel-group">';
		    $div_success += '</div>';
		    $("#div_dstVendorConf").append($div_success);
		}

//	    console.log(result);
	    //添加当前端口的warn和success结果至指定区域
	    if (result.level === "warn") {	        
	        warnCount++;
	        logDiagResult += result.subTitle + ';';
	        
	        var $offline_div_warn_result = "";
	        $offline_div_warn_result += '<div class="panel panel-info">' +
			                                '<div class="panel-heading">' +
			                                    '<div class="panel-title">' +
			                                        '<img src="../../common/image/warn.png" style="margin-right:5px; width:14px; height:14px;"></img>' +
			                                        '<a data-toggle="collapse" data-parent=""' + 
			                                            'href="#collapse_' + warnCount + '"' + 'style="font-size:12px;">' +
			                                            result.subTitle.replace(/\\n/g, '<br />') +
			                                        '</a>' +
			                                    '</div>' +
			                                '</div>' +
			                                '<div id="collapse_' + warnCount + '"' + 'class="panel-collapse collapse">' +
			                                    '<div class="panel-body" style="font-size:12px;">';

	        for (var i = 0; i < result.problems.length; i++) {
	            $offline_div_warn_result += '<div>' +
			                                    '<img src="../../common/image/red_circle.png" style="margin-left:3px; margin-right:5px;"></img>' +
			                                    '<span style="line-height: 20px;">' +
			                                        result.problems[i].desc.replace(/\r?\n/g, '<br />').replace(/\t/g, '&nbsp;&nbsp;&nbsp;&nbsp;') 
                                                    .replace(/\\n/g, '<br />') +
			                                    '</span>';
                console.log('kkkkk:', result.problems[i].desc);
	            
	            $offline_div_warn_result += '</div>' +
			                                '<div style="margin-top:5px;">' +
			                                    '<img src="../../common/image/blue_circle.png" style="margin-left:3px; margin-right:5px;"></img>' +
			                                    '<span style="line-height: 20px;">' +
			                                        result.problems[i].advice.replace(/\r?\n/g, '<br />').replace(/\t/g, '&nbsp;&nbsp;&nbsp;&nbsp;') 
                                                    .replace(/\\n/g, '<br />') +
			                                    '</span>' +
			                                '</div>';
	            
	            $offline_div_warn_result += '<img src="./image/ruijieQrCode.png" style="width: 150px;"></img>';
	        }
	        $offline_div_warn_result += '</div></div></div>';
	        
	        $('#offlineDiag_warn').append($offline_div_warn_result);     
	        
	    } else if (result.level === "success") {
	        logDiagResult += result.subTitle + ';';
	        
	        var $offline_div_success_result = "";
	        $offline_div_success_result += '<div class="panel panel-info">' +
			                                    '<div class="panel-heading">' +
			                                        '<div class="panel-title">' +
			                                            '<img src="../../common/image/success.png" style="margin-right:5px; width:14px; height:14px;"></img>' +
			                                            '<a data-toggle="collapse" data-parent=""' + 
			                                                'href="#collapse_' + warnCount + '"' + 'style="font-size:12px;">' +
			                                                result.subTitle +
			                                            '</a>' +
			                                        '</div>' +
			                                    '</div>' +
			                                '</div>';
	        
	        $('#offlineDiag_success').append($offline_div_success_result);
	    }
	    
	    console.log("warnCount", warnCount);
	    for (var i = 1; i <= warnCount; i++) {
            var collapseId = "#collapse_" + i;
            $(collapseId).collapse('hide');
        }
	}
	
	function uploadLogDiagInfoToCloud(param) {
	    var uploadDiagDataAray = [];
	    var uploadDiagData = {};
	     
	    uploadDiagData.deviceSn = global.jsUtil.uuidByMac() + "_offline";
	    uploadDiagData.deviceIp = "0.0.0.0";
	    uploadDiagData.deviceVersion = '0';
	    uploadDiagData.deviceType = "offline";
	    uploadDiagData.ruleCode = null;
	    uploadDiagData.ruleName = "offline";
	    uploadDiagData.subRuleCode = null;
	    uploadDiagData.subRuleName = "offline";
	    uploadDiagData.diagnoseTime = global.moment().format('YYYY-MM-DD HH:mm:ss');
	    uploadDiagData.duration = param.duration;
	    uploadDiagData.logDiagResult = param.actionResult;
	    uploadDiagData.productLine = "offline";
	    uploadDiagData.argument = null;
	    uploadDiagData.manualDiagnose = false;
	    uploadDiagData.hasProblem = param.hasProblem;
	    uploadDiagData.isResolved = param.isResolved;
	     
	    uploadDiagDataAray.push(uploadDiagData);
	    console.log(uploadDiagDataAray);
	    statInfoIns.sendFaultDiagnose(uploadDiagDataAray, param.dataType);
	}
	
	function init() {
		initPageStatistic();
		initVariable();
		initEvent();
		initDom();
		resize();
		initGlobalEvent();
		
		function initPageStatistic() {
			statRecordEle("logDiag#logDiag");
		}
		function initVariable() {
			DIAG_CONF_PATH = 'db/diagConf';
			DIAG_RULE_CONF = 'offlineDiagrules.json';
			warnCount = 0;
			logDiagResult = "";
			startTime_logDiag = 0;
			endTime_logDiag = 0;
			db = null;
			ids = new Array();
			productTypes = new Array();
			keywords = new Array();
			problems = new Array();
			solutions = new Array();
			minVersions = new Array();
			maxVersions = new Array();
			results = new Array();
		}
		function initEvent() {
			$("#importConfFile").click(function() {
				importFile('#importConfFileDialog');
			});

		    $("#offlineDiagRule_select").change(function() {
	            ids.splice(0, ids.length);
	            keywords.splice(0, keywords.length);
	            problems.splice(0, problems.length);
	            solutions.splice(0, solutions.length);
	            minVersions.splice(0, minVersions.length);
	            maxVersions.splice(0, maxVersions.length);

                global.offlineDbMgr.readAllRows($("#offlineDiagRule_select").val(), ids, keywords, problems, solutions, minVersions, maxVersions);
		    });
		    
		    $("#doLogDiag").click(function() { 
		        var srcConf = $("#srcVendorConf").val();
		        if (srcConf == "") {
		            alert(undefined, "诊断数据不能为空！");
		            return false;
		        }
		        
		        //初始化诊断结果保存的一些变量
				warnCount = 0;
				logDiagResult = "";
				startTime_logDiag = global.moment();
				
		        doDiag();
		    });

		    $("#clearText").click(function () { 
		        clearLog();
		    });
            global.offlineDbMgr.readAllRows($("#offlineDiagRule_select").val(), ids, keywords, problems, solutions, minVersions, maxVersions);
		}
		function initDom() {

		}
		function resize() {

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