<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet"  type="text/css" href="${ctx}/css/indexNew/base.css" />
<link rel="stylesheet"  type="text/css" href="${ctx}/css/indexNew/all.css" />
<link rel="stylesheet"  type="text/css" href="${ctx}/css/indexNew/perfect-scrollbar.css" />
<title>知识图谱平台</title>
<style>
	*{
		box-sizing: border-box;
	}
</style>
</head>
<body class="bg1">
<div class="headCon">
	<jsp:include page="../top.jsp">
	<jsp:param name="index" value="1" />
	</jsp:include>
</div>
<div class="searchCon">
	<div class="subNavUp">
		<div class="upPart">
			<div class="btns">
				<i class="prev"></i>
				<i class="next"></i>
				<i class="save"></i>
			</div>
			<div class="connect">
				连接<span><i></i>+  添加</span>
			</div>
			<ul id="connList" class="connList">
				<li>
					<p>海南易建科技</p>
				</li>
			</ul>
		</div>
	</div>
	<div class="sunNavDown">
		<div class="downPart">
			<p>文件</p>
			<div>
				<ul id="filesList">
				</ul>
			</div>
		</div>
	</div>
	<div class="DShistoryCon">
		<p>已保存数据</p>
		<div class="DShistory">
			<ul>
				<li>海南人口统计</li>
				<li>海南人口统计</li>
			</ul>
		</div>
	</div>
</div>
<div class="main" id="main" style="position:relative;padding:0;">
	<div class="connectArea" id="connectArea" style="position:relative;">
		<div class="connectCon">
			<div class="connectionClear" id="connectionClear">清空</div>
			<div class="connectDetail" hidden id="connectDetail">
				<div class="detailHead">
					联接<i class="close1"></i>
				</div>
				<div class="connType">
					<ul>
						<li class="connTypeActive"><img src="${ctx}/images/indexNew/inside.png"><span>内部</span></li>
						<li><img src="${ctx}/images/indexNew/leftJoin.png"><span>左侧</span></li>
						<li><img src="${ctx}/images/indexNew/rightJoin.png"><span>右侧</span></li>
						<li><img src="${ctx}/images/indexNew/outside.png"><span>外部</span></li>
					</ul>
				</div>
				<div class="detailList">
					<table>
						<thead>
							<tr>
								<th style="width:40%;">数据源</th>
								<th style="width:12%;"></th>
								<th style="width:40%;">people.txt</th>
								<th style="width:8%;"></th>
							</tr>
						</thead>
						<tbody>
							<tr>
								<td style="position:relative">
									<input type="text" id="source" placeholder="添加关联" />
									<ul id="chooseSourceItem" hidden>

									</ul>
								</td>
								<td>=</td>
								<td style="position:relative">
									<input type="text" id="thisSource" placeholder="添加关联" />
									<ul id="chooseThisItem" hidden>

									</ul>
								</td>
								<td class="connectClear">X</td>
							</tr>
						</tbody>
					</table>
				</div>
			</div>
			<ul class="connectAreaRow" id="connectAreaRow" style="width:1300px">
			<!-- 
				<li>
					<ul class="connectAreaCol">
						<li>
							<div class="DSTableItem">yijiankeji</div>
						</li>
					</ul>
				</li>
				<li>
					<ul class="connectAreaCol">
						<li>
							<div class="link1"><i></i></div>
							<div class="DSTableItem">yijiankeji</div>
						</li>
						<li>
							<div class="link2"><i></i></div>
							<div class="DSTableItem">yijiankeji</div>
						</li>
					</ul>
				</li>
				<li>
					<ul class="connectAreaCol">
						<li>
							<div class="link1"><i></i></div>
							<div class="DSTableItem">yijiankeji</div>
						</li>
					</ul>
				</li>
				  -->
			</ul>
		</div>
	</div>
	<div class="tableArea">
		<div class="tableAreaHead"></div>
		<div class="table" id="table">
			<div class="tableListInfo">没有关联信息</div>
		</div>
	</div>
</div>

<script type="text/html" id="filesList_template"> 
<!for(var i=0;i<data.length;i++){!>
			<li data-file="<!=data[i].name!>" data-index="<!=i!>" draggable="true">
						<div>
							<i></i>
							<!=data[i].name!>
						</div>
					</li>
<!}!>
</script>
<script type="text/html" id="firstNode_template"> 
<li data-file="<!=name!>">
	<div class="DSTableItem"><!=name!></div>
</li>
</script>
<script type="text/html" id="link1_template"> 
<li data-file="<!=name!>" data-linkindex="<!=data.connPoolIndex!>">
	<div class="link1" data-link=""><i></i></div>
	<div class="DSTableItem"><!=name!></div>
</li>
</script>
<script type="text/html" id="link2_template"> 
<li data-file="<!=name!>" data-linkindex="<!=data.connPoolIndex!>">
	<div class="link2" data-link=""><i></i></div>
	<div class="DSTableItem"><!=name!></div>
</li>
</script>
<script type="text/html" id="source_template"> 
<!for(var i=0;i<data.length;i++){!>
	<li class="sourceName" data-name="<!=data[i].name!>"><!=data[i].name!></li>
	<!for(var j=0;j<data[i].cols.length;j++){!>
		<li class="sourceItem" data-file="<!=data[i].name!>" data-item="<!=data[i].cols[j]!>"><!=data[i].cols[j]!></li>
	<!}!>
<!}!>
</script>
<script type="text/html" id="tableData_template"> 
<!if(data.length==0){!>
<div class="tableListInfo">没有关联信息</div>
<!}else{!>
<table id="connTable">
	<thead>
					<tr>
						<!for(var props in data[0]){!>
							<th style="width:200px;"><!=props!></th>
						<!}!>
 					</tr>		
				</thead>
				<tbody>
					<!for(var i=0;i<data.length;i++){!>
						<tr>
							<!for(var props in data[i]){!>
								<td title="<!=data[i][props]!>"><!=(data[i][props].length>20?data[i][props].substring(0,20)+"...":data[i][props])!></td>
							<!}!>					
						</tr>
					<!}!>
				</tbody>
			</table>
<!}!>
</script>

<script src="${ctx}/js/lib/jquery-1.11.1.min.js"></script>
<script src="${ctx}/js/lib/core.js"></script>
<script src="${ctx}/js/lib/baiduTemplate.js"></script>
<script src="${ctx}/js/lib/perfect-scrollbar.jquery.js"></script>
<script src="${ctx}/js/component/data.js"></script>
<script>
/*
	var json = {
			data:[
			      {
			    	  name:"enterprise.txt",
			    	  key:["enterpriseID","name","date","address","investment","presidentID","presidentName"],
			    	  value:[
			    	         {"enterpriseID":"001","name":"易建科技股份有限公司","date":"2006-9-10","address":"国贸嘉陵大厦17层","investment":"3500万","presidentID":"46010019760905","presidentName":"喻龑冰"},
			    	         {"enterpriseID":"002","name":"海航集团有限公司","date":"1996-4-1","address":"国兴大道海航大厦","investment":"900亿","presidentID":"46010119650708","presidentName":"陈峰"}
			    	         ]
			      },
			      {
			    	  name:"enterpriseManagers.txt",
			    	  key:["enterpriseID","peopleID","position"],
			    	  value:[
			    	         {"enterpriseID":"001","peopleID":"46010019760905","position":"董事长"},
			    	         {"enterpriseID":"002","peopleID":"46010119650708","position":"董事长"}
			    	         ]
			      },
			      {
			    	  name:"people.txt",
			    	  key:["ID","peoName","gender"],
			    	  value:[
			    	         {"ID":"46010019760905","peoName":"喻龑冰","gender":"male"},
			    	         {"ID":"46010119650708","peoName":"陈峰","gender":"male"}
			    	         ]
			      }
			      ]
	};
	*/
	
	var connPool = []; //链接数目
	var connData = [];
	var connLink = [];
	var connName = [];
	console.log(json);
	resize();
	$(window).resize(function(){
		resize();
	});
	function resize(){
		//获取窗口高度
		var windowheight=$(window).height();
		var searchCon = windowheight-40-146;
		$(".searchCon").css("height",windowheight-40);
		$(".main").css("height",windowheight-40-3);
		$(".table").css("height",windowheight-40-333-42);
	}
	//perfect-scrollbar滚动条插件
	$('.table').perfectScrollbar();
	$('#chooseSourceItem').perfectScrollbar();
	$('#chooseThisItem').perfectScrollbar();
	$("#table").perfectScrollbar();
	//返回数据导入页面
	$(".prev").click(function(){
		 window.location.href="/KnowledgeGraph/KG/importDS.do";
	});
	//清空链接区域
	$("#connectionClear").click(function(){
		//初始化全局变量，清空连线
		connPool.splice(0,connPool.length);
		connData.splice(0,connData.length);
		connLink.splice(0,connLink.length);
		connName.splice(0,connName.length);
		$("#table").html("<div class='tableListInfo'>没有关联信息</div>");//清空表格
		$("#connectAreaRow").html("");//清空实体链接
		$("#connectDetail").hide();//隐藏弹出框
	});
	//打开弹窗
	$("#connectAreaRow").delegate("i","click",function(e){
		var thisFileName = $(this).parent().parent().data("file");
		var linkIndex = $(this).parent().parent().data("linkindex");
		$("#connectDetail #source").val(connPool[linkIndex].sourceFactor).data("file",connPool[linkIndex].sourceName);
		$("#connectDetail #thisSource").val(connPool[linkIndex].targetFactor).data("file",connPool[linkIndex].targetName);
		$("#connectDetail").css("left",e.clientX-465).css("top",e.clientY-40);
		$("#connectDetail .detailList th").eq(2).html(thisFileName);
		$("#connectDetail").show().data("linkindex",linkIndex);
		$('#chooseSourceItem').hide();
		$('#chooseThisItem').hide();
	});
	//关闭弹窗
	$("#connectDetail .close1").click(function(){
		$("#connectDetail").hide();
	});
	//选择匹配字段列表
	$("#connectDetail #source").focus(function(){
		var thisFileName = $("#connectDetail .detailList th").eq(2).html();
		var colsMap = getCols(thisFileName,false);
		var ht = baidu.template("source_template",{data:colsMap});
		$(this).parent().find("#chooseSourceItem").html(ht);
		$('#chooseSourceItem').perfectScrollbar('update');
		$('#chooseSourceItem').show();
	}).blur(function(){
		$('#chooseSourceItem').hide();
	});
	$("#connectDetail #thisSource").focus(function(){
		var thisFileName = $("#connectDetail .detailList th").eq(2).html();
		var colsMap = getCols(thisFileName,true);
		var ht = baidu.template("source_template",{data:colsMap});
		$(this).parent().find("#chooseThisItem").html(ht);
		$('#chooseThisItem').perfectScrollbar('update');
		$('#chooseThisItem').show();
	}).blur(function(){
		$('#chooseThisItem').hide();
	});
	//选择字段
	$("#chooseSourceItem").delegate(".sourceItem","mousedown",function(){
		$('#chooseSourceItem').hide();
		$("#source").val($(this).html()).data("file",$(this).data("file"));
		changeConnect($('#connectDetail').data("linkindex"));
	});
	$("#chooseThisItem").delegate(".sourceItem","mousedown",function(){
		$('#chooseThisItem').hide();
		$("#thisSource").val($(this).html()).data("file",$(this).data("file"));
		changeConnect($('#connectDetail').data("linkindex"));
	});
	//清空联接
	$(".detailList .connectClear").click(function(){
		$("#connectDetail #source").val("");
		$("#connectDetail #thisSource").val("");
	});
	//获取文件名和字段map
	function getCols(thisFileName,flag){
		var colsMap = [];
		for(var i=0;i<json.data.length;i++){
			if(flag){
				console.log("getData:");
				console.log(connName)
				if(thisFileName==json.data[i].name && connName.indexOf(json.data[i].name)>=0){
					colsMap.push({
						name:json.data[i].name,
						cols:json.data[i].key
					});
				}
			}else{
				if(thisFileName!=json.data[i].name && connName.indexOf(json.data[i].name)>=0){
					colsMap.push({
						name:json.data[i].name,
						cols:json.data[i].key
					});
				}	
			}
		}
		return colsMap;
	}
	//数据源列表,为每一个list绑定文件数据
	function getDSList(){
		var ht = baidu.template("filesList_template",json);
		$("#filesList").html(ht);
		$("#filesList li").each(function(){
			$(this).data("content",json.data[$(this).data("index")]);
		});
	}
	/*数据源拖拽*/
	$("#filesList").delegate("li","dragstart",function(e){
		e.originalEvent.dataTransfer.setData("file",$(this).data("file"));
	});
	$("#main").delegate("#connectArea","dragover",function(e){
		e.preventDefault();
	});
	$("#main").delegate("#connectArea","drop",function(e){
		e.preventDefault();
		e.stopPropagation(); 
		//接收files数据
		var content = e.originalEvent.dataTransfer.getData("file");
		addFiles(content);
	});
	function addFiles(name){
		if(connName.indexOf(name)>=0){
			return;
		}
		var files = null;
		for(var i=0;i<json.data.length;i++){
			if(json.data[i].name==name){
				files = json.data[i];
				break;
			}
		}
		connData.push(files);
		connName.push(name);
		//选择连线，链接列表
		autoChoose();
		//实体链接
		entityConn();
	}
	//自动选择
	function autoChoose(){
		connPool.splice(0, connPool.length);//清除当前的连线
		if(connName.length==1){
			showTable(connData[0].value);
		}else{
			var sourceName = connName[0];
			for(var k=1;k<connData.length;k++){
				var targetName = connName[k];
				var isConn = false;
				for(var i=0;i<connData[0].key.length;i++){//第一个实体的列
					if(isConn) break;//如果比配上，退出循环
					
					for(var j=0;j<connData[k].key.length;j++){//第n个实体的列
						if(connData[0].key[i]==connData[k].key[j]){
							connPool.push({
								sourceName:sourceName,
								targetName:targetName,
								sourceFactor:connData[0].key[i],
								targetFactor:connData[k].key[j]
							});
							isConn = true;
							break;//进行第一个实体和下一个实体的列比较
						}else{
							if(j==connData[k].key.length-1 && i==connData[0].key.length-1){
								connPool.push({
									sourceName:sourceName,
									targetName:targetName,
									sourceFactor:connData[0].key[0],
									targetFactor:connData[k].key[0]
								});
							}
						}//end of if
					}//end of 3th for
				}//end of second for
			}//end of first for
			console.log(connPool);
			var tableData = buildConnection();
			console.log(tableData);
			showTable(tableData);
		}//end of if
	}
	//链接实体
	function entityConn(){
		$(".connectAreaRow").html("");
		if(connName.length==1){//只有一个实体
			var ht = baidu.template("firstNode_template",connData[0]);
			$(".connectAreaRow").append("<li><ul class='connectAreaCol'>"+ht+"</ul></li>");
		}else{//多余一个实体
			for(var i=0;i<connPool.length;i++){
				var $source = $(".connectAreaRow").find("[data-file='"+connPool[i].sourceName+"']");
				var sourceOutLiIndex = 0;
				if($source[0]==null || $source[0]==undefined){
					var ht = baidu.template("firstNode_template",getFileAll(connPool[i].sourceName));
					$(".connectAreaRow").append("<li><ul class='connectAreaCol'>"+ht+"</ul></li>");
				}else{
					sourceOutLiIndex = $source.parent().parent().index();
				}
				var targetOutLiIndex = sourceOutLiIndex+1;
				var outLiNum = $(".connectAreaRow>li").length;
				var targetData = getFileAll(connPool[i].targetName);
				targetData.connPoolIndex = i;
				if(outLiNum>targetOutLiIndex){
					var ht = baidu.template("link2_template",targetData);
					$(".connectAreaRow>li:nth-child("+(targetOutLiIndex+1)+") .connectAreaCol").append(ht);
				}else{
					var ht = baidu.template("link1_template",targetData);
					$(".connectAreaRow").append("<li><ul class='connectAreaCol'>"+ht+"</ul></li>");
				}
			}
		}
	}
	//建立链接
	function changeConnect(linkIndex){
		console.log("linkIndex:"+linkIndex);
		var sourceName = $("#source").data("file");
		var targetName = $("#thisSource").data("file");
		var sourceFactor = $("#source").val();
		var targetFactor = $("#thisSource").val();
		//备份改变之前的数据
		var prevLinkStatus = Object.assign({},connPool[linkIndex]);
		console.log(prevLinkStatus);
		
		if(sourceName!="" && sourceFactor!="" && targetName!="" && targetFactor!=""){
			connPool.splice(linkIndex,1,{
				sourceName:sourceName,
				sourceFactor:sourceFactor,
				targetName:targetName,
				targetFactor:targetFactor
			});
			console.log(["before",connPool]);
			var flag = false;
			//判断第一个表是否被关联到，如果没有关联提示错误，关联的话将关联的连线提到第一个
			for(var i=0;i<connPool.length;i++){
				if(connPool[i].sourceName==connName[0]){
					flag = true;
					if(i>0){
						var tmp = Object.assign({},connPool[i]);
						connPool.splice(i,1);
						connPool.splice(0,0,tmp);
					}
					break;
				}
			}
			console.log(["after",connPool]);
			if(flag){
				//刷新表格和实体连线
				var tableData = buildConnection();
				console.log(tableData);
				showTable(tableData);
				entityConn();
			}else{
				//恢复成原来的边
				connPool.splice(linkIndex,1,{
					sourceName:prevLinkStatus.sourceName,
					sourceFactor:prevLinkStatus.sourceFactor,
					targetName:prevLinkStatus.targetName,
					targetFactor:prevLinkStatus.targetFactor
				});
				//恢复弹出框的内容
				$("#connectDetail #source").val(prevLinkStatus.sourceFactor).data("file",prevLinkStatus.sourceName);
				$("#connectDetail #thisSource").val(prevLinkStatus.targetFactor).data("file",prevLinkStatus.targetName);
				alert("无法更改"+targetName+"的联接子句信息");
			}
		}
	}
	function showTable(tableData){
		var ht = baidu.template("tableData_template",{data:tableData});
		$("#table").html(ht);
		$("#connTable").css("width",200*$("#connTable tbody tr").eq(0).find("td").length);
		$('#table').perfectScrollbar('update');
	}
	function buildConnection2(){
		console.log("链接条数:"+connPool.length);
		if(connPool.length<=0){
			return null;
		}
		var result = new Object();
		for(var i=0;i<connPool.length;i++){
			var oneConn = connPool[i];
			
			
		}
		return entries;
	}
	function buildConnection(){
		console.log("链接条数:"+connPool.length);
		if(connPool.length<=0){
			return null;
		}
		var entries = (getFileData(connPool[0].sourceName)).concat();
		var fileNames = [];
		for(var i=0;i<connPool.length;i++){
			var tmp = [];
			var oneConn = connPool[i];
			var oneSourceValue,
				oneTargetValue,
				sourceFactor,
				targetFactor;
			if(i==0){
				fileNames.push(oneConn.sourceName);
				fileNames.push(oneConn.targetName);
				oneSourceValue = entries;
				oneTargetValue = getFileData(oneConn.targetName);
				sourceFactor = oneConn.sourceFactor;
				targetFactor = oneConn.targetFactor;
			}else{
				if(fileNames.indexOf(oneConn.sourceName)>=0){
					oneSourceValue = entries;
					oneTargetValue = getFileData(oneConn.targetName);
					fileNames.push(oneConn.targetName);
					sourceFactor = oneConn.sourceFactor;
					targetFactor = oneConn.targetFactor;
				}else if(fileNames.indexOf(oneConn.targetName)>=0){
					oneSourceValue = getFileData(oneConn.sourceName);
					oneTargetValue = entries;			
					fileNames.push(oneConn.sourceName);
					sourceFactor = oneConn.targetFactor;
					targetFactor = oneConn.sourceFactor;
				}else{
					return null;
				}
			}
			
			if(oneSourceValue!=null && oneTargetValue!=null){
				for(var j=0;j<oneSourceValue.length;j++){
					var sourceItem = oneSourceValue[j][sourceFactor];
					for(var k=0;k<oneTargetValue.length;k++){
						var targetItem = oneTargetValue[k][targetFactor];
						if(sourceItem == targetItem){
							//var res = mergeEntry(oneSourceValue[j],oneTargetValue[k]);
							tmp.push(Object.assign(clone(oneSourceValue[j]),clone(oneTargetValue[k])));
							//tmp.push(res);
							//break;
						}
					}
				}
				entries = tmp.concat();
			}
		}
		return entries;
	}
	function mergeEntry(sourceEntry,targetEntry){
		
	}
	function getFileData(name){
		for(var i=0;i<json.data.length;i++){
			if(json.data[i].name==name){
				return json.data[i].value;
			}
		}
		return null;
	}
	function getFileAll(name){
		for(var i=0;i<json.data.length;i++){
			if(json.data[i].name==name){
				return json.data[i];
			}
		}
		return null;
	}
	function clone(obj){
		var o,i,j,k;
		if(typeof(obj)!="object" || obj===null)return obj;
		if(obj instanceof(Array))
		{
			o=[];
			i=0;j=obj.length;
			for(;i<j;i++)
			{
				if(typeof(obj[i])=="object" && obj[i]!=null)
				{
					o[i]=arguments.callee(obj[i]);
				}
				else
				{
					o[i]=obj[i];
				}
			}
		}
		else
		{
			o={};
			for(i in obj)
			{
				if(typeof(obj[i])=="object" && obj[i]!=null)
				{
					o[i]=arguments.callee(obj[i]);
				}
				else
				{
					o[i]=obj[i];
				}
			}
		}
	 
		return o;
	}
	//初始化
	function init(){
		getDSList();
	}
	init();
</script>	
</body>
</html>