tree.html 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572
  1. {% extends "layout.html" %}
  2. {% block title %}生物遗传图谱 - 家谱管理系统{% endblock %}
  3. {% block extra_css %}
  4. <style>
  5. #tree-container {
  6. width: 100%;
  7. height: 700px;
  8. background: white;
  9. border: 1px solid #e9ecef;
  10. border-radius: 8px;
  11. margin-top: 10px;
  12. box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
  13. position: relative;
  14. overflow: auto;
  15. scroll-behavior: smooth;
  16. }
  17. #tree-container::-webkit-scrollbar {
  18. width: 8px;
  19. height: 8px;
  20. }
  21. #tree-container::-webkit-scrollbar-track {
  22. background: #f1f1f1;
  23. border-radius: 4px;
  24. }
  25. #tree-container::-webkit-scrollbar-thumb {
  26. background: #c1c1c1;
  27. border-radius: 4px;
  28. }
  29. #tree-container::-webkit-scrollbar-thumb:hover {
  30. background: #a1a1a1;
  31. }
  32. .node rect, .node circle {
  33. stroke-width: 2px;
  34. filter: drop-shadow(0 2px 4px rgba(0,0,0,0.1));
  35. }
  36. .node text { font: 13px 'Microsoft YaHei', sans-serif; }
  37. .node .node-name {
  38. font-size: 13px;
  39. font-weight: 500;
  40. fill: #334155;
  41. stroke: #fff;
  42. stroke-width: 4px;
  43. paint-order: stroke;
  44. stroke-linejoin: round;
  45. }
  46. /* 样图一致:较粗的细实线、浅灰蓝色,显得专业 */
  47. .link { fill: none; stroke: #94A3B8; stroke-width: 2px; stroke-linejoin: round; }
  48. /* 关系标签文字,取消白色粗描边,因为已有胶囊形背景 */
  49. .link-label { font-size: 11px; fill: #64748B; font-weight: 500; }
  50. .link-label-sibling { fill: #64748B; }
  51. /* 男女形状与颜色区分:男性方形(蓝),女性圆形(粉红),添加轻微圆角与投影 */
  52. .node-male rect { stroke: #3B82F6; fill: #EFF6FF; rx: 8px; ry: 8px; }
  53. .node-female circle { stroke: #EC4899; fill: #FDF2F8; }
  54. /* 未知性别默认 */
  55. .node-leaf circle, .node-internal circle { stroke: #94A3B8; fill: #F8FAFC; }
  56. .node-male circle { stroke: none; fill: none; } /* 清除可能的干扰 */
  57. /* 样图一致:全部细实线 */
  58. .link-parent-child { stroke: #333; stroke-dasharray: none; }
  59. .link-spouse { stroke: #333; stroke-dasharray: none; stroke-width: 1.2px; }
  60. .link-sibling { stroke: #333; stroke-dasharray: none; stroke-width: 1.2px; }
  61. /* 右键菜单样式 */
  62. .context-menu {
  63. position: absolute;
  64. display: none;
  65. background: white;
  66. border: 1px solid #ccc;
  67. box-shadow: 2px 2px 10px rgba(0,0,0,0.2);
  68. z-index: 1000;
  69. border-radius: 4px;
  70. padding: 5px 0;
  71. min-width: 120px;
  72. }
  73. .context-menu-item {
  74. padding: 8px 15px;
  75. cursor: pointer;
  76. font-size: 14px;
  77. color: #333;
  78. }
  79. .context-menu-item:hover {
  80. background-color: #f8f9fa;
  81. color: #0d6efd;
  82. }
  83. .context-menu-item i {
  84. margin-right: 8px;
  85. }
  86. </style>
  87. {% endblock %}
  88. {% block content %}
  89. <div class="d-flex justify-content-between align-items-center mb-3">
  90. <h2><i class="bi bi-diagram-3"></i> 家谱关系树状图</h2>
  91. <div>
  92. <a href="{{ url_for('tree_classic') }}" class="btn btn-outline-primary" target="_blank">
  93. <i class="bi bi-printer"></i> 导出传统吊线图
  94. </a>
  95. </div>
  96. </div>
  97. <div class="alert alert-light border small py-2">
  98. <i class="bi bi-info-circle me-1"></i> 提示:图中按生物遗传图谱格式展示。支持拖拽建立关系,右键点击成员可查看、编辑或新增。
  99. </div>
  100. <div id="tree-container">
  101. <!-- 右键菜单 -->
  102. <div id="contextMenu" class="context-menu">
  103. <div class="context-menu-item" onclick="menuAction('detail')"><i class="bi bi-eye"></i>查看成员</div>
  104. <div class="context-menu-item" onclick="menuAction('edit')"><i class="bi bi-pencil"></i>编辑成员</div>
  105. <div class="context-menu-item" onclick="menuAction('add')"><i class="bi bi-plus-lg"></i>新增成员</div>
  106. </div>
  107. </div>
  108. <!-- 关系选择弹窗 -->
  109. <div class="modal fade" id="relationModal" tabindex="-1">
  110. <div class="modal-dialog modal-sm">
  111. <div class="modal-content">
  112. <div class="modal-header">
  113. <h5 class="modal-title">建立关系</h5>
  114. <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
  115. </div>
  116. <div class="modal-body">
  117. <p id="relationInfo" class="small mb-3"></p>
  118. <input type="hidden" id="sourceMid">
  119. <input type="hidden" id="targetMid">
  120. <div class="mb-3">
  121. <label class="form-label small">关系类型</label>
  122. <select id="relType" class="form-select form-select-sm">
  123. <option value="1">是其 儿子/女儿</option>
  124. <option value="10">是其 妻子/丈夫</option>
  125. <option value="11">是其 兄弟</option>
  126. <option value="12">是其 姐妹</option>
  127. </select>
  128. </div>
  129. <div class="mb-3">
  130. <label class="form-label small">子类型</label>
  131. <select id="subRelType" class="form-select form-select-sm">
  132. <option value="0">亲生/正妻</option>
  133. <option value="1">养子/女</option>
  134. <option value="2">过继</option>
  135. </select>
  136. </div>
  137. </div>
  138. <div class="modal-footer">
  139. <button type="button" class="btn btn-sm btn-secondary" data-bs-dismiss="modal">取消</button>
  140. <button type="button" class="btn btn-sm btn-primary" onclick="saveRelation()">保存关系</button>
  141. </div>
  142. </div>
  143. </div>
  144. </div>
  145. {% endblock %}
  146. {% block extra_js %}
  147. <!-- 优先使用本地 D3.js -->
  148. <script src="{{ url_for('static', filename='js/d3.min.js') }}"></script>
  149. <!-- fallback to CDN if local fails -->
  150. <script>
  151. if (typeof d3 === 'undefined') {
  152. var script = document.createElement('script');
  153. script.src = 'https://cdn.jsdelivr.net/npm/d3@7.8.5/dist/d3.min.js';
  154. script.onload = function() {
  155. if (typeof d3 !== 'undefined') {
  156. loadTree();
  157. } else {
  158. var container = document.getElementById('tree-container');
  159. if (container) container.innerHTML = '<div class="h-100 d-flex align-items-center justify-content-center text-danger small">D3.js 未加载,请检查网络或稍后重试。</div>';
  160. }
  161. };
  162. script.onerror = function() {
  163. var container = document.getElementById('tree-container');
  164. if (container) container.innerHTML = '<div class="h-100 d-flex align-items-center justify-content-center text-danger small">D3.js 未加载,请检查网络或稍后重试。</div>';
  165. };
  166. document.head.appendChild(script);
  167. }
  168. </script>
  169. <script>
  170. (function() {
  171. if (typeof d3 === 'undefined') {
  172. // CDN will handle loading and initialization
  173. }
  174. })();
  175. let currentData = null;
  176. let dragSource = null;
  177. let dragTarget = null;
  178. let selectedMid = null; // 当前选中的成员 ID
  179. const relationModal = new bootstrap.Modal(document.getElementById('relationModal'));
  180. const contextMenu = document.getElementById('contextMenu');
  181. // 隐藏右键菜单
  182. window.addEventListener('click', () => {
  183. contextMenu.style.display = 'none';
  184. });
  185. // 处理菜单点击
  186. function menuAction(type) {
  187. if (!selectedMid && type !== 'add') return;
  188. switch(type) {
  189. case 'detail':
  190. window.location.href = `/manager/member_detail/${selectedMid}`;
  191. break;
  192. case 'edit':
  193. window.location.href = `/manager/edit_member/${selectedMid}`;
  194. break;
  195. case 'add':
  196. window.location.href = '/manager/add_member';
  197. break;
  198. }
  199. }
  200. // 获取数据并渲染
  201. function loadTree() {
  202. if (typeof d3 === 'undefined') return;
  203. fetch('/manager/api/tree_data')
  204. .then(response => response.json())
  205. .then(data => {
  206. currentData = data;
  207. renderTree(data);
  208. });
  209. }
  210. if (typeof d3 !== 'undefined') loadTree();
  211. function renderTree(data) {
  212. const container = document.getElementById('tree-container');
  213. container.innerHTML = '';
  214. container.appendChild(contextMenu);
  215. try {
  216. const { members, relations } = data;
  217. if (!members || members.length === 0) {
  218. container.innerHTML = '<div class="h-100 d-flex align-items-center justify-content-center text-muted">暂无成员数据,无法生成关系图。</div>';
  219. return;
  220. }
  221. const nodes = members.map(m => ({ id: m.id, name: m.name, simplified_name: m.simplified_name, sex: m.sex }));
  222. const hierarchicalLinks = relations.filter(r => r.relation_type === 1 || r.relation_type === 2)
  223. .map(r => ({ source: r.parent_mid, target: r.child_mid }));
  224. const spouseLinks = relations.filter(r => r.relation_type === 10);
  225. const otherLinks = relations.filter(r => r.relation_type >= 11);
  226. const childIds = new Set(hierarchicalLinks.map(l => l.target));
  227. const allSpouseIds = new Set(spouseLinks.map(l => l.child_mid));
  228. const roots = nodes.filter(n => !childIds.has(n.id) && !allSpouseIds.has(n.id));
  229. function buildHierarchy(nodeId, processedNodes = new Set()) {
  230. const node = nodes.find(n => n.id === nodeId);
  231. if (!node || processedNodes.has(nodeId)) return null;
  232. processedNodes.add(nodeId);
  233. const children = hierarchicalLinks.filter(l => l.source === nodeId)
  234. .map(l => buildHierarchy(l.target, processedNodes))
  235. .filter(c => c !== null);
  236. const spouses = spouseLinks.filter(l => l.parent_mid === nodeId)
  237. .map(l => {
  238. const spouseId = l.child_mid;
  239. if (!childIds.has(spouseId)) {
  240. const sNode = nodes.find(n => n.id === spouseId);
  241. if (sNode && !processedNodes.has(spouseId)) {
  242. processedNodes.add(spouseId);
  243. return { id: sNode.id, name: sNode.name, simplified_name: sNode.simplified_name, sex: sNode.sex, isSpouseNode: true, children: [] };
  244. }
  245. }
  246. return null;
  247. })
  248. .filter(s => s !== null);
  249. return { id: node.id, name: node.name, simplified_name: node.simplified_name, sex: node.sex, children: spouses.concat(children) };
  250. }
  251. let treeData;
  252. if (roots.length > 1) {
  253. treeData = { name: "家谱根源", children: roots.map(root => buildHierarchy(root.id)).filter(r => r !== null) };
  254. } else if (roots.length === 1) {
  255. treeData = buildHierarchy(roots[0].id);
  256. } else {
  257. treeData = buildHierarchy(nodes[0].id);
  258. }
  259. const margin = {top: 80, right: 60, bottom: 80, left: 60};
  260. const containerWidth = document.getElementById('tree-container').offsetWidth;
  261. let rootNode = d3.hierarchy(treeData, d => (d && d.children) || []);
  262. // 动态调整间距,保证节点绝对不重叠,长辈/同辈/配偶使用固定基础间距
  263. const nodeWidth = 90; // 基础宽度
  264. const nodeHeight = 260; // 基础高度,调大以避免上下层重叠
  265. const treemap = d3.tree().nodeSize([nodeWidth, nodeHeight]).separation((a, b) => {
  266. return a.parent === b.parent ? 1.4 : 2.0;
  267. });
  268. let nodesHier = treemap(rootNode);
  269. // 配偶固定在“下层半级”:纵向放到两代中间;横向围绕本人轻度展开
  270. const spouseHalfLevelOffsetY = Math.round(nodeHeight * 0.5); // 半级
  271. const spouseSpreadX = 110; // 多配偶时的横向间距
  272. nodesHier.descendants().forEach(parent => {
  273. const spouses = (parent.children || []).filter(c => c.data && c.data.isSpouseNode);
  274. if (spouses.length === 0) return;
  275. spouses.forEach((spouse, idx) => {
  276. const order = idx - (spouses.length - 1) / 2;
  277. spouse.x = parent.x + order * spouseSpreadX;
  278. spouse.y = parent.y + spouseHalfLevelOffsetY;
  279. });
  280. });
  281. // 计算边界以动态设置 SVG 宽高,实现自动滚动不挤压
  282. let x0 = Infinity;
  283. let x1 = -Infinity;
  284. let y1 = -Infinity;
  285. nodesHier.descendants().forEach(d => {
  286. if (d.x < x0) x0 = d.x;
  287. if (d.x > x1) x1 = d.x;
  288. if (d.y > y1) y1 = d.y;
  289. });
  290. // 增加更宽的边距以确保左侧不被切断
  291. const minWidth = containerWidth;
  292. const calculatedWidth = x1 - x0 + margin.left + margin.right + 400; // 增加额外的宽度缓冲
  293. const svgWidth = Math.max(minWidth, calculatedWidth);
  294. const svgHeight = Math.max(600, y1 + margin.top + margin.bottom);
  295. // 修正偏移量计算:确保最小的 x0 节点完全在可视区域内(加上足够的左边距)
  296. // 这样即便是负的很大,也会被完整平移到正数区域
  297. const extraLeftMargin = 200; // 增加更多左侧空间
  298. let offsetX = margin.left - x0 + extraLeftMargin; // 强制将最左侧节点右移确保文字不被截断
  299. // 确保offsetX至少为margin.left,防止内容被左侧菜单遮挡
  300. offsetX = Math.max(offsetX, margin.left + 50);
  301. const svg = d3.select("#tree-container").append("svg")
  302. .attr("width", svgWidth)
  303. .attr("height", svgHeight)
  304. .append("g")
  305. .attr("transform", `translate(${offsetX},${margin.top})`);
  306. // 节点圆圈半径(连线与节点共用),调大让图谱更清晰大气
  307. const circleR = 20;
  308. // 辅助函数:绘制精致的徽章式关系标签
  309. function addBadge(g, x, y, text) {
  310. const group = g.append("g").attr("transform", `translate(${x},${y})`);
  311. group.append("rect")
  312. .attr("x", -20).attr("y", -10)
  313. .attr("width", 40).attr("height", 20)
  314. .attr("rx", 10).attr("ry", 10) // 胶囊形状
  315. .attr("fill", "#fff")
  316. .attr("stroke", "#CBD5E1").attr("stroke-width", 1.2);
  317. group.append("text")
  318. .attr("class", "link-label")
  319. .attr("x", 0).attr("y", 0).attr("dy", "0.32em")
  320. .attr("text-anchor", "middle")
  321. .text(text);
  322. }
  323. // 连线:第二层连线设计(U型配偶线 + 亲子水平线)
  324. nodesHier.descendants().forEach(node => {
  325. if (!node.children || node.children.length === 0) return;
  326. const realChildren = (node.children || []).filter(c => c.data && !c.data.isSpouseNode);
  327. const spouses = (node.children || []).filter(c => c.data && c.data.isSpouseNode);
  328. // 配偶连线拐点:位于本人与配偶节点之间,匹配“下层半级”显示
  329. const hY = node.y + Math.round(spouseHalfLevelOffsetY * 0.55);
  330. const num = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : 0);
  331. // 夫妻关系:倒U型连线(主节点向下,然后横向连到配偶上面)
  332. if (spouses.length > 0) {
  333. const g = svg.append("g").attr("class", "link-group");
  334. spouses.forEach((spouse, idx) => {
  335. // 主节点向下,拐向配偶,再向下连接配偶顶部 (spouse.y - circleR)
  336. const pathD = `M${num(node.x)},${num(node.y + circleR)}
  337. L${num(node.x)},${num(hY)}
  338. L${num(spouse.x)},${num(hY)}
  339. L${num(spouse.x)},${num(spouse.y - circleR)}`;
  340. g.append("path").attr("class", "link link-spouse").attr("d", pathD);
  341. if (idx === 0) addBadge(g, (node.x + spouse.x) / 2, hY + 14, "配偶");
  342. });
  343. }
  344. if (realChildren.length === 0) return;
  345. const childrenY = realChildren[0].y;
  346. const minChildX = d3.min(realChildren, c => c.x);
  347. const maxChildX = d3.max(realChildren, c => c.x);
  348. // 如果有配偶,子代主线从配偶连线的中间引出,否则从自己直接引出
  349. const startX = spouses.length > 0 ? (node.x + spouses[0].x) / 2 : node.x;
  350. const startY = spouses.length > 0 ? hY : node.y + circleR;
  351. // 将子女横线也相应地下移一些,避免和配偶长名字重叠
  352. const sibsY = childrenY - 60;
  353. const g = svg.append("g").attr("class", "link-group");
  354. const hLineLeft = Math.min(minChildX, startX);
  355. const hLineRight = Math.max(maxChildX, startX);
  356. // 主线:从配偶U型线中点连到子女水平线
  357. let pathD = `M${num(startX)},${num(startY)} L${num(startX)},${num(sibsY)} M${num(hLineLeft)},${num(sibsY)} L${num(hLineRight)},${num(sibsY)}`;
  358. // 短竖线:连到每个子女顶部
  359. realChildren.forEach(child => {
  360. pathD += ` M${num(child.x)},${num(sibsY)} L${num(child.x)},${num(child.y) - circleR}`;
  361. });
  362. g.append("path").attr("class", "link link-parent-child").attr("d", pathD);
  363. // 去除家谱根源到第一层的关系展示;下层亲子关系标记使用徽章式标签放在短竖线上,一目了然
  364. const isRootToFirst = !node.parent || !(node.data && node.data.id);
  365. if (!isRootToFirst && node.data) {
  366. realChildren.forEach(child => {
  367. const pSex = node.data.sex;
  368. const cSex = child.data && child.data.sex;
  369. let label = "亲子";
  370. if (pSex === 1) label = cSex === 1 ? "父子" : "父女";
  371. else if (pSex === 2) label = cSex === 1 ? "母子" : "母女";
  372. const childLinkMidY = (sibsY + child.y - circleR) / 2;
  373. addBadge(g, child.x, childLinkMidY, label);
  374. });
  375. }
  376. });
  377. // 兄弟/姐妹:上方 U 型连线避免穿透节点
  378. const idToPos = {};
  379. nodesHier.descendants().forEach(d => { if (d.data.id) idToPos[d.data.id] = { x: d.x, y: d.y }; });
  380. otherLinks.forEach(rel => {
  381. const s = idToPos[rel.parent_mid], t = idToPos[rel.child_mid];
  382. if (s && t) {
  383. const x1 = Math.min(s.x, t.x), x2 = Math.max(s.x, t.x);
  384. const y = s.y - circleR - 25; // 兄弟线在节点上方
  385. const g = svg.append("g");
  386. const pathD = `M${x1},${s.y - circleR} L${x1},${y} L${x2},${y} L${x2},${t.y - circleR}`;
  387. g.append("path").attr("class", "link link-sibling").attr("d", pathD);
  388. addBadge(g, (x1 + x2) / 2, y, rel.relation_type === 11 ? "兄弟" : "姐妹");
  389. }
  390. });
  391. const node = svg.selectAll(".node")
  392. .data(nodesHier.descendants())
  393. .enter().append("g")
  394. .attr("class", d => {
  395. let cls = "node" + (d.children ? " node--internal" : " node--leaf");
  396. if (d.data.sex === 1) cls += " node-male";
  397. else if (d.data.sex === 2) cls += " node-female";
  398. return cls;
  399. })
  400. .attr("transform", d => `translate(${d.x},${d.y})`)
  401. .on("contextmenu", function(event, d) {
  402. if (!d.data.id) return;
  403. event.preventDefault();
  404. selectedMid = d.data.id;
  405. const containerRect = document.getElementById('tree-container').getBoundingClientRect();
  406. contextMenu.style.display = 'block';
  407. contextMenu.style.left = (event.clientX - containerRect.left) + 'px';
  408. contextMenu.style.top = (event.clientY - containerRect.top) + 'px';
  409. })
  410. .call(d3.drag()
  411. .on("start", dragstarted)
  412. .on("drag", dragged)
  413. .on("end", dragended));
  414. // 图形:男性方形,女性圆形,更符合生物遗传图谱
  415. node.each(function(d) {
  416. const el = d3.select(this);
  417. if (d.data.sex === 1) {
  418. el.append("rect")
  419. .attr("x", -circleR).attr("y", -circleR)
  420. .attr("width", circleR * 2).attr("height", circleR * 2)
  421. .style("cursor", "grab");
  422. } else {
  423. el.append("circle")
  424. .attr("r", circleR)
  425. .style("cursor", "grab");
  426. }
  427. });
  428. // 人名:往下移动更多,避免和长方形/圆形图形或者连线重叠
  429. const nameOffsetY = circleR + 25; // 增加间距
  430. const maxNameLen = 12; // 允许稍微长一点的文字
  431. function fullName(d) {
  432. if (!d.data) return '';
  433. return d.data.simplified_name ? `${d.data.name || ''} (${d.data.simplified_name})` : (d.data.name || '');
  434. }
  435. const nameGroup = node.append("g").attr("class", "node-name-wrap").attr("transform", "translate(0, " + nameOffsetY + ")");
  436. nameGroup.each(function(d) {
  437. const g = d3.select(this);
  438. const full = fullName(d);
  439. const disp = full.length <= maxNameLen ? full : full.slice(0, maxNameLen) + '…';
  440. // 姓名可能较长,我们这里做个简单的多行拆分显示或者让它有一个白色背景遮挡线
  441. // 这里为了简单不破坏原有结构,仅使用 text,但可以给一个白色的 stroke 做底或者调整 y 坐标
  442. const textNode = g.append("text")
  443. .attr("class", "node-name")
  444. .attr("x", 0).attr("y", 0)
  445. .attr("dy", "0.8em") // 使得文字基线往下靠,进一步远离图形
  446. .attr("text-anchor", "middle")
  447. .style("pointer-events", "all")
  448. .style("cursor", "default")
  449. .text(disp);
  450. if (full.length > maxNameLen) {
  451. textNode.append("title").text(full);
  452. }
  453. });
  454. function dragstarted(event, d) {
  455. if (!d.data.id) return;
  456. d3.select(this).raise().classed("active", true);
  457. d._currentX = d.x; d._currentY = d.y;
  458. dragSource = d.data;
  459. }
  460. function dragged(event, d) {
  461. d._currentX += event.dx; d._currentY += event.dy;
  462. d3.select(this).attr("transform", `translate(${d._currentX},${d._currentY})`);
  463. }
  464. function dragended(event, d) {
  465. d3.select(this).classed("active", false);
  466. const mouseX = event.sourceEvent.clientX, mouseY = event.sourceEvent.clientY;
  467. let foundNode = null;
  468. svg.selectAll(".node").each(function(nodeData) {
  469. if (!nodeData.data || nodeData.data.id === d.data.id || !nodeData.data.id) return;
  470. const rect = this.getBoundingClientRect();
  471. if (mouseX >= rect.left && mouseX <= rect.right && mouseY >= rect.top && mouseY <= rect.bottom) foundNode = nodeData.data;
  472. });
  473. if (foundNode && foundNode.id) {
  474. dragTarget = foundNode;
  475. document.getElementById('sourceMid').value = dragSource.id;
  476. document.getElementById('targetMid').value = dragTarget.id;
  477. document.getElementById('relationInfo').innerHTML = `确认将 <strong>${dragSource.name}</strong> 设定为 <strong>${dragTarget.name}</strong> 的关系人?`;
  478. relationModal.show();
  479. }
  480. setTimeout(() => { renderTree(currentData); }, 100);
  481. }
  482. } catch (err) {
  483. console.error('renderTree error:', err);
  484. container.innerHTML = '<div class="h-100 d-flex align-items-center justify-content-center text-danger small">关系图渲染出错,请刷新重试。<br>' + (err.message || '') + '</div>';
  485. }
  486. }
  487. function saveRelation() {
  488. const payload = {
  489. source_mid: document.getElementById('sourceMid').value,
  490. target_mid: document.getElementById('targetMid').value,
  491. relation_type: document.getElementById('relType').value,
  492. sub_relation_type: document.getElementById('subRelType').value
  493. };
  494. fetch('/manager/api/save_relation', {
  495. method: 'POST',
  496. headers: { 'Content-Type': 'application/json' },
  497. body: JSON.stringify(payload)
  498. }).then(res => res.json()).then(data => {
  499. if (data.success) { relationModal.hide(); loadTree(); }
  500. else { alert('保存失败: ' + data.message); }
  501. });
  502. }
  503. </script>
  504. {% endblock %}