/**
 * 树型菜单 依赖ztree jquery插件,做了下封装,方便使用
 * 框架提供的api不好使用,,,加止树形菜单业务复杂,
 	封装的代码会很复杂,不过外面使用很简单:

 	var Tree = require("lib/util/tree");
 	var tree = new Tree({
		id: "tree",
		url:  File.getUrlDir()+"?"+$.param(param)
	});
 * @author kenny
 */
(function() {
	/** 取目录的分隔符,根据操作系统自动区别 */
	function getSeparate() {
		var ua = navigator.appVersion || navigator.userAgent;
		if (/Windows/.test(ua)) {
			return "\\";
		}
		return "/";
	}

	function getDir(node) {
		if (!node) return;
		var dir = "";
		var deal = function(dir, node) {
			if (!node) return dir;
			dir = (node.name || "") + getSeparate() + dir;
			return deal(dir, node.getParentNode());
		}
		return deal(dir, node).replace(/\\+/g, "/");
	}
	function treeChangeData(list, conf){
		if(!list || list.length < 1){
			return list;
		}
		conf = conf || {};
		var newList = [];
		for(var i in list){
			var item = list[i];
			item.isParent = item.isfile ? false : true;
			item.id=item.name;
			if(conf.showType == "dir" && item.isfile){
				continue;
			}
			if(item.children){
				treeChangeData(item.children, conf);
			}
			newList.push(item);
		}
		return newList;
	}
	window.treeChangeData = treeChangeData;
	define("lib/util/tree", function(require, exports, module) {
		require("lib/jquery/ztree");
		var dbfen = require("dbfen/client/com/dbfen");

		var g_dom_id ;
		function Module(conf){
			this.config = conf;
			this.init(conf);
		}
		$.extend(Module.prototype, {
			init: function(conf) {
				var me = this;
				conf = conf || {};
				g_dom_id = conf.id;
				if(conf.data){//如果有数据传送进来
					var list = (conf.data || {}).list || [];
					list = treeChangeData(list, conf);
					me.tree = initTree(conf, list);
				}else{
					/*$.ajax({
						url: conf.url,
						data:{
							ttl: new Date().getTime()
						},
						type: conf.type || "get",
						dataType: conf.dataType||"json",
						success: function(result) {
							var list = (result.data || {}).list || [];
							treeChangeData(list, conf);
							switch (result.code) {
								case 0:
									me.tree = initTree(conf, list);
									break;
								default:
							}

						}
					});*/
					me.tree = initTree(conf, []);
				}		
			},
			/**
				取用户选择的文件夹
				如果子文件全选,会取父目录地址,不会再包含子文件
			*/
			getSelectDir: function() { 
				var me = this;
				//下面有逻辑处理,比较复杂
				var list = me.tree.getNodesByFilter(function(node) {
					//me.checked = Q.isNull(me.checked) ? me.checked : true;
					var isRadio = me.config.checked ? true : false;
					if(!isRadio){
						if(node.checked){
							var l1 = $("#" + node.tId + " >ul>li>.checkbox_true_full").length;
							var l2 = $("#" + node.tId + " >ul>li").length;
							if (l1 == l2) {
								return true;
							}
							return false;
						}
					}else if(node.isHover){
						return true;
					}
					return false;
				}) || [];
				var result = [],
					tmpArray = [];
				for (var i = 0; i < list.length; i++) {
					var node = list[i];
					var dir = getDir(node);
					
					var test = true;
					for (var j in tmpArray) {
						//var v1 = (tmpArray[j]||"").replace(/\\/g,"\\\\").replace(/\//g, "\/");
						/*if (new RegExp("^\s*" + v1).test(dir)) {
							test = false;
							break;
						}*/
						if (dir.indexOf(tmpArray[j]) == 0) {
							test = false;
							break;
						}
					}
					if (test) {
						dir = dir.replace(/\\/g, "/").replace(/[\/\\]$/, "");
						dir = dir.replace(/^\s*(\/){2,}/, "/");
						result.push(dir);
						tmpArray.push(dir);
					}
				}
				return result || [];
			}
		});

		function initTree(param, dataList) {
			param = param || {};
			var log, className = "dark",
				startTime = 0,
				endTime = 0,
				perCount = 100,
				perTime = 100,
				url = param.url,
				searchId = param.id,
				checked = param.checked==null ? true: param.checked==true,
				autoRequestCount = 0,
				isFirstLoad = false;

			function getAbsPath(node, path){			
				if(!node) return ;
				path = path || node.name+getSeparate();
				var parentNode = node.getParentNode();
				if(!parentNode) return path;
				path = parentNode.name +getSeparate()+ path;
				return getAbsPath(parentNode, path);
			}	

			//树型菜单配置
			var setting = {
				async: {
					enable: true,
					type: 'get',
					dataType: "json",
					url: function(treeId, treeNode) {
						var abspath = getAbsPath(treeNode)||"";
						var prefixUrl = url.replace(/\?.*/, "");
						//var curCount = (treeNode.children) ? treeNode.children.length : 0;
						//var getCount = (curCount + perCount) > treeNode.count ? (treeNode.count - curCount) : perCount;
						//var param = "path=" + abspath + "_" + (treeNode.times++) + "&count=" + getCount;
						var param = dbfen.serialize(url.replace(/^[^\?]*/g,""));
						param.path = abspath.replace(/\\/g,"/").replace(/(\/|\\)\s*$/,"");
						return prefixUrl + "?" + $.param(param);
					}
				},
				check: {
					enable: checked,
					autoCheckTrigger: true
				},
				data: {
					simpleData: {
						enable: true
					}
				},
				view: {
					showType: param.showType,
					expandSpeed: ""
				},
				callback: {
					beforeExpand: function(treeId, treeNode) {
						if (!treeNode.isAjaxing) {
							startTime = new Date();
							treeNode.times = 1;
							ajaxGetNodes(treeNode, "refresh");
							return true;
						} else {
							//alert("zTree 正在下载数据中，请稍后展开节点。。。");
							return false;
						}
					},
					//取得数据后回调方法
					onAsyncSuccess: function(event, treeId, treeNode, list) {
						param.onClick && param.onClick();
						if( param.autoload != false ){ //自动请求下级节点
							/** 如果给出的节点是打上勾的,就主动请求对应的子节点	start	 */			
							$.each(list||[], function(i, item){
								//如果不是选择状态,文件,子文件全选,返回
								if(item.checked!=true || item.isfile || item.fselect){
									return;
								}
								if(treeNode && autoRequestCount < 100){//最多自动请求100次
									setTimeout(function(){
										autoRequestCount++;
										$.each(treeNode.children, function(i, node){
											if(node.checked){
												var $nodes = $("#" + node.tId + " > span.switch");
												$nodes.trigger("click");
											}
										});
									}, 100);								
								}else{
									var $nodes = $("#"+treeId+" > li.level0 > span.checkbox_true_full").prev("span.switch");
									$nodes.trigger("click");
								}								
							});
						}	
						if(isFirstLoad != true){
							setTimeout(function(){
								var $nodes = $("#"+treeId+"  li.level0  span.checkbox_true_full").first();
								$nodes[0] && $nodes[0].scrollIntoView(true);
							}, 300);	
							isFirstLoad = true;
						}
									
						/** 如果给出的节点是打上勾的,就主动请求对应的子节点	end	 */	
						if(treeNode==null)return;

						var zTree = $.fn.zTree.getZTreeObj(searchId),
							totalCount = treeNode.count;
						if (treeNode.children.length < totalCount) {
							setTimeout(function() {
								ajaxGetNodes(treeNode);
							}, perTime);
						} else {
							treeNode.icon = "";
							zTree.updateNode(treeNode);
							zTree.selectNode(treeNode.children[0]);
							endTime = new Date();
							var usedTime = (endTime.getTime() - startTime.getTime()) / 1000;
							className = (className === "dark" ? "" : "dark");
							//showLog("[ "+getTime()+" ]&nbsp;&nbsp;treeNode:" + treeNode.name );
							//showLog("加载完毕，共进行 "+ (treeNode.times-1) +" 次异步加载, 耗时："+ usedTime + " 秒");
						}
					},
					onAsyncError: function(event, treeId, treeNode, XMLHttpRequest, textStatus, errorThrown) {
						var zTree = $.fn.zTree.getZTreeObj(searchId);
						//alert("异步获取数据出现异常。");
						treeNode.icon = "";
						zTree.updateNode(treeNode);
					}
				}
			};


			function ajaxGetNodes(treeNode, reloadType) {
				var zTree = $.fn.zTree.getZTreeObj(g_dom_id);
				if (reloadType == "refresh") {
					treeNode.icon = "/images/loading.gif";
					zTree.updateNode(treeNode);
				}
				zTree.reAsyncChildNodes(treeNode, reloadType, true);
			}
			return $.fn.zTree.init($("#" + searchId), setting, dataList);
		}
		module.exports = Module;
	});
})();