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

	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="table-btn connect" style="width: 50px;">连接</div>';
	}

	function collectClick(row, index) {
		if(jGlobal.faultDiag.curStatus == 'closing') {
			alert(undefined, '正在与设备(' + jGlobal.faultDiag.collectDevName[0] + ')断开连接，请稍等');
			return;
		}
		if(jGlobal.faultDiag.curStatus != 'init') {
			alert(undefined, '正在连接设备(' + jGlobal.faultDiag.collectDevName[0] + ')，请稍等');
			return;
		}
		jGlobal.faultDiag.curStatus = jGlobal.changeDevStatus(jGlobal.faultDiag.curStatus, 'connecting');

		$('#connectDevModal').modal('show');
		jGlobal.faultDiag.collectDevName = [];
		jGlobal.faultDiag.collectDevName.push(row.deviceName);
		global.devicesIns.connectDeviceByDeviceName(jGlobal.faultDiag.collectDevName[0]);
	}
	exports.collectClick = collectClick;

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

		function initGuide() {
			if(global.guide) {
				$('#red-point').css({
					display: 'block',
					top: '160px',
					left: '680px'
				});
			}
		}       

		function initWindowEvent() {
			window.operateStyle = operateStyle;
			window.operateEvents = {
				'click .connect': function(e, value, row, index) {
					collectClick(row, index);
				}
			};
		}

		function initPageStatistic() {
			statRecordEle("faultDiag#selectDevice");
		}

		function removeGlobalEvent() {
			global.devicesIns.removeAllListeners("deviceConnected");
			global.devicesIns.removeAllListeners("deviceError");
			global.devicesIns.removeAllListeners("deviceDisconnected");
		}

		function initVariable() {
			//全局变量初始化
			jGlobal.faultDiag.isLoadFromDiag = false;
			jGlobal.faultDiag.cycleNum = 0;
		}

		function initTable() {
			$('#selectDeviceTable').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));
			});

			$('#consoleAccessBtn').click(function() {
				$("#consoleModal").modal('show');
				//				console.error(global.devicesIns.getSerialDeviceName());
				$("#loca_dev_name").val(global.devicesIns.getSerialDeviceName());
				$("#loca_ip_addr").val("");
				$("#loca_username").val("");
				$("#loca_pwd").val("");
				$("#loca_enable_pwd").val("");
				$("#code_option").val("UTF8,通用编码");
				$("#group_name").hide();

				//添加串口
				var select_id = "port";
				$("#" + select_id).children().remove();

				function getComListCallback(data) {
					if(data.length === 0) {
						global.addOption("无", "无", select_id);
					} else {
						data = data.sort();
						for(var i = 0; i < data.length; ++i) {
							global.addOption(data[i], data[i], select_id);
						}
					}
				}
				global.deviceConfIns.getComList(getComListCallback);
			});

			$("#consoleModal .btn-confirm").click(function() {
				var parameter = deviceManage.get_connect_param(null);
				if(parameter === false) {
					return;
				}

				var dataToModify = {};
				dataToModify.deviceName = parameter.deviceName;
				//		        dataToModify.groupId = 10086;
				dataToModify.protocal = parameter.protocal;
				dataToModify.username = parameter.username;
				dataToModify.password = parameter.password;
				dataToModify.encoding = parameter.encoding;
				dataToModify.comNum = parameter.comNum;
				dataToModify.baudrate = parameter.baudrate;
				dataToModify.enablePassword = parameter.enablePassword;
				//		        console.log(parameter);
				//		        console.log(dataToModify);

				function updateDevinfoCallback(error, result) {
					if(error === null) { //保存console接入到数据后，连接设备
						//	                	console.log("222222222222222222222222222");
						var row = {};
						row.deviceName = dataToModify.deviceName;
						collectClick(row);
					} else {
						alert(undefined, "添加console接入信息失败!");
					}
				}
				//	            console.log("111111111111111111");
				global.devicesIns.updateDeviceLink(dataToModify, updateDevinfoCallback);
			});

			global.devicesIns.on("deviceConnected", function(devName) {
				if(jGlobal.faultDiag.curStatus != 'connecting') {
					return;
				}
				jGlobal.faultDiag.curStatus = jGlobal.changeDevStatus(jGlobal.faultDiag.curStatus, 'connected');

				jGlobal.faultDiag.productType = undefined;
				jGlobal.faultDiag.collectType = undefined;
				jGlobal.faultDiag.typeName = undefined;
				var groupId = $('#selectGroup').val();
				groupId = groupId.split(':')[0];
				if(groupId == "null") {
					groupId = null;
				}
				addDevInfoToTable(deviceManage.searchDeviceByGroupId(groupId));

				//* 判断规则文件是否存在
				jGlobal.faultDiag.rulePath = global.tftpOperateInstance.queryRulePathByDeviceName(jGlobal.faultDiag.collectDevName[0]);
				if(jGlobal.faultDiag.rulePath === null) {
					if(jGlobal.faultDiag.curStatus == "connected") {
						jGlobal.faultDiag.curStatus = jGlobal.changeDevStatus(jGlobal.faultDiag.curStatus, 'closing');
						global.devicesIns.closeDeviceLink(jGlobal.faultDiag.collectDevName[0]);
						alert(undefined, "当前设备不支持收集诊断！");
						return false;
					} else {
						alert(undefined, "程序内部运行出错！请关闭程序后重试！");
						return false;
					}
				}
				$('#connectDevModal').modal('hide');

				if($("#definedCollect").hasClass("curSelectItem")) {

					setTimeout(function() {

						$(".selectDeviceContent").load("./faultDiagMenu/html/selectDiagContent.html", function() {
							$(".curStep .curStepText .curStepDiv").eq(1).text("配置收集参数");
							$(".curStep .curStepText .curStepDiv").eq(2).text("收集中");
							$(".curStep .curStepText .curStepDiv").eq(3).text("收集完成");
							$(".diagContent .diagItem").hide();
							$("#startDiag").hide();
							$("#startCollect").show();
							$(".diagCondition").css("width", "100%");
							$(".diagCondition .diagConditionText").hide();
							$("#detailFault").css("height", "447px");
							$("#detailFault").empty();
							$("#detailFault").load("../../db/html/common/defineCollect.html");
						});

					}, 300)
				} else {
					setTimeout(function() {
						$(".selectDeviceContent").load("./faultDiagMenu/html/selectDiagContent.html");
					}, 300);
				}
			});

			global.devicesIns.on("deviceError", function(res) {
				$('#connectDevModal').modal('hide');

				if(jGlobal.faultDiag.curStatus == 'closing' || jGlobal.faultDiag.curStatus == 'init') {
					return;
				}

				jGlobal.faultDiag.curStatus = jGlobal.changeDevStatus(jGlobal.faultDiag.curStatus, 'closing');
				global.tftpOperateInstance.changeDirName(jGlobal.faultDiag.collectDevName[0]);

				alert(undefined, '连接设备(' + res.deviceName + ')失败！错误信息: ' + res.errInfo);
				return;
			});

			global.devicesIns.on("deviceDisconnected", function(devName) {
				$('#connectDevModal').modal('hide');

				if(jGlobal.faultDiag.curStatus == 'closing' || jGlobal.faultDiag.curStatus == 'init') {
					jGlobal.faultDiag.curStatus = jGlobal.changeDevStatus(jGlobal.faultDiag.curStatus, 'init');
					return;
				}

				var msg = '';
				if(jGlobal.faultDiag.curStatus == 'connecting') {
					msg = '无法与设备(' + devName + ')建立连接！';
				} else if(jGlobal.faultDiag.curStatus == 'collect') { //* 原则上不会跑到
					msg = '收集失败，与设备(' + devName + ')断开连接';
				} else if(jGlobal.faultDiag.curStatus == 'diagnosis') { //* 原则上不会跑到
					msg = '诊断失败，与设备(' + devName + ')断开连接';
				} else if(jGlobal.faultDiag.curStatus == 'repair') { //* 原则上不会跑到
					msg = '修复失败，与设备(' + devName + ')断开连接';
				} else if(jGlobal.faultDiag.curStatus == 'backRepair') { //* 原则上不会跑到
					msg = '回退失败，与设备(' + devName + ')断开连接';
				} else {
					msg = '与设备(' + devName + ')连接断开！';
				}

				jGlobal.faultDiag.curStatus = jGlobal.changeDevStatus(jGlobal.faultDiag.curStatus, 'init');
				alert(undefined, msg);
			});
		}

		function initDom() {
			$('#connectDevModal').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
			});
		}

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