//------------------------------ Global Variable -------------------------------

var pageIndex = 0;
var curPageId = -1;
var pageDic = {};
var pageIdList = [];
var pageUrlDic = {};
var nodeDic = {};
var curSysResNodeId = "";

var projList;
var dbList;
var config;
var curServer;

//------------------------------ Common Function -------------------------------

//替换默认的提示框
alert = function(str){
  $("#divAlert").text(str);
  var left = (document.documentElement.clientWidth-$("#divAlert").width())/2;
  $("#divAlert").css("left", parseInt(left)+"px");
  if($("#divAlert").is(":visible")) return;
  $("#divAlert").show();
  setTimeout(function() {
    $("#divAlert").fadeOut("slow");
  }, 3000);
};

var cbConfirm;
var frameConfirmOpener;

function closeConfirm(ret) {
  $("#divConfirm").hide();
  $("#divMask").hide();
  if(cbConfirm) cbConfirm(ret); 
}

confirm = function(msg, cb) {
  cbConfirm = cb;
  var top = (document.documentElement.clientHeight-100)/2;
  if(top>0) $("#divConfirm").css("top", parseInt(top)+"px");
  var left = (document.documentElement.clientWidth-200)/2;
  if(left>0) $("#divConfirm").css("left", parseInt(left)+"px");
  $("#divConfirmMsg").html(msg);
  $("#divMask").css("z-index", curZIndex);
  curZIndex++;
  $("#divMask").show();
  $("#divConfirm").css("z-index", curZIndex);
  curZIndex++;
  $("#divConfirm").show();
  $("#divConfirm").find("input").get(0).focus();
};

//显示提示消息
function showMsg(msg) {
  alert(msg);
}

/**
 * 设置状态栏
 * @param {[type]} content [description]
 */
function setStatusBar(content) {
  $("#divBottomLeft").html(content);
}

/**
 * 显示错误信息
 * @param  {[type]} err [description]
 */
function showErr(err) {
  if(typeof(err)=="string") setStatusBar(err)
  else setStatusBar(err.message);
}

/**
 * 打开文件
 */
function openFile() {
	var args = {
		filters: [
	    { name: '所有文件', extensions: ['*'] },
	    { name: 'tfp', extensions: ['tfp'] },
	    { name: 'tbs', extensions: ['tbs'] },
	    { name: 'tdm', extensions: ['tdm'] },
	    { name: 'html', extensions: ['html'] },
	    { name: 'css', extensions: ['css'] },
	    { name: 'js', extensions: ['js'] },
	    { name: 'json', extensions: ['json'] }
	  ]
	};
	taskBuilder.showFilePicker(args, function(files) {
		var fileInfo = files[0];
		var ext = taskBuilder.getFileExt(fileInfo.name).toLowerCase();
		if(ext==".tfp") {
			openPage(fileInfo.name, "taskbuilder-tfp-designer/index.html?path="+fileInfo.path);
			setCurFilePath(fileInfo.path);
		}
	});
}

//------------------------------ Page Management -------------------------------

/**
 * 打开页面
 * @param  {[type]} title            [description]
 * @param  {[type]} url              [description]
 * @param  {[type]} sysResTreeNodeId [description]
 */
function openPage(title, url, sysResTreeNodeId) {
  let urlPath = url;
  if(urlPath.indexOf("http")!=0) {
    if(urlPath.indexOf("/")!=0) {
      urlPath = "../"+urlPath;
    } else {
      urlPath = ".."+urlPath;
    }
  }
	if(urlPath in pageUrlDic) {
		var pageId = pageUrlDic[urlPath];
    if(pageId==curPageId) return;
		if(curPageId!=-1) hidePage(curPageId);
		showPage(pageId);
	} else {
		if(curPageId!=-1) hidePage(curPageId);
		pageIndex++;
		curPageId = pageIndex;
		var newPage = {};
		newPage.id = pageIndex;
		newPage.url = urlPath;
    newPage.sysResTreeNodeId = "";
    if(sysResTreeNodeId) newPage.sysResTreeNodeId = sysResTreeNodeId;
    pageDic[newPage.id] = newPage;
    pageIdList.push(newPage.id);
		pageUrlDic[urlPath] = newPage.id;
    $("#divSysTabBar").append("<div id=\"tabBar_"+curPageId+"\" class=\"tabBarSelected\">"
			+"<div id=\"tabBarTitle_"+curPageId+"\" class=\"tabBarTitleSelected\" title=\""+title
			+"\" onclick=\"tabBarTitleOnClick("+curPageId+")\">"+title+"</div>"
			+"<div id=\"tabBarCloseDiv_"+curPageId+"\" class=\"tabBarCloseDivSelected\" >"
			+"<img src=\"images/icon/close1.png\" style=\"cursor: pointer; margin-top:2px;\""
			+" title=\"关闭\" onclick=\"closePage("+curPageId+")\" /></div></div>");
    if(urlPath.indexOf("http")<0 && urlPath.indexOf("tfp-designer")<0 
      && urlPath.indexOf(".tfp")>0 && urlPath.indexOf(".tfp.html")<0) {
    	$("#divCenter").append("<iframe id=\"pageFrame_"+pageIndex+"\" class=\"pageFrame\" frameborder=\"0\" "
			  +"height=\"100%\" width=\"100%\" marginheight=\"0\" marginwidth=\"0\" src=\"\" "
			  +"scrolling=\"auto\" allowtransparency=\"false\"></iframe>");
    } else {
      $("#divCenter").append("<iframe id=\"pageFrame_"+pageIndex+"\" class=\"pageFrame\" frameborder=\"0\" "
			  +"height=\"100%\" width=\"100%\" marginheight=\"0\" marginwidth=\"0\" src=\""
				+urlPath+"\" scrolling=\"auto\" allowtransparency=\"false\"></iframe>");
		}
		setCurFilePath(urlPath);
	}
}

/**
 * 点击选项卡标题后执行的操作
 * @param  {[type]} pageId [description]
 */
function tabBarTitleOnClick(pageId) {
	if(pageId==curPageId) return;
	if($("#pageFrame_"+pageId).is(":hidden")) {
		hidePage(curPageId);
		showPage(pageId);
	}
}

/**
 * 隐藏页面
 * @param  {[type]} id [description]
 */
function hidePage(id) {
	$("#tabBar_"+id).removeClass("tabBarSelected");
	$("#tabBar_"+id).addClass("tabBar");
	$("#tabBarTitle_"+id).removeClass("tabBarTitleSelected");
	$("#tabBarTitle_"+id).addClass("tabBarTitle");
	$("#tabBarCloseDiv_"+id).removeClass("tabBarCloseDivSelected");
	$("#tabBarCloseDiv_"+id).addClass("tabBarCloseDiv");
	$("#pageFrame_"+id).hide();
  var page = pageDic[id];
  if(!page) return;
  if(page.sysResTreeNodeId == curSysResNodeId) {
    $("#"+curSysResNodeId).css("background-color", "");
    curSysResNodeId = "";
  }
}

function setCurFilePath(url) {
	let curPath = url;
  if(curPath.startsWith("taskbuilder-tfp-designer") 
    || curPath.startsWith("taskbuilder-code-editor")) {
  	curPath = curPath.substr(curPath.indexOf("path=")+5);
  }
  setStatusBar("当前文件路径："+curPath);
};

/**
 * 显示页面
 * @param  {[type]} id [description]
 */
function showPage(id) {
	$("#tabBar_"+id).removeClass("tabBar");
	$("#tabBar_"+id).addClass("tabBarSelected");
	$("#tabBarTitle_"+id).removeClass("tabBarTitle");
	$("#tabBarTitle_"+id).addClass("tabBarTitleSelected");
	$("#tabBarCloseDiv_"+id).removeClass("tabBarCloseDiv");
	$("#tabBarCloseDiv_"+id).addClass("tabBarCloseDivSelected");
	$("#pageFrame_"+id).show();
	curPageId = id;
  var page = pageDic[id];
  if(page.sysResTreeNodeId) {
    $("#"+page.sysResTreeNodeId).css("background-color", "#555");
    curSysResNodeId = page.sysResTreeNodeId;
  }
  setCurFilePath(page.url);
}

/**
 * 关闭页面
 * @param  {[type]} id [description]
 */
function closePage(id) {
	$("#tabBar_"+id).remove();
	$("#pageFrame_"+id).remove();
  var page = pageDic[id];
  if(page.sysResTreeNodeId == curSysResNodeId) {
    $("#"+curSysResNodeId).css("background-color", "");
    curSysResNodeId = "";
  }
  delete pageUrlDic[page.url];
  delete pageDic[page.id];
  pageIdList.remove(page.id);
	if(id==curPageId && pageIdList.length>0) { 
		setStatusBar("");
    if(pageIdList.length==1 || pageIdList[0]>id) {
      showPage(pageIdList[0]);
      return;
    }
		var lastId = -1;
    for(var i=pageIdList.length-1;i>=0;i--) {
      var pageId = pageIdList[i];
      if(pageId<curPageId) {
        lastId = pageId;
        break;
      }
    }
    if(lastId>=0) showPage(lastId);
	}
}

/**
 * 关闭当前页面
 * @return {[type]} [description]
 */
function closeCurPage() {
	closePage(curPageId);
}

/*
 以下代码是为了解决嵌入的框架页无法监听到窗口大小改变事件
 */

var pageFrameIds = [];

function onResize() {
  for(pageId in pageDic) {
    let page = pageDic[pageId];
    if($("#pageFrame_"+pageIndex).length>0) {
      let pageWin = $("#pageFrame_"+pageIndex).get(0).contentWindow.window;
      if(pageWin.onResize) pageWin.onResize();
    }
  }
}

//---------------------------------- Pop Dialog ---------------------------------

/*
 * 处理对话框拖拽
 */
(function($){
  //拖拽插件,参数:id或object
  $.Move = function(_this){
      if(typeof(_this)=='object'){
          _this=_this;
      }else{
          _this=$("#"+_this);
      }
      if(!_this){return false;}

      _this.css({'position':'absolute'}).hover(function(){
        $(this).css("cursor","move");
      },function(){
        $(this).css("cursor","default");
      })
      _this.mousedown(function(e){//e鼠标事件
          var offset = $(this).offset();
          var x = e.pageX - offset.left;
          var y = e.pageY - offset.top;
          _this.css({'opacity':'0.6'});
          $(document).bind("mousemove",function(ev){//绑定鼠标的移动事件，因为光标在DIV元素外面也要有效果，所以要用doucment的事件，而不用DIV元素的事件
              _this.bind('selectstart',function(){return false;});
              var _x = ev.pageX - x;//获得X轴方向移动的值
              var _y = ev.pageY - y;//获得Y轴方向移动的值
              _this.css({'left':_x+"px",'top':_y+"px"});
          });
      });

      $(document).mouseup(function(){
          $(this).unbind("mousemove");
          _this.css({'opacity':''});
      })
  };
})(jQuery);

var curZIndex = 10000;  //当前对话框Z坐标
var curDialogId = "";   //当前对话框id
var dialogList = [];    //打开的对话框列表
var dialogDic = {};

/**
 * 打开对话框
 * @param  {[type]} title      [description]
 * @param  {[type]} url        [description]
 * @param  {[type]} width      [description]
 * @param  {[type]} height     [description]
 * @param  {[type]} srcElement [description]
 * @param  {[type]} opener     [description]
 */
function openDialog(title, url, width, height, srcElement, opener, args, cb) {
	if(!title) {
	  alert("请设置窗口标题！");
	  return;
	}
	if(!url) {
	  alert("请设置窗口URL路径！");
	  return;
	}
  let urlPath = url;
  if(urlPath.indexOf("http")!=0) {
    if(urlPath.indexOf(".tfp")>0) {
      urlPath = "../taskbuilder-tfp-renderer/index.html?path="+urlPath;
    } else if(urlPath.indexOf("/")!=0) {
      urlPath = "../"+urlPath;
    } else {
      urlPath = ".."+urlPath;
    }
  }
	$("#divMask").css("z-index", curZIndex);
	curZIndex++;
  var dialog = $("#divDialogTemplate").clone();
  let dialogId = "dialog"+curZIndex;
	dialog.attr("id", "dialog"+curZIndex);
	curDialogId = "dialog"+curZIndex;
	dialog.css("zIndex", curZIndex);
	curZIndex++;
	dialog.css("width", width ? width : "320px");
	dialog.css("height", height ? height : "240px");
	var top = (document.documentElement.clientHeight-getPixel(dialog.css("height")))/2;
	if(top>0) dialog.css("top", parseInt(top)+"px");
	var left = (document.documentElement.clientWidth-getPixel(dialog.css("width")))/2;
	if(left>0) dialog.css("left", parseInt(left)+"px");
	dialog.find("div.divDialogTitle").text(title);
	$.Move(dialog);
	dialog.appendTo("body");
  if(srcElement) dialog.srcElement = $(srcElement);
  if(opener) dialog.opener = opener;
  if(args) {
  	sessionStorage.setItem("_OpenDialogArgs", args);
  } else {
  	sessionStorage.setItem("_OpenDialogArgs", "");
  }
  if(cb) dialog.cb = cb;
  dialogList.push(dialogId);
  dialogDic[dialogId] = dialog;
  //console.log(urlPath);
  dialog.find(".frameDialog").attr("src", urlPath);
	dialog.find(".imgDialogClose").click(function() {
    closeDialog(dialogId);
  });
  $("#divMask").show();
  dialog.show();
}

function setCurDialogSize(width, height) {
  let curDialog = dialogDic[curDialogId];
  curDialog.css("width", width);
  curDialog.css("height", height);
  var top = (document.documentElement.clientHeight-curDialog.height())/2;
  if(top>0) curDialog.css("top", parseInt(top)+"px");
  var left = (document.documentElement.clientWidth-curDialog.width())/2;
  if(left>0) curDialog.css("left", parseInt(left)+"px");
}

function onDialogOK(ret) {
  var curDialog = dialogDic[curDialogId];
  if(curDialog.cb) {
    curDialog.cb(ret);
  }
  /*curDialog.remove();
  curDialog = null;
  delete dialogDic[curDialogId];
  dialogList.remove(curDialogId);*/
}

/**
 * 关闭当前对话框
 */
function closeCurDialog() {
  closeDialog(curDialogId);
}

/**
 * 关闭指定的对话框
 * @param  {[type]} dialog [description]
 */
function closeDialog(dialogId) {
  var dialog = dialogDic[dialogId];
  delete dialogDic[dialogId];
  dialogList.remove(dialogId);
  dialog.remove();
  dialog = null;
  if(dialogId==curDialogId) {
    curDialogId = "";
  }
  if(dialogList.length>0) {
  	curDialogId = dialogList[dialogList.length - 1];
  	$("#divMask").css("z-index", parseInt(curDialogId.replace("dialog", ""))-1);
  } else {
    $("#divMask").hide();
  }
}

/**
 * 获得当前对话框
 * @return {[type]} [description]
 */
function getCurDialog() {
  return dialogDic[curDialogId];
}

function getCurDialogId() {
  return curDialogId;
}

//-------------------------------------- Sys ToolBar --------------------------------------

/**
 * 隐藏系统资源管理器
 * @return {[type]} [description]
 */
function hideSysRes() {
	$("#divLeft").hide();
	$("#divMain").css("left", "0");
	$("#divTopTool_sysres").removeClass("divTopToolSelected");
}

/**
 * 隐藏系统控制台
 * @return {[type]} [description]
 */
function hideConsole() {
	$("#divConsole").hide();
	$("#divCenter").css("bottom", "0");
	$(".pageFrame").css("height", getPixel($("#divCenter").css("height"))+"px");
	$("#divTopTool_console").removeClass("divTopToolSelected");
}

/**
 * 显示或隐藏系统资源管理器
 * @return {[type]} [description]
 */
function toggleSysRes() {
	if($("#divLeft").is(':visible')) {
		hideSysRes();
	} else {
		var width = getPixel($("#divLeft").css("width"));
		$("#divMain").css("left", (width+2)+"px");
		$("#divTopTool_sysres").addClass("divTopToolSelected");
		$("#divLeft").show();
	}
}

/**
 * 显示或隐藏系统控制台
 * @return {[type]} [description]
 */
function toggleConsole() {
	if($("#divConsole").is(':visible')) {
		hideConsole();
	} else {
		var height = getPixel($("#divConsole").css("height"));
		$("#divCenter").css("bottom", (height+1)+"px");
	  $("#divTopTool_console").addClass("divTopToolSelected");
	  $(".pageFrame").css("height", getPixel($("#divCenter").css("height"))+"px");
		$("#divConsole").show();
	}
}

/**
 * 显示或隐藏调试工具
 * @return {[type]} [description]
 */
function toggleDevTool() {
	taskBuilder.toggleDevTool();
}

/**
 * 服务器列表值发生变化时
 * @return {[type]} [description]
 */
function serverListOnChange() {
	var serverId = $("#sltServerList").val();
  taskBuilder.setCurServer(serverId);
	getProjList();
}

/**
 * 打开服务器设置
 * @return {[type]} [description]
 */
function openServerSetting() {

	var args = {
		dataset: {
			columns: [
      {
        "id": "id",
        "name": "编号",
        "type": "string",
        "width": "60px",
        "required": true
      },
      {
        "id": "name",
        "name": "名称",
        "type": "string",
        "width": "100px",
        "required": true
      },
      {
        "id": "address",
        "name": "地址",
        "type": "string",
        "width": "120px",
        "required": true
      },
      {
        "id": "port",
        "name": "端口",
        "type": "int",
        "width": "60px",
        "required": true
      },
      {
        "id": "orgcode",
        "name": "组织代码",
        "type": "string",
        "width": "60px",
        "required": true
      },
      {
        "id": "orgkey",
        "name": "组织密钥",
        "type": "string",
        "width": "130px",
        "required": true
      },
      {
        "id": "loginname",
        "name": "用户名",
        "type": "string",
        "width": "60px",
        "required": true
      },
      {
        "id": "password",
        "name": "登录密码",
        "type": "password",
        "width": "60px",
        "required": true
      }
    ]},
		val: config.servers
	};

	openDialog("服务器设置", "taskbuilder-tfp-designer/DataSetSetting.html", "780px", "355px", null, this,
		JSON.stringify(args), function(ret) {
		config.servers = ret;
    taskBuilder.setServers(ret);

		$("#sltServerList").empty();
		for(var i=0;i<config.servers.length;i++) {
			var server = config.servers[i];
			$("#sltServerList").append("<option value='"+server.id+"'>"+server.name+"</option>");
		}

		$("#divSysResTree").empty();

	  if(config.servers.length>0) getProjList();
  });
}


function showSQLQuerier() {
  openPage("SQL查询分析器", "taskbuilder-sql-querier/index.html");
}

function showFileManager() {
  openPage("文件管理器", "taskbuilder-file-manager/index.html");
}

//-------------------------------------- Console --------------------------------------

/*var webContents = remote.getCurrentWebContents();
webContents.on("console-message", function(event, level, message, line, sourceId) {
	//暂时禁用此功能
	return;
	var msgType = "";
	var msgColor = "#fff";
	if(level==0) {
		msgType = "verbose";
		msgColor = "#33CC00";
	} else if(level==1) {
		msgType = "info";
		msgColor = "#fff";
	} else if(level==2) {
		msgType = "warning";
		msgColor = "#FF9900";
	} else if(level==3) {
		msgType = "error";
		msgColor = "#FF0000";
	}
	var content = "<tr class='trConsole_"+msgType+"'>"
	  +"<td style='width:60px; line-height:18px; color:"+msgColor+";'>"+msgType+"</td>"
	  +"<td style='line-height:18px; color:";
	if(msgType == "error") content += msgColor
	else content += "#fff";
  content += ";'><div>"+message+"</div>";
	if($("#cbkShowMsgSource").is(":checked")) {
		content += "<div class='consoleMsgSource'>"+sourceId+" , "+line+"</div>";
	}
	content += "</td>";
	content += "</tr>";
	$("#divConsoleContent").append(content);
	var ele = document.getElementById("divConsoleContent");
	//判断元素是否出现了滚动条
	if(ele.scrollHeight > ele.clientHeight) {
		//设置滚动条到最底部
		ele.scrollTop = ele.scrollHeight;
	}
});*/

function consoleMsgTypeOnChange() {
	var msgType = $("#sltConsoleMsgType").val();
	if(msgType=="all") {
		$("#divConsoleContent").find("tr").show();
		return;
	}
	$("#divConsoleContent").find("tr").hide();
	$("#divConsoleContent").find(".trConsole_"+msgType).show();
}

//------------------------------- Sys Resource Tree ----------------------------

/**
 * 添加系统资源树节点
 * @param {[type]}  parentId      [description]
 * @param {[type]}  id            [description]
 * @param {[type]}  type          [description]
 * @param {[type]}  level         [description]
 * @param {Boolean} hasChild      [description]
 * @param {[type]}  icon          [description]
 * @param {[type]}  name          [description]
 * @param {[type]}  tag           [description]
 * @param {[type]}  rightBtnTitle [description]
 * @param {[type]}  rightBtnIcon  [description]
 * @param {[type]}  rightBtnClick [description]
 */
function addTreeNode(parentId, id, type, level, hasChild, icon, name, tag, rightBtnTitle, rightBtnIcon, rightBtnClick) {
	var str = "<div id=\""+id+"\" class=\"divResRow\" nowrap onclick=\"sysResNodeOnClick('"+id+"', '"+type+"','"+name+"')\" "
	  +"onmouseover=\"sysResNodeOnMouseOver('"+id+"')\" onmouseout=\"sysResNodeOnMouseOut('"+id+"')\">";
	if(hasChild) {
		str += "<img src=\"images/arrow/right.png\" style=\"margin-left:"+(level-1)*10+"px;\" />";
	  str += "<img src=\""+icon+"\" /><div class=\"divResName\" style=\"width: calc(100% - "+((level-1)*10+54)+"px);\">"+name+"</div>";
  } else {
		str += "<img src=\""+icon+"\" style=\"margin-left:"+((level-1)*10+16)+"px;\" />"
      +"<div class=\"divResName\" style=\"width: calc(100% - "+((level-1)*10+55)+"px);\">"+name+"</div>";
	}
	if(rightBtnIcon) str += "<div class=\"divResRight\" title=\""+rightBtnTitle+"\" onclick=\""
	  +rightBtnClick+"\">"+rightBtnIcon+"</div>";
	str += "</div>";
  if(level==1) {
		$("#"+parentId).append(str);
		if(hasChild) $("#"+parentId).append("<div id=\""+id+"_Res\" class=\"divRes\"></div>");
	} else {
		$("#"+parentId+"_Res").append(str);
		if(hasChild) $("#"+parentId+"_Res").append("<div id=\""+id+"_Res\" class=\"divRes\"></div>");
	}

	var node = {};
	node.id = id;
	node.parentId = parentId;
	node.type = type;
	node.level = level;
	node.childs = [];
	node.icon = icon;
	node.name = name;
	if(tag) node.tag = tag;

	if(rightBtnTitle) {
		node.rightBtn = {
			title: rightBtnTitle,
			icon: rightBtnIcon,
			onclick: rightBtnClick
		};
	}

	nodeDic[node.id] = node;

	var parentNode = nodeDic[node.parentId];
	if(parentNode) parentNode.childs.push(node.id);

	return node;
}

function getNodeByTag(tag, type) {
  for(nodeId in nodeDic) {
    let node = nodeDic[nodeId];
    if(type && node.type==type) {
      if(node.tag == tag) {
        return node;
      }
    } else if(node.tag == tag) {
      return node;
    }
  }
  return null;
}

function addServiceNode(servicePath) {
  let fileName = servicePath.substr(servicePath.lastIndexOf("/")+1);
  let fileType = fileName.substr(fileName.lastIndexOf(".")+1);
  let arrPath = servicePath.split("/");
  let projServiceNode = nodeDic["divProj_"+arrPath[0]+"_service"];
  if(!projServiceNode.isList) return;
  //如果是项目根目录的服务
  if(arrPath.length==3) {
    let newId = Guid.NewGuid().ToString("N");
    addTreeNode("divProj_"+arrPath[0]+"_service", "divFile_"+newId, 
      fileType, 3, false, "images/icon/file.png", fileName,
     "/app/"+servicePath, "删除", "-", "delFile('"+newId+"')");
    return;
  }
  let tmpPath = "/app/"+arrPath[0]+"/service";
  let parentNode = projServiceNode;
  for(let i=2;i<arrPath.length-1;i++) {
    tmpPath += "/"+arrPath[i];
    let tmpNode = getNodeByTag(tmpPath, "dir");
    //如果本级节点存在
    if(tmpNode) {
      //如果本级节点还未列出子节点，则不继续执行后续操作
      if(!tmpNode.isList) return;
      //如果已经到最后一级目录节点，则添加服务文件
      if(i==(arrPath.length-2)) {
        let newId = Guid.NewGuid().ToString("N");
        addTreeNode(tmpNode.id, "divFile_"+newId, 
          fileType, tmpNode.level+1, false, "images/icon/file.png", fileName,
         "/app/"+servicePath, "删除", "-", "delFile('"+newId+"')");
      } else {
        //如果没到最后一级目录节点，这设置父节点
        parentNode = tmpNode;
      }
    } else {
      //如果没有找到本级节点，则创建该节点，并停止查找下级节点
      let newId = Guid.NewGuid().ToString("N");
      addTreeNode(parentNode.id, "divDir_"+newId, "Dir", parentNode.level+1, true, 
        "images/icon/dir.png", arrPath[i], tmpPath, "添加", "+", 
        "showAddServerResDialog('divDir_"+newId+"')");
      return;
    }
  }
}

function getServicePath(tfpPath , modelName , operate) {
  let servicePath = tfpPath.substr(9);
  let projName = "";
  if(servicePath.indexOf("/")>0) {
    projName = servicePath.substr(0, servicePath.indexOf("/"));
    servicePath = projName+"/service"+servicePath.substr(servicePath.indexOf("/"));
  } else {
    projName = servicePath;
    servicePath = projName+"/service";
  }
  servicePath += "/"+operate+modelName.substr(0,1).toUpperCase()+modelName.substr(1);
  return servicePath;
}

/**
 * 鼠标经过系统资源节点时
 * @param  {[type]} divId [description]
 */
function sysResNodeOnMouseOver(divId) {
  if(divId==curSysResNodeId) return;
  $("#"+divId).css("background-color", "#444");
}

/**
 * 鼠标移出系统资源节点时
 * @param  {[type]} divId [description]
 */
function sysResNodeOnMouseOut(divId) {
  if(divId==curSysResNodeId) return;
  $("#"+divId).css("background-color", "");
}

/**
 * 点击系统资源节点时
 * @param  {[type]} nodeId [description]
 */
function sysResNodeOnClick(nodeId) {
	var imgArrow = $("#"+nodeId).find("img").first();
	if(imgArrow.attr("src").indexOf("right.png")>0) {
	  imgArrow.attr("src", "images/arrow/down.png");
		$("#"+nodeId+"_Res").show();
	} else if(imgArrow.attr("src").indexOf("down.png")>0) {
		imgArrow.attr("src", "images/arrow/right.png");
		$("#"+nodeId+"_Res").hide();
	}
	if(curSysResNodeId==nodeId) return;
  $("#"+curSysResNodeId).css("background-color", "");
	//$("#"+curSysResNodeId).find("label").css("color", "#ccc");
	curSysResNodeId = nodeId;
  $("#"+nodeId).css("background-color", "#555");
	//$("#"+nodeId).find("label").css("color", "#3f0");

	var node = nodeDic[nodeId];
	if(!node) return;
  //console.log(node.id+","+node.type+","+node.tag);
  if(node.type=="Dir" && !node.isList) {
    if(!node.tag) {
      //showMsg(node.tag+"不存在！");
      return;
    }
    node.isList = true;
    setStatusBar("路径："+node.tag);
		listFile(node);
	} else if(node.type=="tdm") {
    openPage(node.name, "taskbuilder-model-designer/index.html?path="+node.tag, node.id);
    setStatusBar("路径："+node.tag);
  } else if(node.type=="tbs") {
    openPage(node.name, "taskbuilder-tbs-designer/index.html?path="+node.tag, node.id);
    setStatusBar("路径："+node.tag);
  } else if(node.type=="tfp") {
		openPage(node.name, "taskbuilder-tfp-designer/index.html?path="+node.tag, node.id);
    setStatusBar("路径："+node.tag);
	} else if(node.type=="htm" || node.type=="html" || node.type=="js" || node.type=="json" || node.type=="css") {
		openPage(node.name, "taskbuilder-code-editor/index.html?type="+node.type+"&path="+node.tag, node.id);
    setStatusBar("路径："+node.tag);
	} else if(node.type=="img") {
		openPage(node.name, "ImageBrowser/index.html?path="+node.tag, node.id);
    setStatusBar("路径："+node.tag);
	}
}

/**
 * 点击系统资源节点展开图标时
 * @param  {[type]} img   [description]
 * @param  {[type]} divId [description]
 * @return {[type]}       [description]
 */
function sysResNodeImgOnClick(img,divId) {
	sysResNodeOnClick(divId);
	if($(img).attr("src").indexOf("right.png")>0) {
	  $(img).attr("src", "images/arrow/down.png");
		$("#"+divId+"_Res").show();
	} else {
		$(img).attr("src", "images/arrow/right.png");
		$("#"+divId+"_Res").hide();
	}
}

//--------------------------------- Proj Manager --------------------------------

/**
 * 新建项目
 */
function addNewProj() {
	var e = window.event;
	e.stopPropagation();

	openDialog("新建项目", "taskbuilder-proj-manager/createProj.tfp", null, null, null, null, null, function(ret) {
		let pcode = ret;
    if($("#divProj_"+pcode).length>0) return;
		addProjNode(pcode, pcode);
	});
}

function delProj(pcode) {
	var e = window.event;
	e.stopPropagation();

	confirm("确定删除？", function(ret) {
		taskBuilder.requestByIPC("dev/service/proj/delete", {code: pcode}, function(req, res) {
	  	$("#divProj_"+pcode).remove();
	  	$("#divProj_"+pcode+"_Res").remove();
	  	delete nodeDic["divProj_"+pcode];
	  });
	});
}

/**
 * 显示添加TDM对话框
 * @param  {[type]} nodeId [description]
 * @return {[type]}        [description]
 */
function showAddDataObjDialog(nodeId) {
	var e = window.event;
	e.stopPropagation();

	var node = nodeDic[nodeId];
	if(!node) return;
	let args = {
    name: node.name, 
    path: node.tag,
    proj: getProjName(node)
  };
	openDialog("添加"+node.name, "taskbuilder-model-designer/createModel.tfp", 
		"290px", "520px", null, window, JSON.stringify(args), function(ret) {
    if(ret.type=="new") return;
		if(!$("#"+node.id+"_Res").is(":visible")) {
			node.isList = false;
			sysResNodeOnClick(nodeId);
		} else {
			let newId = Guid.NewGuid().ToString("N");
			let fileType = (node.name=="数据模型") ? "tdm" : "tda";
			let fileName = ret.modelName+"."+fileType;
			addTreeNode(node.id, "divFile_"+newId, fileType, node.level+1, false,
				"images/icon/file.png", fileName, node.tag+'/'+fileName, 
				"删除", "-", "delFile('"+newId+"')");
		}
    let modelFile = node.tag+"/"+ret.modelName+".tdm";
    openPage(ret.modelName+".tdm", "taskbuilder-model-designer/index.html?path="+modelFile);
    setStatusBar("路径："+modelFile);
	});
}

/**
 * 显示添加后台服务资源对话框
 * @param  {[type]} nodeId [description]
 * @return {[type]}        [description]
 */
function showAddServerResDialog(nodeId) {
	var e = window.event;
	e.stopPropagation();

	var node = nodeDic[nodeId];
	if(!node) return;
  var args = {
    id: node.id,
    level: node.level,
    path: node.tag,
    proj: getProjName(node)
  };
	openDialog("添加后台资源", "taskbuilder-proj-manager/createServerRes.tfp", 
		"420px", "540px", null, window, JSON.stringify(args), function(ret) {
    if(!ret) return;
    let res = JSON.parse(ret);
		if(!$("#"+node.id+"_Res").is(":visible")) {
			node.isList = false;
			sysResNodeOnClick(nodeId);
		} else {
			let newId = Guid.NewGuid().ToString("N");
			if(res.type=="dir") {
			  addTreeNode(node.id, "divDir_"+newId, "Dir", node.level+1, true, "images/icon/dir.png", 
				  res.name, node.tag+'/'+res.name, "添加", "+", "showAddServerResDialog('divDir_"+newId+"')");
			} else {
			  let fileName = res.name.endsWith(res.type) ? res.name : res.name+"."+res.type;
			  addTreeNode(node.id, "divFile_"+newId, res.type, node.level+1, false, "images/icon/file.png", 
				  fileName, node.tag+'/'+fileName, "删除", "-", "delFile('"+newId+"')");
		  }
		}
	});
}

/**
 * 显示添加客户端资源对话框
 * @param  {[type]} nodeId [description]
 * @return {[type]}        [description]
 */
function showAddClientResDialog(nodeId) {
	var e = window.event;
	e.stopPropagation();

	var node = nodeDic[nodeId];
	if(!node) return;
  var args = {
    id: node.id,
    level: node.level,
    path: node.tag,
    proj: getProjName(node)
  };
	openDialog("添加前端资源", "taskbuilder-proj-manager/createClientRes.tfp", 
		"420px", "530px", null, window, JSON.stringify(args), function(ret) {
    if(!ret) return;
    let res = JSON.parse(ret);
    if(!$("#"+node.id+"_Res").is(":visible")) {
			node.isList = false;
			sysResNodeOnClick(nodeId);
		} else {
			let newId = Guid.NewGuid().ToString("N");
			if(res.type=="dir") {
			  addTreeNode(node.id, "divDir_"+newId, "Dir", node.level+1, true, "images/icon/dir.png", 
				  res.name, node.tag+'/'+res.name, "添加", "+", "showAddClientResDialog('divDir_"+newId+"')");
			} else {
			  let fileName = res.name.endsWith("."+res.type) ? res.name : res.name+"."+res.type;
			  addTreeNode(node.id, "divFile_"+newId, res.type, node.level+1, false, "images/icon/file.png", 
				  fileName, node.tag+'/'+fileName, "删除", "-", "delFile('"+newId+"')");
		  }
		}
	});
}

/**
 * 显示添加应用对话框
 * @param  {[type]} nodeId [description]
 * @return {[type]}        [description]
 */
function showAddAppDialog(nodeId) {
  var e = window.event;
  e.stopPropagation();

  var node = nodeDic[nodeId];
  if(!node) return;
  var args = {
    id: node.id,
    level: node.level,
    path: node.tag,
    proj: getProjName(node)
  };
  openDialog("添加应用", "taskbuilder-proj-manager/createApp.tfp", 
    "480px", "300px", null, window, JSON.stringify(args), function(ret) {
    if(!ret) return;
    let app = JSON.parse(ret);
    if(!$("#"+node.id+"_Res").is(":visible")) {
      node.isList = false;
      sysResNodeOnClick(nodeId);
    } else {
      addTreeNode(node.id, "divApp_"+app.id, 'app', node.level+1, false, 
        "images/icon/app.png", app.name, app.id, "删除", "-", "delApp('"+app.id+"')");
    }
  });
};

/**
 * 添加项目资源节点
 * @param {[type]} pcode [description]
 * @param {[type]} pname [description]
 */
function addProjNode(pcode, pname) {
	var level = 1;
	addTreeNode("divSysResTree", "divProj_"+pcode, "Proj", level, true, "images/icon/proj.png", pname,
    pcode, "删除", "-", "delProj('"+pcode+"')");
	addTreeNode("divProj_"+pcode, "divProj_"+pcode+"_model", "Dir", level+1, true, "images/icon/model.png", "数据模型",
	  "/app/"+pcode+"/model", "添加", "+", "showAddDataObjDialog('divProj_"+pcode+"_model')");
	//addTreeNode("divProj_"+pcode, "divProj_"+pcode+"_dao", "Dir", level+1, true, "images/icon/dao.png", "数据访问",
	//  "/app/"+pcode+"/dao", "添加", "+", "showAddDataObjDialog('divProj_"+pcode+"_dao')");
	addTreeNode("divProj_"+pcode, "divProj_"+pcode+"_service", "Dir", level+1, true, "images/icon/code.png", "后台服务",
    "/app/"+pcode+"/service", "添加", "+", "showAddServerResDialog('divProj_"+pcode+"_service')");
  addTreeNode("divProj_"+pcode, "divProj_"+pcode+"_web", "Dir", level+1, true, "images/icon/ui.png", "前端文件",
    "/web/app/"+pcode, "添加", "+", "showAddClientResDialog('divProj_"+pcode+"_web')");
  addTreeNode("divProj_"+pcode, "divProj_"+pcode+"_app", "Apps", level+1, true, "images/icon/app.png", "应用管理",
    pcode, "添加", "+", "showAddAppDialog('divProj_"+pcode+"_app')");
}

/**
 * 获得当前节点所属项目的名称
 * @param  {[type]} node [description]
 * @return {[type]}      [description]
 */
function getProjName(node) {
  let projName = null;
  let pnode = node;
  while(true) {
    pnode = nodeDic[pnode.parentId];
    if(!pnode) break;
    if(pnode.type=="Proj") {
      projName = pnode.name;
      break;
    }
  }
  return projName;
}

/**
 * 获取文件列表
 * @param  {[type]} node [description]
 * @return {[type]}      [description]
 */
function listFile(node) {
	taskBuilder.requestByIPC("dev/service/proj/getFileList", {dir: node.tag}, function(req, res) {
		if(res.code!=0) {
			var errMsg = res.message;
			if(errMsg.indexOf("ECONNREFUSED")>=0) errMsg = "连接服务器失败！";
			showErr(errMsg);
			return;
		}
		$("#"+node.id+"_Res").empty();
		for(var i=0;i<res.dirs.length;i++) {
			var dir = res.dirs[i];
			var newId = Guid.NewGuid().ToString("N");
			if(node.tag.startsWith("/app/")) {
			  addTreeNode(node.id, "divDir_"+newId, "Dir", node.level+1, true, "images/icon/dir.png", 
			  	dir.name, node.tag+'/'+dir.name, "添加", "+", "showAddServerResDialog('divDir_"+newId+"')");
		  } else {
		  	addTreeNode(node.id, "divDir_"+newId, "Dir", node.level+1, true, "images/icon/dir.png", 
			  	dir.name, node.tag+'/'+dir.name, "添加", "+", "showAddClientResDialog('divDir_"+newId+"')");
		  }
		}
		for(var i=0;i<res.files.length;i++) {
			var file = res.files[i];
			var newId = Guid.NewGuid().ToString("N");
			var li = file.name.lastIndexOf(".");
			var nodeType = "";
			if(li>0) nodeType = file.name.substring(li+1).toLowerCase();
			addTreeNode(node.id, "divFile_"+newId, nodeType, node.level+1, false,
				"images/icon/file.png", file.name, node.tag+'/'+file.name, "删除", "-", "delFile('"+newId+"')");
		}
	});
}

function delFile(fileId) {
	var e = window.event;
	e.stopPropagation();

  let nodeId = "divFile_"+fileId;
	var node = nodeDic[nodeId];
	if(!node) return;

	confirm("确定删除？", function() {
		taskBuilder.requestByIPC("dev/service/proj/deleteFile", {path: node.tag}, function(req, res) {
	  	$("#"+nodeId).remove();
	  	node = null;
	  	delete nodeDic[nodeId];
	  });
  });
}

/**
 * 获取项目列表
 * @return {[type]} [description]
 */
function getProjList() {
	$("#divSysResTree").empty();
	taskBuilder.requestByIPC("dev/service/proj/getList", {}, function(req, res) {
    if(res.code!=0) {
			var errMsg = res.message;
			if(errMsg.indexOf("ECONNREFUSED")>=0) errMsg = "连接服务器失败！";
			showErr(errMsg);
			return;
		}
		curSysResNodeId = null;
		for(var i=0;i<res.ret.length;i++) {
			addProjNode(res.ret[i], res.ret[i]);
		}
	});
}

//-------------------------------------- Init --------------------------------------

$(function() {

  $("#spanCurYear").text((new Date()).getFullYear());
  //console.log("");

  $( "#divLeft").resizable({
    handles: 'e',
    maxWidth: 400,
    minWidth: 240,
		resize: function(event, ui) {
      $("#divLeft").css("width", ui.size.width+"px");
      $("#divMain").css("left", (ui.size.width+2)+"px");
    }
	});

  $( "#divConsole").resizable({
    handles: 'n',
    maxHeight: 400,
    minHeight: 120,
		resize: function(event, ui) {
    	$("#divConsole").css("top", "");
      $("#divCenter").css("bottom", (ui.size.height+1)+"px");
    	$("#divCenter").find(".pageFrame").css("height", $("#divCenter").css("height"));
    }
	});

  $("body").keyup(function(event) {
    if($("#divConfirm").is(":visible")) {
      if(event.keyCode ==13) {
        if($("#divConfirm").find("input").get(0).is(":focus")) {
          closeConfirm(true);
        } else {
          closeConfirm(false);
        }
      } else if(event.keyCode ==37) {
        $("#divConfirm").find("input[value=确定]").focus();
      } else if(event.keyCode ==39) {
        $("#divConfirm").find("input[value=取消]").focus();
      }
    }
  });

	config = window.taskBuilder.getConfig();
	if(config.servers) {
		for(var i=0;i<config.servers.length;i++) {
			var server = config.servers[i];
			$("#sltServerList").append("<option value='"+server.id+"'>"+server.name+"</option>");
		}
	}

	if(config.servers.length>0) getProjList();
});
