add_member.html 121 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501
  1. {% extends "layout.html" %}
  2. {% block title %}{{ '编辑' if member else '录入' }}成员 - 家谱管理系统{% endblock %}
  3. {% block extra_css %}
  4. <style>
  5. .split-container { display: flex; height: calc(100vh - 100px); overflow: hidden; }
  6. .form-panel { flex: 1.2; padding: 20px; overflow-y: auto; border-right: 1px solid #dee2e6; }
  7. .image-panel { flex: 0.8; padding: 20px; background: #f8f9fa; display: flex; flex-direction: column; }
  8. .image-viewer { flex: 1; border: 1px solid #ccc; background: white; overflow: hidden; text-align: center; position: relative; }
  9. .image-viewer img { max-width: 100%; height: auto; transition: transform 0.2s, filter 0.2s; transform-origin: top left; cursor: grab; }
  10. .image-viewer img.dragging { cursor: grabbing; }
  11. /* 放大镜样式 */
  12. .magnifier-glass {
  13. position: absolute;
  14. border: 3px solid #000;
  15. border-radius: 50%;
  16. cursor: none;
  17. width: 150px;
  18. height: 150px;
  19. box-shadow: 0 0 10px rgba(0,0,0,0.5);
  20. display: none;
  21. z-index: 1000;
  22. background-repeat: no-repeat;
  23. background-color: white;
  24. pointer-events: none;
  25. }
  26. /* Image Viewer & Dragging */
  27. .image-viewer {
  28. flex: 1;
  29. border: 1px solid #ccc;
  30. background: #f0f0f0;
  31. overflow: hidden;
  32. text-align: center;
  33. position: relative;
  34. cursor: grab;
  35. user-select: none;
  36. }
  37. .image-viewer:active {
  38. cursor: grabbing;
  39. }
  40. .image-wrapper {
  41. display: inline-block;
  42. transition: transform 0.2s ease-out;
  43. transform-origin: center center;
  44. position: absolute;
  45. /* Initial centering will be handled by JS or CSS translate */
  46. top: 50%;
  47. left: 50%;
  48. transform: translate(-50%, -50%);
  49. }
  50. .image-wrapper img {
  51. max-width: 100%;
  52. max-height: 100vh;
  53. display: block;
  54. pointer-events: none;
  55. user-select: none;
  56. transition: filter 0.2s;
  57. }
  58. .image-toolbar {
  59. background: #e9ecef;
  60. padding: 5px 10px;
  61. border-bottom: 1px solid #dee2e6;
  62. display: flex;
  63. gap: 10px;
  64. align-items: center;
  65. flex-wrap: wrap;
  66. }
  67. .image-toolbar .btn-group-xs > .btn, .image-toolbar .btn-sm {
  68. padding: 0.25rem 0.5rem;
  69. font-size: 0.875rem;
  70. }
  71. .filter-controls { display: flex; align-items: center; gap: 5px; font-size: 0.8rem; }
  72. .filter-controls input[type=range] { width: 80px; }
  73. .page-nav { margin-bottom: 10px; display: flex; gap: 10px; align-items: center; }
  74. .section-title { border-left: 4px solid #0d6efd; padding-left: 10px; margin: 25px 0 15px; font-weight: bold; color: #333; }
  75. .father-lineage-hint {
  76. background-color: #f8f9fa;
  77. border-left: 4px solid #17a2b8;
  78. padding: 8px 12px;
  79. border-radius: 4px;
  80. font-size: 14px;
  81. margin-top: 8px;
  82. margin-bottom: 12px;
  83. }
  84. .father-lineage-hint .text-info {
  85. color: #17a2b8;
  86. }
  87. </style>
  88. {% endblock %}
  89. {% block content %}
  90. <div class="split-container">
  91. <!-- 左侧:录入/编辑表单 -->
  92. <div class="form-panel">
  93. <div class="card shadow-sm mb-4">
  94. <div class="card-header bg-primary text-white d-flex justify-content-between align-items-center">
  95. <h5 class="mb-0">{{ '编辑成员信息' if member else '录入新成员' }}</h5>
  96. <a href="{{ url_for('members') }}" class="btn btn-sm btn-light">返回列表</a>
  97. </div>
  98. <div class="card-body">
  99. <form method="POST">
  100. <input type="hidden" name="source_record_id" value="{{ source_record_id if source_record_id else (member.source_record_id if member and member.source_record_id else '') }}">
  101. <input type="hidden" name="source_index" value="">
  102. <div class="section-title">核心信息 (必填)</div>
  103. <div class="row g-3 mb-4">
  104. <div class="col-md-6">
  105. <label class="form-label">姓名(繁体) <span class="text-danger">*</span></label>
  106. <input type="text" name="name" id="nameInput" class="form-control" required value="{{ member.name if member else '' }}">
  107. <div id="nameCheckResult" class="mt-2"></div>
  108. </div>
  109. <div class="col-md-6">
  110. <label class="form-label">姓名(简体)</label>
  111. <input type="text" name="simplified_name" class="form-control" value="{{ member.simplified_name if member else '' }}">
  112. </div>
  113. <div class="col-md-6">
  114. <label class="form-label">性别 <span class="text-danger">*</span></label>
  115. <select name="sex" class="form-select" required>
  116. <option value="1" {{ 'selected' if member and member.sex == 1 else '' }}>男</option>
  117. <option value="2" {{ 'selected' if member and member.sex == 2 else '' }}>女</option>
  118. </select>
  119. </div>
  120. <div class="col-md-6">
  121. <label class="form-label">出生日期 <span class="text-danger">*</span></label>
  122. <div class="input-group has-validation">
  123. {% set birthday_val = member.birthday_date if member and member.birthday_date != '未知' else '' %}
  124. <input type="date" name="birthday" class="form-control" required value="{{ birthday_val }}" onchange="validateAge()">
  125. <div class="input-group-text bg-white">
  126. <input class="form-check-input mt-0" type="checkbox" id="birthdayUnknown" onchange="toggleBirthdayUnknown()" {{ 'checked' if member and member.birthday_date == '未知' else '' }}>
  127. <label class="form-check-label ms-1 small user-select-none" for="birthdayUnknown">不详</label>
  128. </div>
  129. <div class="invalid-feedback" id="ageFeedback"></div>
  130. </div>
  131. </div>
  132. <div class="col-md-8">
  133. <label class="form-label">世系世代</label>
  134. <div id="lineage-generations-container" class="d-flex flex-wrap align-items-center gap-2">
  135. {% if member and member.name_word_generation %}
  136. {% set generations = member.name_word_generation.split(';') %}
  137. {% for gen in generations %}
  138. {% if gen.strip() %}
  139. <span class="lineage-tag badge bg-primary bg-opacity-10 text-primary border border-primary border-opacity-25 px-3 py-2 rounded-pill d-inline-flex align-items-center" style="font-size: 0.85rem;">
  140. {{ gen.strip() }}
  141. <button type="button" class="btn-close ms-2 remove-lineage" style="font-size: 0.55rem; filter: none; opacity: 0.6;" aria-label="删除"></button>
  142. <input type="hidden" name="lineage_generations[]" value="{{ gen.strip() }}">
  143. </span>
  144. {% endif %}
  145. {% endfor %}
  146. {% endif %}
  147. <div id="lineage-input-form" class="d-none">
  148. <div class="input-group input-group-sm" style="width: 220px;">
  149. <input type="text" id="lineage-input" class="form-control" placeholder="如:衢州第二十九代" maxlength="20">
  150. <button type="button" id="confirm-lineage" class="btn btn-success"><i class="bi bi-check-lg"></i></button>
  151. <button type="button" id="cancel-lineage" class="btn btn-outline-secondary"><i class="bi bi-x-lg"></i></button>
  152. </div>
  153. </div>
  154. <button type="button" id="add-lineage" class="btn btn-outline-primary btn-sm rounded-pill px-3 py-1">
  155. <i class="bi bi-plus-lg me-1"></i>添加
  156. </button>
  157. </div>
  158. </div>
  159. <div class="col-md-4">
  160. <label class="form-label">堂内排行</label>
  161. <input type="text" name="family_rank" class="form-control" value="{{ member.family_rank if member else '' }}">
  162. </div>
  163. </div>
  164. <div class="section-title">状态信息</div>
  165. <div class="row g-3 mb-4">
  166. <div class="col-md-6">
  167. <label class="form-label">是否过世</label>
  168. <select name="is_pass_away" class="form-select">
  169. <option value="0" {{ 'selected' if member and member.is_pass_away == 0 else '' }}>健在</option>
  170. <option value="1" {{ 'selected' if member and member.is_pass_away == 1 else '' }}>已故</option>
  171. <option value="2" {{ 'selected' if member and member.is_pass_away == 2 else '' }}>未知</option>
  172. </select>
  173. </div>
  174. <div class="col-md-6">
  175. <label class="form-label">婚姻状况</label>
  176. <select name="marital_status" class="form-select">
  177. <option value="0" {{ 'selected' if member and member.marital_status == 0 else '' }}>未知</option>
  178. <option value="1" {{ 'selected' if member and member.marital_status == 1 else '' }}>未婚</option>
  179. <option value="2" {{ 'selected' if member and member.marital_status == 2 else '' }}>已婚</option>
  180. <option value="3" {{ 'selected' if member and member.marital_status == 3 else '' }}>离异/丧偶</option>
  181. </select>
  182. </div>
  183. </div>
  184. <div class="section-title">关系录入 (选择关联成员及关系)</div>
  185. <div class="row g-3 mb-4">
  186. <div class="col-md-5">
  187. <label class="form-label">关联成员</label>
  188. <div class="input-group">
  189. <input type="text" id="related-member-display" class="form-control" placeholder="点击选择关联成员" readonly value="{{ selected_member_name }}">
  190. <input type="hidden" name="related_mid" id="related_mid" value="{{ current_relation.parent_mid if current_relation else '' }}">
  191. <button type="button" class="btn btn-outline-primary" data-bs-toggle="modal" data-bs-target="#memberSelectModal">
  192. <i class="bi bi-search"></i>
  193. </button>
  194. </div>
  195. </div>
  196. <div class="col-md-4">
  197. <label class="form-label">关系类型</label>
  198. <select name="relation_type" class="form-select">
  199. <option value="">-- 请选择 --</option>
  200. <option value="1" {{ 'selected' if current_relation and current_relation.relation_type == 1 else '' }}>父子 (关联人为父)</option>
  201. <option value="2" {{ 'selected' if current_relation and current_relation.relation_type == 2 else '' }}>母子 (关联人为母)</option>
  202. <option value="10" {{ 'selected' if current_relation and current_relation.relation_type == 10 else '' }}>夫妻</option>
  203. <option value="11" {{ 'selected' if current_relation and current_relation.relation_type == 11 else '' }}>兄弟</option>
  204. <option value="12" {{ 'selected' if current_relation and current_relation.relation_type == 12 else '' }}>姐妹</option>
  205. </select>
  206. </div>
  207. <div class="col-md-3">
  208. <label class="form-label">子类型</label>
  209. <select name="sub_relation_type" class="form-select">
  210. <option value="0" {{ 'selected' if current_relation and current_relation.sub_relation_type == 0 else '' }}>亲生/正妻</option>
  211. <option value="1" {{ 'selected' if current_relation and current_relation.sub_relation_type == 1 else '' }}>养父</option>
  212. <option value="2" {{ 'selected' if current_relation and current_relation.sub_relation_type == 2 else '' }}>过继</option>
  213. <option value="10" {{ 'selected' if current_relation and current_relation.sub_relation_type == 10 else '' }}>妾</option>
  214. <option value="11" {{ 'selected' if current_relation and current_relation.sub_relation_type == 11 else '' }}>外室</option>
  215. </select>
  216. </div>
  217. </div>
  218. <div class="section-title">人员备注</div>
  219. <div class="row g-3 mb-4">
  220. <div class="col-md-12">
  221. <textarea name="notes" class="form-control" rows="2">{{ member.notes if member else '' }}</textarea>
  222. </div>
  223. </div>
  224. <!-- 悬浮的保存按钮,始终保持在一屏内或跟随页面底部 -->
  225. <div class="d-grid gap-2 mb-4 sticky-bottom bg-white py-2 border-top" style="z-index: 1020;">
  226. <button type="submit" class="btn btn-success btn-lg">
  227. <i class="bi bi-check-circle me-1"></i> {{ '保存修改' if member else '确认录入' }}
  228. </button>
  229. </div>
  230. <!-- 折叠的其他信息区 -->
  231. <div class="accordion" id="accordionExtraInfo">
  232. <div class="accordion-item border-0">
  233. <h2 class="accordion-header" id="headingExtra">
  234. <button class="accordion-button collapsed bg-light text-secondary rounded shadow-sm border" type="button" data-bs-toggle="collapse" data-bs-target="#collapseExtra" aria-expanded="false" aria-controls="collapseExtra">
  235. <i class="bi bi-three-dots me-2"></i> 展开更多其他信息(谱系详情、联络、履历等)
  236. </button>
  237. </h2>
  238. <div id="collapseExtra" class="accordion-collapse collapse" aria-labelledby="headingExtra" data-bs-parent="#accordionExtraInfo">
  239. <div class="accordion-body px-0 pt-3 pb-0">
  240. <div class="section-title mt-0">谱系详情</div>
  241. <div class="row g-3 mb-4">
  242. <div class="col-md-4">
  243. <label class="form-label">曾用名</label>
  244. <input type="text" name="former_name" class="form-control" value="{{ member.former_name if member else '' }}">
  245. </div>
  246. <div class="col-md-4">
  247. <label class="form-label">幼名/乳名</label>
  248. <input type="text" name="childhood_name" class="form-control" value="{{ member.childhood_name if member else '' }}">
  249. </div>
  250. <div class="col-md-4">
  251. <label class="form-label">字辈</label>
  252. <input type="text" name="name_word" class="form-control" value="{{ member.name_word if member else '' }}">
  253. </div>
  254. <div class="col-md-6">
  255. <label class="form-label">名号/封号</label>
  256. <input type="text" name="name_title" class="form-control" value="{{ member.name_title if member else '' }}">
  257. </div>
  258. <div class="col-md-6">
  259. <label class="form-label">分房/堂号</label>
  260. <input type="text" name="branch_family_hall" class="form-control" value="{{ member.branch_family_hall if member else '' }}">
  261. </div>
  262. <div class="col-md-6">
  263. <label class="form-label">聚居地</label>
  264. <input type="text" name="cluster_place" class="form-control" value="{{ member.cluster_place if member else '' }}">
  265. </div>
  266. </div>
  267. <div class="section-title">联络信息</div>
  268. <div class="row g-3 mb-4">
  269. <div class="col-md-4">
  270. <label class="form-label">民族</label>
  271. <input type="text" name="nation" class="form-control" value="{{ member.nation if member else '' }}">
  272. </div>
  273. <div class="col-md-4">
  274. <label class="form-label">手机号</label>
  275. <input type="text" name="phone" class="form-control" value="{{ member.phone if member else '' }}">
  276. </div>
  277. <div class="col-md-4">
  278. <label class="form-label">微信号</label>
  279. <input type="text" name="wechat_account" class="form-control" value="{{ member.wechat_account if member else '' }}">
  280. </div>
  281. <div class="col-md-12">
  282. <label class="form-label">现居住址</label>
  283. <input type="text" name="residential_address" class="form-control" value="{{ member.residential_address if member else '' }}">
  284. </div>
  285. </div>
  286. <div class="section-title">个人履历</div>
  287. <div class="row g-3 mb-2">
  288. <div class="col-md-6">
  289. <label class="form-label">职业</label>
  290. <textarea name="occupation" class="form-control" rows="2">{{ member.occupation if member else '' }}</textarea>
  291. </div>
  292. <div class="col-md-6">
  293. <label class="form-label">教育背景</label>
  294. <textarea name="educational" class="form-control" rows="2">{{ member.educational if member else '' }}</textarea>
  295. </div>
  296. <div class="col-md-12">
  297. <label class="form-label">标签</label>
  298. <input type="text" name="tags" class="form-control" placeholder="例如:抗战老兵, 教师 (用逗号分隔)" value="{{ member.tags if member else '' }}">
  299. </div>
  300. <div class="col-md-12">
  301. <label class="form-label">个人成就</label>
  302. <textarea name="personal_achievements" class="form-control" rows="3">{{ member.personal_achievements if member else '' }}</textarea>
  303. </div>
  304. </div>
  305. </div>
  306. </div>
  307. </div>
  308. </div>
  309. </form>
  310. </div>
  311. </div>
  312. </div>
  313. <!-- AI 推理日志及结果面板 -->
  314. <div id="aiLogPanel" class="position-fixed bottom-0 end-0 p-3 bg-dark text-white shadow"
  315. style="display: none; width: 450px; max-height: 85vh; border-radius: 8px 0 0 0; z-index: 1050; opacity: 0.95; overflow-y: auto;">
  316. <!-- 吸顶头部与当前选中详情 -->
  317. <div class="sticky-top bg-dark pb-2" style="z-index: 1060; margin-top: -1rem; padding-top: 1rem; border-bottom: 1px solid #444;">
  318. <div class="d-flex justify-content-between align-items-center mb-2 pb-1">
  319. <span class="fw-bold"><i class="bi bi-robot"></i> AI 识别助手</span>
  320. <button class="btn btn-sm btn-outline-light py-0" onclick="closeAiLog()">×</button>
  321. </div>
  322. <!-- 当前选中详情 -->
  323. <div id="aiCurrentDetail" class="mt-2 p-2 bg-secondary bg-opacity-25 rounded border border-info shadow-sm" style="display:none; max-height: 250px; overflow-y: auto;">
  324. <div class="d-flex justify-content-between align-items-center mb-2 border-bottom border-secondary pb-1">
  325. <strong class="text-info"><i class="bi bi-info-circle"></i> 当前填充详情</strong>
  326. <button class="btn btn-sm btn-link text-muted py-0 text-decoration-none" onclick="document.getElementById('aiCurrentDetail').style.display='none'">×</button>
  327. </div>
  328. <div id="aiDetailContent" class="small text-light" style="word-break: break-all;"></div>
  329. </div>
  330. </div>
  331. <!-- 推理过程 -->
  332. <div class="mb-3 mt-3">
  333. <button class="btn btn-sm btn-link text-decoration-none text-light p-0 mb-1 d-flex align-items-center" type="button" data-bs-toggle="collapse" data-bs-target="#collapseReasoning">
  334. <i class="bi bi-cpu me-1"></i> 推理过程 <span class="badge bg-secondary ms-2" id="reasoningStatus">进行中...</span>
  335. </button>
  336. <div class="collapse show" id="collapseReasoning">
  337. <pre id="aiLogContent" class="text-success small mb-0 p-2 bg-black rounded border border-secondary" style="max-height: 200px; overflow-y: auto; white-space: pre-wrap; font-family: monospace; font-size: 0.8rem;"></pre>
  338. </div>
  339. </div>
  340. <!-- 识别结果列表 -->
  341. <div id="aiResultSection" style="display: none;">
  342. <div class="d-flex justify-content-between align-items-center mb-2">
  343. <h6 class="mb-0 text-info"><i class="bi bi-check-circle"></i> 识别结果 (<span id="resultCount">0</span>)</h6>
  344. <span class="small text-muted">点击下方条目填充</span>
  345. </div>
  346. <div id="aiResultList" class="d-flex flex-column gap-2">
  347. <!-- 结果项将动态插入 -->
  348. </div>
  349. </div>
  350. </div>
  351. <!-- 右侧:图片参考 -->
  352. <div class="image-panel">
  353. <div class="page-nav">
  354. <label class="fw-bold">扫描件参考:</label>
  355. <button id="aiBtn" onclick="recognizeImage()" class="btn btn-sm btn-info text-white ms-2 me-2">
  356. <i class="bi bi-magic"></i> AI 识别
  357. </button>
  358. <input type="number" id="pageInput" class="form-control form-control-sm" style="width: 70px;" placeholder="页码">
  359. <button onclick="gotoPage()" class="btn btn-sm btn-primary">跳转</button>
  360. <div class="ms-auto small text-muted">
  361. 当前: <span id="currentPage">1</span> / <span id="totalPages">{{ images|length }}</span>
  362. </div>
  363. </div>
  364. <div class="mb-2 small text-muted" id="imageMetadata" style="display: none;">
  365. <span class="me-2"><i class="bi bi-journal-text"></i> 版本名称: <span id="metaVersion">-</span></span>
  366. <span class="me-2"><i class="bi bi-archive"></i> 版本来源: <span id="metaSource">-</span></span>
  367. <span><i class="bi bi-person"></i> 提供人: <span id="metaPerson">-</span></span>
  368. </div>
  369. <div class="image-toolbar rounded-top">
  370. <div class="btn-group btn-group-sm">
  371. <button type="button" class="btn btn-outline-secondary" onclick="rotateImage(-90)" title="左旋90°"><i class="bi bi-arrow-counterclockwise"></i></button>
  372. <button type="button" class="btn btn-outline-secondary" onclick="rotateImage(90)" title="右旋90°"><i class="bi bi-arrow-clockwise"></i></button>
  373. </div>
  374. <div class="filter-controls border-start border-end px-2 mx-1">
  375. <i class="bi bi-brightness-high" title="亮度"></i>
  376. <input type="range" min="50" max="150" value="100" oninput="updateImageFilter()" id="brightnessRange">
  377. <i class="bi bi-circle-half ms-2" title="对比度"></i>
  378. <input type="range" min="50" max="200" value="100" oninput="updateImageFilter()" id="contrastRange">
  379. <button class="btn btn-link btn-sm text-decoration-none py-0" onclick="resetFilters()">重置</button>
  380. </div>
  381. <div class="form-check form-switch ms-auto mb-0" title="开启后鼠标悬停图片可局部放大">
  382. <input class="form-check-input" type="checkbox" id="magnifierSwitch">
  383. <label class="form-check-label small" for="magnifierSwitch">🔍 放大镜</label>
  384. </div>
  385. </div>
  386. <div class="image-viewer shadow-inner" id="viewer">
  387. <div id="magnifier" class="magnifier-glass"></div>
  388. <div id="imageWrapper" class="image-wrapper">
  389. {% if images %}
  390. <img id="refImage" src="{{ images[0].oss_url }}" alt="家谱图片" draggable="false">
  391. {% else %}
  392. <div class="mt-5 text-muted">
  393. <i class="bi bi-image fs-1 d-block mb-2"></i>
  394. 暂无上传的家谱图片
  395. </div>
  396. {% endif %}
  397. </div>
  398. </div>
  399. <div class="mt-2 d-flex justify-content-between">
  400. <button onclick="prevImage()" class="btn btn-sm btn-outline-secondary">上一张</button>
  401. <button onclick="nextImage()" class="btn btn-sm btn-outline-secondary">下一张</button>
  402. </div>
  403. </div>
  404. <!-- 成员选择弹窗 -->
  405. <div class="modal fade" id="memberSelectModal" tabindex="-1" aria-hidden="true">
  406. <div class="modal-dialog modal-lg">
  407. <div class="modal-content border-0 shadow-lg">
  408. <div class="modal-header bg-primary text-white">
  409. <h5 class="modal-title"><i class="bi bi-people me-2"></i>选择关联成员</h5>
  410. <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
  411. </div>
  412. <div class="modal-body">
  413. <div class="mb-4">
  414. <div class="input-group">
  415. <input type="text" id="member-search" class="form-control" placeholder="搜索成员姓名(支持繁体和简体)">
  416. <button type="button" class="btn btn-primary" onclick="searchMembers()">
  417. <i class="bi bi-search"></i> 搜索
  418. </button>
  419. </div>
  420. </div>
  421. <div id="member-list" class="list-group mb-4 max-h-96 overflow-y-auto">
  422. <!-- 成员列表将通过JavaScript动态生成 -->
  423. </div>
  424. <div class="d-flex justify-content-between align-items-center">
  425. <div class="text-muted small">共 <span id="total-members">0</span> 个成员</div>
  426. <nav>
  427. <ul class="pagination pagination-sm" style="max-width: 300px; overflow-x: auto; padding: 5px;">
  428. <li class="page-item disabled">
  429. <a class="page-link" href="#" onclick="changePage(0)">&laquo;</a>
  430. </li>
  431. <li class="page-item active">
  432. <a class="page-link" href="#" onclick="changePage(1)">1</a>
  433. </li>
  434. <li class="page-item">
  435. <a class="page-link" href="#" onclick="changePage(2)">&raquo;</a>
  436. </li>
  437. </ul>
  438. </nav>
  439. </div>
  440. </div>
  441. <div class="modal-footer">
  442. <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
  443. </div>
  444. </div>
  445. </div>
  446. </div>
  447. </div>
  448. {% endblock %}
  449. {% block extra_js %}
  450. <script>
  451. let tomSelectInstance = null;
  452. let currentPage = 1;
  453. let totalPages = 1;
  454. let totalMembers = 0;
  455. let membersData = [];
  456. function toggleBirthdayUnknown() {
  457. const cb = document.getElementById('birthdayUnknown');
  458. const input = document.querySelector('input[name="birthday"]');
  459. if (!cb || !input) return;
  460. if (cb.checked) {
  461. input.value = '';
  462. input.disabled = true;
  463. input.required = false;
  464. input.classList.remove('is-invalid');
  465. const fb = document.getElementById('ageFeedback');
  466. if(fb) fb.textContent = '';
  467. } else {
  468. input.disabled = false;
  469. input.required = true;
  470. }
  471. }
  472. function validateAge() {
  473. const cb = document.getElementById('birthdayUnknown');
  474. if (cb && cb.checked) return;
  475. const birthdayInput = document.querySelector('input[name="birthday"]');
  476. const relatedSelect = document.querySelector('select[name="related_mid"]');
  477. const relationType = document.querySelector('select[name="relation_type"]');
  478. const feedback = document.getElementById('ageFeedback');
  479. if (!birthdayInput.value || !relatedSelect.value) {
  480. birthdayInput.classList.remove('is-invalid');
  481. return;
  482. }
  483. // Only check for Parent-Child relations (1: Father, 2: Mother)
  484. if (relationType.value !== '1' && relationType.value !== '2') return;
  485. // We need the parent's birthday. This is tricky as we only have the ID.
  486. // Option 1: Store parent birthdays in the select option dataset (easiest)
  487. // Option 2: Async fetch.
  488. const selectedOption = relatedSelect.options[relatedSelect.selectedIndex];
  489. const parentBirthdayTs = parseInt(selectedOption.dataset.birthday || '0');
  490. if (parentBirthdayTs > 0) {
  491. const childBirthday = new Date(birthdayInput.value).getTime() / 1000;
  492. if (childBirthday < parentBirthdayTs) {
  493. birthdayInput.classList.add('is-invalid');
  494. feedback.textContent = '警告:子女出生日期早于父母,请核对!';
  495. } else if (childBirthday - parentBirthdayTs < 12 * 365 * 24 * 3600) {
  496. // Warning if age gap < 12 years
  497. birthdayInput.classList.add('is-invalid');
  498. feedback.textContent = '警告:父母与子女年龄差小于12岁,请核对!';
  499. } else {
  500. birthdayInput.classList.remove('is-invalid');
  501. }
  502. }
  503. }
  504. // Call validation when relation changes too
  505. document.addEventListener('DOMContentLoaded', () => {
  506. const relatedSelect = document.querySelector('select[name="related_mid"]');
  507. if (relatedSelect) {
  508. relatedSelect.addEventListener('change', validateAge);
  509. if (typeof TomSelect !== 'undefined') {
  510. tomSelectInstance = new TomSelect(relatedSelect, {
  511. create: false,
  512. sortField: null,
  513. searchField: ['text'],
  514. render: {
  515. no_results: function(data, escape) {
  516. return '<div class="no-results">未找到匹配项</div>';
  517. }
  518. }
  519. });
  520. }
  521. }
  522. // Initialize birthday unknown state
  523. toggleBirthdayUnknown();
  524. });
  525. const images = [
  526. {% for img in images %}
  527. {
  528. id: {{ img.id }},
  529. url: "{{ img.oss_url }}",
  530. page: {{ img.page_number or 0 }},
  531. ai_status: {{ img.ai_status or 0 }},
  532. ai_content: {{ img.ai_content | tojson | safe if img.ai_content else 'null' }},
  533. genealogy_version: "{{ img.genealogy_version or '' }}",
  534. genealogy_source: "{{ img.genealogy_source or '' }}",
  535. upload_person: "{{ img.upload_person or '' }}"
  536. },
  537. {% endfor %}
  538. ];
  539. let currentIndex = 0;
  540. // 初始化时根据source_record_id设置正确的扫描件
  541. {% if source_record_id %}
  542. // 在模板渲染时直接设置currentIndex
  543. currentIndex = images.findIndex(img => img.id == {{ source_record_id }});
  544. // 如果找不到,保持为0
  545. if (currentIndex === -1) {
  546. currentIndex = 0;
  547. }
  548. {% endif %}
  549. let currentParsedPeople = [];
  550. // Image State
  551. let imgRotation = 0;
  552. let imgBrightness = 100;
  553. let imgContrast = 100;
  554. // Dragging State
  555. let isDragging = false;
  556. let hasDragged = false;
  557. let startX = 0, startY = 0;
  558. let currentX = 0, currentY = 0; // Relative to center (offsets)
  559. // Zoom State
  560. let isZoomedIn = false;
  561. const ZOOM_LEVEL = 2.0;
  562. // Magnifier Logic
  563. const viewer = document.getElementById('viewer');
  564. const magnifier = document.getElementById('magnifier');
  565. const magnifierSwitch = document.getElementById('magnifierSwitch');
  566. const imageWrapper = document.getElementById('imageWrapper');
  567. // 页面加载完成后更新显示
  568. document.addEventListener('DOMContentLoaded', function() {
  569. // 调用updateDisplay函数显示正确的扫描件
  570. updateDisplay();
  571. });
  572. // Initialize Dragging and Zooming
  573. if (imageWrapper) {
  574. // Center initial position
  575. imageWrapper.style.left = '50%';
  576. imageWrapper.style.top = '50%';
  577. viewer.style.cursor = 'zoom-in';
  578. viewer.addEventListener('mousedown', (e) => {
  579. if (e.target.closest('.image-toolbar') || e.target.closest('.magnifier-glass')) return;
  580. isDragging = true;
  581. hasDragged = false;
  582. startX = e.clientX;
  583. startY = e.clientY;
  584. viewer.style.cursor = 'grabbing';
  585. e.preventDefault(); // Prevent text selection
  586. });
  587. window.addEventListener('mousemove', (e) => {
  588. if (!isDragging) return;
  589. const dx = e.clientX - startX;
  590. const dy = e.clientY - startY;
  591. // Threshold to consider it a drag
  592. if (Math.abs(dx) > 2 || Math.abs(dy) > 2) {
  593. hasDragged = true;
  594. }
  595. currentX += dx;
  596. currentY += dy;
  597. startX = e.clientX;
  598. startY = e.clientY;
  599. updateImageTransform();
  600. });
  601. window.addEventListener('mouseup', (e) => {
  602. if (isDragging) {
  603. isDragging = false;
  604. viewer.style.cursor = isZoomedIn ? 'grab' : 'zoom-in';
  605. // If it was a click (not a drag) and clicked inside the viewer
  606. if (!hasDragged && viewer.contains(e.target)) {
  607. toggleZoom();
  608. }
  609. }
  610. });
  611. }
  612. function toggleZoom() {
  613. isZoomedIn = !isZoomedIn;
  614. if (!isZoomedIn) {
  615. // Reset position when zooming out to center
  616. currentX = 0;
  617. currentY = 0;
  618. }
  619. updateImageTransform();
  620. // Update cursor immediately
  621. viewer.style.cursor = isZoomedIn ? 'grab' : 'zoom-in';
  622. }
  623. viewer.addEventListener('mousemove', function(e) {
  624. if (!magnifierSwitch.checked) {
  625. magnifier.style.display = 'none';
  626. return;
  627. }
  628. if (isDragging) {
  629. magnifier.style.display = 'none';
  630. return;
  631. }
  632. const img = document.getElementById('refImage');
  633. if (!img) return;
  634. // Calculate position relative to the image
  635. const rect = img.getBoundingClientRect();
  636. const x = e.clientX - rect.left;
  637. const y = e.clientY - rect.top;
  638. // Only show if inside image rect (approximate for rotated)
  639. if (x < 0 || x > rect.width || y < 0 || y > rect.height) {
  640. magnifier.style.display = 'none';
  641. return;
  642. }
  643. magnifier.style.display = 'block';
  644. // Position the glass near mouse
  645. const glassOffset = 20;
  646. const viewerRect = viewer.getBoundingClientRect();
  647. magnifier.style.left = (e.clientX - viewerRect.left + glassOffset) + 'px';
  648. magnifier.style.top = (e.clientY - viewerRect.top + glassOffset) + 'px';
  649. // Background logic (Zoom 2x)
  650. const zoom = 2.5;
  651. magnifier.style.backgroundImage = `url('${img.src}')`;
  652. magnifier.style.backgroundSize = `${rect.width * zoom}px ${rect.height * zoom}px`;
  653. // Simple version (imperfect for rotation)
  654. magnifier.style.backgroundPosition = `-${x * zoom - 75}px -${y * zoom - 75}px`;
  655. });
  656. // Image Manipulation
  657. function rotateImage(deg) {
  658. imgRotation = (imgRotation + deg) % 360;
  659. updateImageTransform();
  660. }
  661. function updateImageFilter() {
  662. imgBrightness = document.getElementById('brightnessRange').value;
  663. imgContrast = document.getElementById('contrastRange').value;
  664. applyImageFilters();
  665. }
  666. function resetFilters() {
  667. imgRotation = 0;
  668. imgBrightness = 100;
  669. imgContrast = 100;
  670. currentX = 0;
  671. currentY = 0;
  672. isZoomedIn = false;
  673. document.getElementById('brightnessRange').value = 100;
  674. document.getElementById('contrastRange').value = 100;
  675. updateImageTransform();
  676. applyImageFilters();
  677. }
  678. function updateImageTransform() {
  679. const wrapper = document.getElementById('imageWrapper');
  680. if (wrapper) {
  681. const scale = isZoomedIn ? ZOOM_LEVEL : 1;
  682. wrapper.style.transform = `translate(calc(-50% + ${currentX}px), calc(-50% + ${currentY}px)) rotate(${imgRotation}deg) scale(${scale})`;
  683. // Adjust cursor based on state
  684. if (!isDragging) {
  685. viewer.style.cursor = isZoomedIn ? 'grab' : 'zoom-in';
  686. }
  687. }
  688. }
  689. function applyImageFilters() {
  690. const img = document.getElementById('refImage');
  691. if (img) {
  692. img.style.filter = `brightness(${imgBrightness}%) contrast(${imgContrast}%)`;
  693. }
  694. }
  695. // Reuse applyImageStyles as alias for compatibility if called elsewhere
  696. function applyImageStyles() {
  697. updateImageTransform();
  698. applyImageFilters();
  699. }
  700. const fieldMapping = {
  701. name: '姓名(繁体)',
  702. simplified_name: '姓名(简体)',
  703. sex: '性别',
  704. birthday: '出生日期',
  705. father_name: '父亲姓名',
  706. spouse_name: '配偶姓名',
  707. generation: '堂内排行(代数)',
  708. name_word: '字辈',
  709. education: '学历/功名',
  710. title: '官职/称号',
  711. death_date: '逝世日期',
  712. note: '备注'
  713. };
  714. // --- Keyboard Shortcuts ---
  715. document.addEventListener('keydown', (e) => {
  716. // Ctrl/Cmd + Enter: Save
  717. if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') {
  718. e.preventDefault();
  719. const submitBtn = document.querySelector('form button[type="submit"]');
  720. if (submitBtn && !submitBtn.disabled) {
  721. submitBtn.click(); // Trigger form submit listener
  722. }
  723. }
  724. // Ctrl/Cmd + Right Arrow: Next Image
  725. if ((e.ctrlKey || e.metaKey) && e.key === 'ArrowRight') {
  726. e.preventDefault();
  727. nextImage();
  728. }
  729. // Ctrl/Cmd + Left Arrow: Prev Image
  730. if ((e.ctrlKey || e.metaKey) && e.key === 'ArrowLeft') {
  731. e.preventDefault();
  732. prevImage();
  733. }
  734. // Alt + 1: Auto Fill First person in list
  735. if (e.altKey && e.key === '1') {
  736. e.preventDefault();
  737. // Try to find the first "fill" button that is not disabled/success
  738. const firstBtn = document.querySelector('button[id^="btn-fill-"]:not(.btn-success)');
  739. if (firstBtn) firstBtn.click();
  740. }
  741. });
  742. // --- AJAX Form Submission ---
  743. document.addEventListener('DOMContentLoaded', () => {
  744. const form = document.querySelector('form');
  745. form.addEventListener('submit', async (e) => {
  746. e.preventDefault();
  747. // Collect form data
  748. const formData = new FormData(form);
  749. // Visual feedback on button
  750. const submitBtn = form.querySelector('button[type="submit"]');
  751. const originalBtnHtml = submitBtn.innerHTML;
  752. submitBtn.disabled = true;
  753. submitBtn.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> 保存中...';
  754. try {
  755. // Use form.action to support both add and edit URLs
  756. const targetUrl = form.action || window.location.href;
  757. const response = await fetch(targetUrl, {
  758. method: 'POST',
  759. body: formData,
  760. headers: {
  761. 'X-Requested-With': 'XMLHttpRequest'
  762. }
  763. });
  764. const result = await response.json();
  765. if (result.success) {
  766. // Success!
  767. // 1. Show a toast or small alert
  768. const toast = document.createElement('div');
  769. toast.className = 'position-fixed bottom-0 start-50 translate-middle-x mb-4 p-3 bg-success text-white rounded shadow';
  770. toast.style.zIndex = '2000';
  771. toast.innerHTML = `<i class="bi bi-check-circle me-2"></i> ${result.message}`;
  772. document.body.appendChild(toast);
  773. setTimeout(() => toast.remove(), 3000);
  774. // 2. Mark the AI list item as "Saved" if applicable
  775. if (window.lastFilledIndex !== undefined) {
  776. const btn = document.getElementById(`btn-fill-${window.lastFilledIndex}`);
  777. if (btn) {
  778. btn.className = 'btn btn-sm btn-success text-white ms-2 disabled';
  779. btn.innerHTML = '<i class="bi bi-check-lg"></i> 已录入';
  780. btn.onclick = null;
  781. }
  782. // Update local data state so it persists if we switch images/filters
  783. if (currentParsedPeople[window.lastFilledIndex]) {
  784. currentParsedPeople[window.lastFilledIndex].is_imported = true;
  785. currentParsedPeople[window.lastFilledIndex].imported_member_id = result.member_id;
  786. // Sync back to images array to persist across image switching
  787. if (images[currentIndex]) {
  788. images[currentIndex].ai_content = currentParsedPeople;
  789. }
  790. }
  791. }
  792. // 3. Clear form (reset to defaults) or keep some fields?
  793. // Usually for genealogy, Surname/Generation might be same, but let's clear for safety
  794. // Resetting form but keeping "related_mid" might be useful for siblings?
  795. // For now, simple reset.
  796. // --- Update Local Matches before resetting form ---
  797. // If we just saved a person, check if this person is the father/spouse of anyone else in the list
  798. // and update their matches so 'fillForm' will work for them.
  799. const savedName = formData.get('name'); // Traditional (Raw)
  800. const savedSimplifiedName = formData.get('simplified_name'); // Simplified (Cleaned)
  801. const savedId = result.member_id;
  802. const savedSex = formData.get('sex'); // 1: Male, 2: Female
  803. if (savedId) {
  804. currentParsedPeople.forEach(p => {
  805. if (!p.matches) p.matches = {};
  806. // Check Father Match
  807. // Try matching against Simplified Name (p.father_name is Simplified Cleaned)
  808. // Or fallback to savedName if p.father_name happened to be Traditional (rare but possible)
  809. if (p.father_name && (p.father_name === savedSimplifiedName || p.father_name === savedName)) {
  810. // Assume simple match logic here (usually father is male)
  811. if (savedSex === '1') {
  812. if (!p.matches.father) p.matches.father = [];
  813. // Add to matches if not exists
  814. if (!p.matches.father.find(m => m.id === savedId)) {
  815. p.matches.father.push({ id: savedId, name: savedName, sex: 1 }); // Mock DB object
  816. }
  817. }
  818. }
  819. // Check Spouse Match
  820. if (p.spouse_name && (p.spouse_name === savedSimplifiedName || p.spouse_name === savedName)) {
  821. // Spouse logic...
  822. if (!p.matches.spouse) p.matches.spouse = [];
  823. if (!p.matches.spouse.find(m => m.id === savedId)) {
  824. p.matches.spouse.push({ id: savedId, name: savedName, sex: parseInt(savedSex) });
  825. }
  826. }
  827. });
  828. // Also, we need to add this new member to the <select> options for future manual selection!
  829. // This is tricky because the select is rendered by Jinja2.
  830. // We can append an option via JS.
  831. const relatedSelect = document.querySelector('select[name="related_mid"]');
  832. if (relatedSelect) {
  833. const newOption = document.createElement('option');
  834. newOption.value = savedId;
  835. newOption.textContent = `${savedName} (ID: ${savedId})`;
  836. // Add birthday data if available for validation
  837. newOption.dataset.birthday = new Date(formData.get('birthday')).getTime() / 1000;
  838. relatedSelect.add(newOption); // Add to end
  839. }
  840. }
  841. // --- End Local Match Update ---
  842. form.reset();
  843. // Clear lineage generation tags
  844. document.querySelectorAll('#lineage-generations-container .lineage-tag').forEach(t => t.remove());
  845. const lgInput = document.getElementById('lineage-input-form');
  846. if (lgInput) lgInput.classList.add('d-none');
  847. const lgAdd = document.getElementById('add-lineage');
  848. if (lgAdd) lgAdd.classList.remove('d-none');
  849. form.querySelector('[name="personal_achievements"]').value = '';
  850. form.querySelector('[name="notes"]').value = '';
  851. form.querySelector('[name="tags"]').value = '';
  852. form.querySelector('[name="family_rank"]').value = '';
  853. // Update the source_record_id field to the current image's ID after reset
  854. const sourceRecordIdField = document.querySelector('input[name="source_record_id"]');
  855. if (sourceRecordIdField && images.length > 0) {
  856. // If we're editing a member, keep the existing source_record_id
  857. // Otherwise, use the current image's ID
  858. const isEditMode = {{ 'true' if member else 'false' }};
  859. if (!isEditMode) {
  860. sourceRecordIdField.value = images[currentIndex].id;
  861. }
  862. }
  863. // Close detail panel
  864. document.getElementById('aiCurrentDetail').style.display = 'none';
  865. // 4. Auto-Next Logic
  866. // Find the next available person in the list to fill
  867. if (window.lastFilledIndex !== undefined) {
  868. const nextIndex = window.lastFilledIndex + 1;
  869. if (currentParsedPeople[nextIndex]) {
  870. // Automatically fill the next one!
  871. fillForm(nextIndex);
  872. // Scroll list to show the new active item if needed
  873. const btn = document.getElementById(`btn-fill-${nextIndex}`);
  874. if(btn) btn.scrollIntoView({ behavior: 'smooth', block: 'center' });
  875. }
  876. }
  877. } else {
  878. alert('保存失败: ' + result.message);
  879. }
  880. } catch (error) {
  881. console.error('Error submitting form:', error);
  882. alert('网络或服务器错误,请稍后重试');
  883. } finally {
  884. submitBtn.disabled = false;
  885. submitBtn.innerHTML = originalBtnHtml;
  886. }
  887. });
  888. });
  889. // --- End AJAX Form Submission ---
  890. function updateDisplay() {
  891. if (images.length > 0) {
  892. const img = images[currentIndex];
  893. document.getElementById('refImage').src = img.url;
  894. document.getElementById('currentPage').innerText = currentIndex + 1;
  895. // Update metadata display
  896. const metaContainer = document.getElementById('imageMetadata');
  897. if (img.genealogy_version || img.genealogy_source || img.upload_person) {
  898. metaContainer.style.display = 'block';
  899. document.getElementById('metaVersion').innerText = img.genealogy_version || '未提供';
  900. document.getElementById('metaSource').innerText = img.genealogy_source || '未提供';
  901. document.getElementById('metaPerson').innerText = img.upload_person || '未提供';
  902. } else {
  903. metaContainer.style.display = 'none';
  904. }
  905. // Update the source_record_id hidden field in the form
  906. const sourceRecordIdField = document.querySelector('input[name="source_record_id"]');
  907. if (sourceRecordIdField) {
  908. // If we're editing a member, keep the existing source_record_id
  909. // Otherwise, use the current image's ID
  910. const isEditMode = {{ 'true' if member else 'false' }};
  911. if (!isEditMode) {
  912. sourceRecordIdField.value = img.id;
  913. }
  914. }
  915. // Reset image state on switch
  916. resetFilters();
  917. // AI Button Logic
  918. const aiBtn = document.getElementById('aiBtn');
  919. const aiPanel = document.getElementById('aiLogPanel');
  920. const resultList = document.getElementById('aiResultList');
  921. const resultCount = document.getElementById('resultCount');
  922. // Hide panel when switching images to avoid confusion
  923. if (aiPanel) aiPanel.style.display = 'none';
  924. // Clear current data
  925. currentParsedPeople = [];
  926. if (resultCount) resultCount.innerText = '0';
  927. if (resultList) resultList.innerHTML = '';
  928. if (img.ai_status === 2 && img.ai_content) {
  929. // Determine content
  930. let content = img.ai_content;
  931. // Parse if string (it might be a string if double encoded or stored as JSON string in DB)
  932. if (typeof content === 'string') {
  933. try { content = JSON.parse(content); } catch(e) { content = []; }
  934. }
  935. if (!Array.isArray(content) && content) content = [content];
  936. if (content && content.length > 0) {
  937. // Update Button to "View Results"
  938. aiBtn.innerHTML = '<i class="bi bi-list-check"></i> 查看解析结果';
  939. aiBtn.className = 'btn btn-sm btn-success text-white ms-2 me-2';
  940. aiBtn.onclick = function() {
  941. // Show panel with loading
  942. if (aiPanel) aiPanel.style.display = 'block';
  943. if (resultList) resultList.innerHTML = '<div class="text-center p-3"><div class="spinner-border text-primary" role="status"></div></div>';
  944. // Process (small delay to allow UI update)
  945. setTimeout(() => processAiData(content), 10);
  946. };
  947. return; // Done
  948. }
  949. }
  950. // Default: Reset to "AI Recognition"
  951. aiBtn.innerHTML = '<i class="bi bi-magic"></i> AI 识别';
  952. aiBtn.className = 'btn btn-sm btn-info text-white ms-2 me-2';
  953. aiBtn.onclick = recognizeImage;
  954. }
  955. }
  956. function nextImage() {
  957. if (images.length === 0) return;
  958. const currentVersion = images[currentIndex].genealogy_version;
  959. // 从当前索引开始,寻找下一个相同版本的图片
  960. for (let i = currentIndex + 1; i < images.length; i++) {
  961. if (images[i].genealogy_version === currentVersion) {
  962. currentIndex = i;
  963. updateDisplay();
  964. return;
  965. }
  966. }
  967. }
  968. function prevImage() {
  969. if (images.length === 0) return;
  970. const currentVersion = images[currentIndex].genealogy_version;
  971. // 从当前索引开始,寻找上一个相同版本的图片
  972. for (let i = currentIndex - 1; i >= 0; i--) {
  973. if (images[i].genealogy_version === currentVersion) {
  974. currentIndex = i;
  975. updateDisplay();
  976. return;
  977. }
  978. }
  979. }
  980. function gotoPage() {
  981. const val = document.getElementById('pageInput').value;
  982. if (!val) return;
  983. const page = parseInt(val);
  984. if (images.length === 0) {
  985. alert('未找到该页码对应的图片');
  986. return;
  987. }
  988. const currentVersion = images[currentIndex].genealogy_version;
  989. const index = images.findIndex(img => img.page === page && img.genealogy_version === currentVersion);
  990. if (index !== -1) {
  991. currentIndex = index;
  992. updateDisplay();
  993. } else {
  994. alert('未找到该页码对应的图片');
  995. }
  996. }
  997. function closeAiLog() {
  998. document.getElementById('aiLogPanel').style.display = 'none';
  999. }
  1000. function toggleAiPanel() {
  1001. const panel = document.getElementById('aiLogPanel');
  1002. if (panel.style.display === 'none') {
  1003. panel.style.display = 'block';
  1004. } else {
  1005. panel.style.display = 'none';
  1006. }
  1007. }
  1008. function updateAiButtonState(hasResults) {
  1009. const btn = document.getElementById('aiBtn');
  1010. if (!btn) return;
  1011. if (hasResults) {
  1012. btn.innerHTML = '<i class="bi bi-list-check"></i> 查看识别结果';
  1013. btn.onclick = toggleAiPanel;
  1014. btn.classList.remove('btn-info');
  1015. btn.classList.add('btn-success');
  1016. } else {
  1017. // Revert state if needed (usually on new image load if we clear data)
  1018. btn.innerHTML = '<i class="bi bi-magic"></i> AI 识别';
  1019. btn.onclick = recognizeImage;
  1020. btn.classList.remove('btn-success');
  1021. btn.classList.add('btn-info');
  1022. }
  1023. }
  1024. function fillForm(index) {
  1025. window.lastFilledIndex = index;
  1026. const person = currentParsedPeople[index];
  1027. if (!person) return;
  1028. const form = document.querySelector('form');
  1029. form.reset(); // Clear previous data first
  1030. if (tomSelectInstance) {
  1031. tomSelectInstance.clear();
  1032. }
  1033. // Set Source Index
  1034. const sourceIndexInput = form.querySelector('[name="source_index"]');
  1035. if (sourceIndexInput) sourceIndexInput.value = index;
  1036. // 1. 姓名
  1037. if (person.name) {
  1038. const nameInput = form.querySelector('[name="name"]');
  1039. nameInput.value = person.name;
  1040. nameInput.dispatchEvent(new Event('input')); // 触发重名检测
  1041. }
  1042. if (person.simplified_name) {
  1043. const snInput = form.querySelector('[name="simplified_name"]');
  1044. if (snInput) snInput.value = person.simplified_name;
  1045. } else {
  1046. // Fallback: if no simplified_name explicitly, generate it
  1047. if (person.name) {
  1048. const snInput = form.querySelector('[name="simplified_name"]');
  1049. if (snInput) snInput.value = cleanName(person.name);
  1050. }
  1051. }
  1052. // 2. 性别
  1053. if (person.sex) {
  1054. const sexSelect = form.querySelector('[name="sex"]');
  1055. if (person.sex.includes('女')) sexSelect.value = '2';
  1056. else if (person.sex.includes('男')) sexSelect.value = '1';
  1057. }
  1058. // 3. 生日 & 自动推断过世
  1059. // Reset unknown toggle first
  1060. const birthdayUnknownCb = document.getElementById('birthdayUnknown');
  1061. if (birthdayUnknownCb) {
  1062. birthdayUnknownCb.checked = false;
  1063. toggleBirthdayUnknown();
  1064. }
  1065. let isDeceased = false;
  1066. let isDeceasedUnknown = true;
  1067. if (person.birthday) {
  1068. let dateVal = person.birthday;
  1069. // Handle partial dates like "1890年" or "1890年?月?日"
  1070. const partialYearMatch = dateVal.match(/^(\d{4})[^\d]*$/) || dateVal.match(/(\d{4})年\s*[??Xxx]\s*月/i);
  1071. if (partialYearMatch) {
  1072. dateVal = `${partialYearMatch[1]}-01-01`;
  1073. } else {
  1074. // 尝试标准化完整日期
  1075. const dateMatch = dateVal.match(/(\d{4})[-/年](\d{1,2})[-/月](\d{1,2})/);
  1076. if (dateMatch) {
  1077. const y = dateMatch[1];
  1078. const m = dateMatch[2].padStart(2, '0');
  1079. const d = dateMatch[3].padStart(2, '0');
  1080. dateVal = `${y}-${m}-${d}`;
  1081. }
  1082. }
  1083. // 只有当日期格式正确时才填充
  1084. if (/^\d{4}-\d{2}-\d{2}$/.test(dateVal)) {
  1085. form.querySelector('[name="birthday"]').value = dateVal;
  1086. // Auto "Is Deceased" Logic (e.g. older than 100 years from now)
  1087. const birthYear = parseInt(dateVal.substring(0, 4));
  1088. const currentYear = new Date().getFullYear();
  1089. if (currentYear - birthYear > 100) {
  1090. isDeceased = true;
  1091. }
  1092. isDeceasedUnknown = false;
  1093. } else {
  1094. // Parse failed, set to unknown
  1095. if (birthdayUnknownCb) {
  1096. birthdayUnknownCb.checked = true;
  1097. toggleBirthdayUnknown();
  1098. }
  1099. }
  1100. } else {
  1101. // No birthday found, automatically check unknown
  1102. if (birthdayUnknownCb) {
  1103. birthdayUnknownCb.checked = true;
  1104. toggleBirthdayUnknown();
  1105. }
  1106. }
  1107. // 当自己年龄不详时,通过父母年龄推断是否在世
  1108. if (isDeceasedUnknown && person.matches && person.matches.father && person.matches.father.length > 0) {
  1109. const father = person.matches.father[0];
  1110. if (father.birthday) {
  1111. const fatherBirthYear = new Date(father.birthday * 1000).getFullYear();
  1112. const currentYear = new Date().getFullYear();
  1113. // 假设如果父亲是120年前出生的,子女大概率也已超过100岁
  1114. if (currentYear - fatherBirthYear > 120) {
  1115. isDeceased = true;
  1116. isDeceasedUnknown = false;
  1117. }
  1118. }
  1119. }
  1120. // 已故状态
  1121. const passAwaySelect = form.querySelector('[name="is_pass_away"]');
  1122. if (passAwaySelect) {
  1123. // "殁", "葬", "卒" in raw text usually means deceased. If AI extracted death_date, also true.
  1124. if (isDeceased || person.death_date) {
  1125. passAwaySelect.value = '1'; // 已故
  1126. } else if (isDeceasedUnknown) {
  1127. passAwaySelect.value = '2'; // 未知
  1128. } else {
  1129. passAwaySelect.value = '0'; // 默认健在,除非有证据
  1130. }
  1131. }
  1132. // 4. 婚姻状况
  1133. const maritalSelect = form.querySelector('[name="marital_status"]');
  1134. if (maritalSelect) {
  1135. if (person.spouse_name) {
  1136. maritalSelect.value = '2'; // 已婚
  1137. } else {
  1138. maritalSelect.value = '0'; // 未知
  1139. }
  1140. }
  1141. // 4. 代数 -> 堂内排行
  1142. if (person.generation) {
  1143. const genMatch = person.generation.match(/\d+/);
  1144. // 这里将 AI 解析的 'generation' 填入 'family_rank' (堂内排行)
  1145. // 'name_word_generation' (世系世代) 保持为空
  1146. form.querySelector('[name="family_rank"]').value = person.generation;
  1147. }
  1148. // 4.5 字辈 (name_word)
  1149. let zibei = person.name_word;
  1150. if (!zibei && person.name) {
  1151. // Heuristic: If name starts with "留" and is 3 chars long (e.g. 留学勤), Zibei is index 1.
  1152. // If name starts with "留" and is > 3 chars, we can't be sure, but index 1 is a good guess for generation char.
  1153. // "留学公" -> "留" + "学" + "公". Zibei "学".
  1154. // "留学勤" -> "留" + "学" + "勤". Zibei "学".
  1155. // Let's use a safe heuristic: if name starts with '留' and length >= 3
  1156. if (person.name.startsWith('留') && person.name.length >= 3) {
  1157. zibei = person.name.charAt(1);
  1158. }
  1159. }
  1160. if (zibei) {
  1161. form.querySelector('[name="name_word"]').value = zibei;
  1162. person.name_word = zibei; // Update data object for display
  1163. }
  1164. // 5. 其他信息
  1165. if (person.education) form.querySelector('[name="educational"]').value = person.education;
  1166. if (person.title) form.querySelector('[name="occupation"]').value = person.title;
  1167. // 个人成就/备注字段追加信息
  1168. let extraInfo = [];
  1169. if (person.father_name) extraInfo.push(`父亲: ${person.father_name}`);
  1170. if (person.spouse_name) extraInfo.push(`配偶: ${person.spouse_name}`);
  1171. // 将亲属关系存入 'notes' (人员备注) 字段
  1172. const notesField = form.querySelector('[name="notes"]');
  1173. const currentNotes = notesField.value;
  1174. const newInfo = extraInfo.join('; ');
  1175. if (newInfo && !currentNotes.includes(newInfo)) {
  1176. notesField.value = currentNotes ? (currentNotes + '\n' + newInfo) : newInfo;
  1177. }
  1178. // 确保无论如何都触发一遍自动匹配事件
  1179. notesField.dispatchEvent(new Event('input', {bubbles: true}));
  1180. if (window.checkSpouseInNotes) {
  1181. window.checkSpouseInNotes();
  1182. }
  1183. // --- Auto-Linking Logic ---
  1184. if (person.matches) {
  1185. // Priority: Father > Spouse (Configurable?)
  1186. // For now, if father matches, select father.
  1187. if (person.matches.father && person.matches.father.length > 0) {
  1188. // Pick the first one for now (could show UI to choose if multiple)
  1189. const father = person.matches.father[0];
  1190. const relTypeSelect = form.querySelector('[name="relation_type"]');
  1191. if (relTypeSelect) {
  1192. // Set the related member
  1193. document.getElementById('related-member-display').value = father.name;
  1194. document.getElementById('related_mid').value = father.id;
  1195. // Set relation type to father
  1196. relTypeSelect.value = '1'; // 父子
  1197. // Trigger the lineage generation reference display
  1198. const relatedMid = document.getElementById('related_mid').value;
  1199. if (relTypeSelect.value == 1 && relatedMid) {
  1200. fetch(`/manager/api/member/${relatedMid}`, {
  1201. credentials: 'include'
  1202. })
  1203. .then(response => response.json())
  1204. .then(data => {
  1205. if (data.member && data.member.name_word_generation) {
  1206. // 显示父亲的世系世代
  1207. const lineageContainer = document.getElementById('lineage-generations-container');
  1208. const fatherLineageDiv = document.getElementById('father-lineage');
  1209. if (!fatherLineageDiv) {
  1210. const newDiv = document.createElement('div');
  1211. newDiv.id = 'father-lineage';
  1212. newDiv.className = 'father-lineage-hint';
  1213. newDiv.innerHTML = `
  1214. <div class="d-flex align-items-center">
  1215. <i class="bi bi-info-circle me-2 text-info"></i>
  1216. <div>
  1217. <strong class="text-info">父亲世系世代参考:</strong>
  1218. <span>${data.member.name_word_generation}</span>
  1219. </div>
  1220. </div>
  1221. `;
  1222. // Find the add button container
  1223. const addButtonContainer = document.querySelector('#lineage-generations-container .d-flex.justify-content-between.align-items-center');
  1224. if (addButtonContainer) {
  1225. // Insert after the add button container
  1226. addButtonContainer.parentNode.insertBefore(newDiv, addButtonContainer.nextSibling);
  1227. } else if (lineageContainer.firstChild) {
  1228. // Insert after the first child
  1229. lineageContainer.insertBefore(newDiv, lineageContainer.firstChild.nextSibling);
  1230. } else {
  1231. // Append to container
  1232. lineageContainer.appendChild(newDiv);
  1233. }
  1234. } else {
  1235. fatherLineageDiv.innerHTML = `
  1236. <div class="d-flex align-items-center">
  1237. <i class="bi bi-info-circle me-2 text-info"></i>
  1238. <div>
  1239. <strong class="text-info">父亲世系世代参考:</strong>
  1240. <span>${data.member.name_word_generation}</span>
  1241. </div>
  1242. </div>
  1243. `;
  1244. }
  1245. }
  1246. });
  1247. }
  1248. }
  1249. } else if (person.matches.spouse && person.matches.spouse.length > 0) {
  1250. const spouse = person.matches.spouse[0];
  1251. const relTypeSelect = form.querySelector('[name="relation_type"]');
  1252. if (relTypeSelect) {
  1253. // Set the related member
  1254. document.getElementById('related-member-display').value = spouse.name;
  1255. document.getElementById('related_mid').value = spouse.id;
  1256. // Set relation type to spouse
  1257. relTypeSelect.value = '10'; // 夫妻
  1258. }
  1259. }
  1260. }
  1261. // --- Show Details Panel ---
  1262. const detailContainer = document.getElementById('aiCurrentDetail');
  1263. const detailContent = document.getElementById('aiDetailContent');
  1264. let html = '<ul class="list-unstyled mb-0 font-monospace" style="font-size: 0.85rem;">';
  1265. const getLabel = (k) => fieldMapping[k] || (k === 'children' ? '子女' : k);
  1266. // 遍历属性显示
  1267. for (const key in person) {
  1268. // 隐藏内部属性
  1269. if (key.startsWith('_')) continue;
  1270. let val = person[key];
  1271. const label = getLabel(key);
  1272. // 特殊处理 children
  1273. if (key === 'children') {
  1274. if (Array.isArray(val) && val.length > 0) {
  1275. let childrenHtml = '<div class="d-flex flex-wrap gap-1 mt-1">';
  1276. val.forEach(child => {
  1277. // 使用 child._originalIndex 进行跳转填充
  1278. childrenHtml += `<button class="btn btn-sm btn-outline-info py-0 px-2" style="font-size: 0.75rem;" onclick="fillForm(${child._originalIndex})">${child.name || '未知'}</button>`;
  1279. });
  1280. childrenHtml += '</div>';
  1281. html += `<li class="mb-1"><span class="text-info opacity-75">${label}:</span> ${childrenHtml}</li>`;
  1282. }
  1283. continue;
  1284. }
  1285. // 默认显示
  1286. if (!val || val === '') val = '-';
  1287. html += `<li class="mb-1"><span class="text-info opacity-75">${label}:</span> <span class="text-white ms-1">${val}</span></li>`;
  1288. }
  1289. html += '</ul>';
  1290. detailContent.innerHTML = html;
  1291. detailContainer.style.display = 'block';
  1292. // Visual feedback
  1293. const btn = document.getElementById(`btn-fill-${index}`);
  1294. if(btn) {
  1295. const originalHtml = btn.innerHTML;
  1296. btn.innerHTML = '<i class="bi bi-check"></i> 已填';
  1297. btn.classList.remove('btn-outline-info');
  1298. btn.classList.add('btn-info', 'text-white');
  1299. setTimeout(() => {
  1300. btn.innerHTML = originalHtml;
  1301. btn.classList.add('btn-outline-info');
  1302. btn.classList.remove('btn-info', 'text-white');
  1303. }, 1000);
  1304. }
  1305. }
  1306. // --- Pre-fill Logic from Backend (Async AI Result) ---
  1307. const prefilledContent = {{ prefilled_content | tojson | safe if prefilled_content else 'null' }};
  1308. const sourceOssUrl = "{{ source_oss_url if source_oss_url else '' }}";
  1309. const sourceRecordId = "{{ source_record_id if source_record_id else '' }}";
  1310. if (prefilledContent && (sourceOssUrl || sourceRecordId)) {
  1311. // We have prefilled content from DB, simulate "Recognize Image" success
  1312. document.addEventListener('DOMContentLoaded', async () => {
  1313. // Wait a bit for UI to settle
  1314. setTimeout(async () => {
  1315. // Find image index
  1316. let imgIndex = -1;
  1317. if (sourceRecordId) {
  1318. //优先根据sourceRecordId查找
  1319. imgIndex = images.findIndex(img => img.id == sourceRecordId);
  1320. }
  1321. if (imgIndex === -1 && sourceOssUrl) {
  1322. //如果根据sourceRecordId没找到,再根据sourceOssUrl查找
  1323. imgIndex = images.findIndex(img => img.url === sourceOssUrl);
  1324. }
  1325. if (imgIndex !== -1) {
  1326. currentIndex = imgIndex;
  1327. updateDisplay();
  1328. }
  1329. // Parse and display results
  1330. try {
  1331. let data = prefilledContent;
  1332. if (typeof data === 'string') {
  1333. try {
  1334. data = JSON.parse(data);
  1335. } catch(e) {
  1336. console.error("Prefilled content parse error", e);
  1337. return;
  1338. }
  1339. }
  1340. if (!Array.isArray(data)) data = [data];
  1341. await processAiData(data);
  1342. // Open the log panel to show results
  1343. const aiPanel = document.getElementById('aiLogPanel');
  1344. if (aiPanel) aiPanel.style.display = 'block';
  1345. const status = document.getElementById('reasoningStatus');
  1346. if(status) {
  1347. status.textContent = '已加载历史解析';
  1348. status.className = 'badge bg-success ms-2';
  1349. }
  1350. const logContent = document.getElementById('aiLogContent');
  1351. if(logContent) logContent.textContent = "已加载历史 AI 解析记录。";
  1352. } catch (e) {
  1353. console.error("Error processing prefilled content", e);
  1354. }
  1355. }, 500);
  1356. });
  1357. } else {
  1358. // No prefilled content, initialize display for the first image
  1359. document.addEventListener('DOMContentLoaded', () => {
  1360. updateDisplay();
  1361. });
  1362. }
  1363. // --- Name Cleaning Logic (Matching Backend) ---
  1364. // 仅做繁 -> 简转换,不动姓氏/“公”处理,用于配偶等非留氏族人
  1365. function manualSimplify(text) {
  1366. if (!text) return text;
  1367. text = text.trim();
  1368. const mapping = {
  1369. '學': '学', '國': '国', '萬': '万', '寶': '宝', '興': '兴',
  1370. '華': '华', '會': '会', '葉': '叶', '藝': '艺', '號': '号',
  1371. '處': '处', '見': '见', '視': '视', '言': '言', '語': '语',
  1372. '貝': '贝', '車': '车', '長': '长', '門': '门', '韋': '韦',
  1373. '頁': '页', '風': '风', '飛': '飞', '食': '食', '馬': '马',
  1374. '魚': '鱼', '鳥': '鸟', '麥': '麦', '黃': '黄', '齊': '齐',
  1375. '齒': '齿', '龍': '龙', '龜': '龟', '壽': '寿', '榮': '荣',
  1376. '愛': '爱', '慶': '庆', '衛': '卫', '賢': '贤', '義': '义',
  1377. '禮': '礼', '樂': '乐', '靈': '灵', '滅': '灭', '氣': '气',
  1378. '智': '智', '信': '信', '仁': '仁', '勇': '勇', '嚴': '严',
  1379. '劉': '刘'
  1380. };
  1381. let result = '';
  1382. for (const ch of text) {
  1383. result += mapping[ch] || ch;
  1384. }
  1385. return result;
  1386. }
  1387. // 留氏本人姓名清洗:在 manualSimplify 基础上,处理“留”姓和“公”
  1388. function cleanName(name) {
  1389. if (!name) return name;
  1390. name = manualSimplify(name);
  1391. const exceptions = ['学公', '留学公'];
  1392. if (exceptions.includes(name)) {
  1393. if (!name.startsWith('留')) {
  1394. name = '留' + name;
  1395. }
  1396. return name;
  1397. }
  1398. // Remove '公' suffix
  1399. if (name.endsWith('公')) {
  1400. name = name.slice(0, -1);
  1401. }
  1402. // Ensure '留' prefix
  1403. if (!name.startsWith('留')) {
  1404. name = '留' + name;
  1405. }
  1406. return name;
  1407. }
  1408. function isFemaleSex(sexValue) {
  1409. if (sexValue === null || sexValue === undefined) return false;
  1410. const s = String(sexValue).trim().toLowerCase();
  1411. return s === '女' || s === '2' || s === 'female' || s === 'f';
  1412. }
  1413. function normalizeLookupName(name) {
  1414. if (!name) return '';
  1415. return manualSimplify(String(name)).trim();
  1416. }
  1417. // Extracted function to process AI data and render tree
  1418. async function processAiData(data) {
  1419. const spouseNameSet = new Set();
  1420. data.forEach(p => {
  1421. const n = normalizeLookupName(p.spouse_name);
  1422. if (n) spouseNameSet.add(n);
  1423. });
  1424. // Clean Names First
  1425. data.forEach(p => {
  1426. // Determine "Original" (Raw) and "Simplified" (Cleaned)
  1427. let rawName = p.original_name || p.name;
  1428. let simName = p.name || p.original_name; // Prefer AI simplified name; fallback to raw
  1429. const ownName1 = normalizeLookupName(p.name);
  1430. const ownName2 = normalizeLookupName(p.original_name);
  1431. const isFemaleSpouse = isFemaleSex(p.sex) && (
  1432. !!normalizeLookupName(p.spouse_name) ||
  1433. (ownName1 && spouseNameSet.has(ownName1)) ||
  1434. (ownName2 && spouseNameSet.has(ownName2))
  1435. );
  1436. // 女性配偶:只繁转简,不拼接“留”;其他人维持原规则
  1437. p.simplified_name = isFemaleSpouse ? manualSimplify(simName) : cleanName(simName);
  1438. // Set the name to be the Raw Name for storage in 'name' column
  1439. p.name = rawName;
  1440. // 父亲:同族,用 cleanName(加“留”、去“公”)
  1441. if (p.father_name) p.father_name = cleanName(p.father_name);
  1442. // 配偶:只做繁体 -> 简体,不拼接“留”姓
  1443. if (p.spouse_name) p.spouse_name = manualSimplify(p.spouse_name);
  1444. });
  1445. // Call Relation Check API
  1446. try {
  1447. // Send simplified_name for checking relations if available, or name?
  1448. // The API checks against DB 'name' column.
  1449. // Wait, DB 'name' column is now Traditional Raw.
  1450. // But existing data in DB is Simplified Cleaned.
  1451. // New data will be Traditional Raw in 'name', Simplified Cleaned in 'simplified_name'.
  1452. // The check_relations API uses `WHERE name IN (...)`.
  1453. // The AI returns `father_name` as Simplified (usually).
  1454. // So we are checking Simplified Father Name against...
  1455. // If DB 'name' is mixed (Old Simplified, New Traditional), this is messy.
  1456. // But `check_relations` logic:
  1457. // `names_to_check.add(p['father_name'])` -> Simplified.
  1458. // `SELECT ... WHERE name IN ...`
  1459. // If DB 'name' contains Traditional, we won't find match if we search Simplified.
  1460. // Unless we search `simplified_name` column too?
  1461. // I should update `check_relations` in app.py to search both `name` and `simplified_name`.
  1462. const checkRes = await fetch('/manager/api/check_relations', {
  1463. method: 'POST',
  1464. headers: { 'Content-Type': 'application/json' },
  1465. body: JSON.stringify({ people: data })
  1466. });
  1467. const checkResult = await checkRes.json();
  1468. if (checkResult.success && checkResult.matches) {
  1469. // Merge matches into data
  1470. for (const idx in checkResult.matches) {
  1471. const match = checkResult.matches[idx];
  1472. if (data[idx]) {
  1473. data[idx].matches = match;
  1474. }
  1475. }
  1476. }
  1477. } catch (e) {
  1478. console.warn("Auto-linking failed:", e);
  1479. }
  1480. currentParsedPeople = data;
  1481. document.getElementById('resultCount').innerText = data.length;
  1482. // Update Button State to "View Results"
  1483. updateAiButtonState(true);
  1484. // Build Relationship Tree
  1485. const personMap = {};
  1486. const roots = [];
  1487. // 1. Initialize map
  1488. data.forEach((p, index) => {
  1489. p._originalIndex = index; // Store original index for fillForm
  1490. p.children = [];
  1491. // Use simplified_name as key if available, otherwise name (for consistent lookup)
  1492. const lookupKey = p.simplified_name || p.name;
  1493. personMap[lookupKey] = p;
  1494. });
  1495. // 2. Build Hierarchy
  1496. data.forEach(p => {
  1497. let parentFound = false;
  1498. if (p.father_name) {
  1499. // Try exact match using simplified name (since father_name is usually simplified)
  1500. let father = personMap[p.father_name];
  1501. // Try loose match
  1502. if (!father) {
  1503. for (const name in personMap) {
  1504. if (name.includes(p.father_name) || p.father_name.includes(name)) {
  1505. father = personMap[name];
  1506. break;
  1507. }
  1508. }
  1509. }
  1510. if (father && father !== p) {
  1511. father.children.push(p);
  1512. parentFound = true;
  1513. }
  1514. }
  1515. if (!parentFound) {
  1516. roots.push(p);
  1517. }
  1518. });
  1519. // 3. Recursive Render Function
  1520. function renderNode(p, level = 0) {
  1521. const indent = level * 20;
  1522. let html = `
  1523. <div class="card bg-dark border-secondary mb-1" style="margin-left: ${indent}px; background-color: #2c3034;">
  1524. <div class="card-body p-2 d-flex justify-content-between align-items-center">
  1525. <div class="text-white">
  1526. <div class="fw-bold">
  1527. ${level > 0 ? '<i class="bi bi-arrow-return-right text-secondary me-1"></i>' : ''}
  1528. ${p.name || '未知姓名'}
  1529. <span class="badge bg-secondary text-light ms-1" style="font-size: 0.7rem">${p.sex || '-'}</span>
  1530. </div>
  1531. <div class="small text-white-50" style="font-size: 0.75rem; padding-left: ${level > 0 ? 18 : 0}px;">
  1532. ${p.generation ? '第'+p.generation+'世 ' : ''}
  1533. ${p.father_name ? '父:'+p.father_name : ''}
  1534. </div>
  1535. </div>
  1536. <button id="btn-fill-${p._originalIndex}"
  1537. class="btn btn-sm ${p.is_imported ? 'btn-success disabled' : 'btn-outline-info'} text-nowrap ms-2"
  1538. onclick="${p.is_imported ? '' : `fillForm(${p._originalIndex})`}">
  1539. ${p.is_imported ? '<i class="bi bi-check-lg"></i> 已录入' : '<i class="bi bi-pencil-square"></i> 填充'}
  1540. </button>
  1541. </div>
  1542. </div>
  1543. `;
  1544. if (p.children && p.children.length > 0) {
  1545. p.children.forEach(child => {
  1546. html += renderNode(child, level + 1);
  1547. });
  1548. }
  1549. return html;
  1550. }
  1551. // Render List
  1552. const resultList = document.getElementById('aiResultList');
  1553. const resultSection = document.getElementById('aiResultSection');
  1554. resultList.innerHTML = '';
  1555. // Fix: Use data directly if root finding logic fails or returns empty but data exists
  1556. if (roots.length === 0 && data.length > 0) {
  1557. // Just dump everything flat if tree building fails
  1558. data.forEach(p => resultList.innerHTML += renderNode(p, 0));
  1559. } else {
  1560. roots.forEach(p => {
  1561. resultList.innerHTML += renderNode(p, 0);
  1562. });
  1563. }
  1564. resultSection.style.display = 'block';
  1565. }
  1566. async function recognizeImage() {
  1567. if (images.length === 0) {
  1568. alert('没有可用的图片');
  1569. return;
  1570. }
  1571. const currentImg = images[currentIndex];
  1572. const btn = document.getElementById('aiBtn');
  1573. const originalContent = btn.innerHTML;
  1574. const logPanel = document.getElementById('aiLogPanel');
  1575. const logContent = document.getElementById('aiLogContent');
  1576. const resultSection = document.getElementById('aiResultSection');
  1577. const resultList = document.getElementById('aiResultList');
  1578. const reasoningStatus = document.getElementById('reasoningStatus');
  1579. btn.disabled = true;
  1580. btn.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> 识别中...';
  1581. // Reset UI
  1582. logContent.textContent = '';
  1583. resultList.innerHTML = '';
  1584. resultSection.style.display = 'none';
  1585. logPanel.style.display = 'block';
  1586. reasoningStatus.textContent = '连接中...';
  1587. reasoningStatus.className = 'badge bg-secondary ms-2';
  1588. // Ensure reasoning panel is open
  1589. const collapseReasoning = document.getElementById('collapseReasoning');
  1590. if (collapseReasoning && !collapseReasoning.classList.contains('show')) {
  1591. new bootstrap.Collapse(collapseReasoning, { show: true });
  1592. }
  1593. // Retry logic function
  1594. async function fetchAndParse(url, retryCount = 0) {
  1595. const MAX_RETRIES = 2;
  1596. let fullText = '';
  1597. let jsonPart = '';
  1598. let hasJsonStarted = false;
  1599. try {
  1600. if (retryCount > 0) {
  1601. logContent.textContent = `\n[System] 解析失败,正在进行第 ${retryCount} 次重试...\n` + logContent.textContent;
  1602. reasoningStatus.textContent = `重试 ${retryCount}...`;
  1603. }
  1604. const response = await fetch('/manager/api/recognize_image', {
  1605. method: 'POST',
  1606. headers: { 'Content-Type': 'application/json' },
  1607. body: JSON.stringify({ image_url: url })
  1608. });
  1609. if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
  1610. const reader = response.body.getReader();
  1611. const decoder = new TextDecoder();
  1612. const separator = "|||JSON_START|||";
  1613. while (true) {
  1614. const { value, done } = await reader.read();
  1615. if (done) break;
  1616. const chunk = decoder.decode(value, { stream: true });
  1617. fullText += chunk;
  1618. // Only update display if not parsing JSON part yet or just started
  1619. if (!hasJsonStarted) {
  1620. const sepIndex = fullText.indexOf(separator);
  1621. if (sepIndex !== -1) {
  1622. hasJsonStarted = true;
  1623. reasoningStatus.textContent = '解析中...';
  1624. reasoningStatus.className = 'badge bg-info ms-2';
  1625. // Split content for display - only once
  1626. const reasoningPart = fullText.substring(0, sepIndex);
  1627. logContent.textContent = reasoningPart;
  1628. if (collapseReasoning) {
  1629. new bootstrap.Collapse(collapseReasoning, { hide: true });
  1630. }
  1631. } else {
  1632. // Update reasoning text
  1633. logContent.textContent = fullText;
  1634. logContent.scrollTop = logContent.scrollHeight;
  1635. }
  1636. }
  1637. }
  1638. // Parsing Logic
  1639. if (hasJsonStarted) {
  1640. const sepIndex = fullText.indexOf(separator);
  1641. jsonPart = fullText.substring(sepIndex + separator.length);
  1642. reasoningStatus.textContent = '完成';
  1643. reasoningStatus.className = 'badge bg-success ms-2';
  1644. } else {
  1645. // Fallback
  1646. jsonPart = fullText;
  1647. }
  1648. // Clean JSON
  1649. // 1. Try finding [...] array
  1650. let start = jsonPart.indexOf('[');
  1651. let end = jsonPart.lastIndexOf(']');
  1652. // 2. If not found, try finding {...} object and wrap it
  1653. let isSingleObject = false;
  1654. if (start === -1 || end === -1 || end <= start) {
  1655. start = jsonPart.indexOf('{');
  1656. end = jsonPart.lastIndexOf('}');
  1657. isSingleObject = true;
  1658. }
  1659. if (start !== -1 && end !== -1 && end > start) {
  1660. jsonPart = jsonPart.substring(start, end + 1);
  1661. } else {
  1662. // Try to extract any JSON-like array/object structure using regex as fallback
  1663. const jsonMatch = jsonPart.match(/(\[.*\]|\{.*\})/s);
  1664. if (jsonMatch) {
  1665. jsonPart = jsonMatch[0];
  1666. if (jsonPart.trim().startsWith('{')) isSingleObject = true;
  1667. } else {
  1668. // No valid JSON structure found
  1669. console.warn("No JSON brackets found in:", jsonPart);
  1670. throw new Error("未找到有效的 JSON 数据结构");
  1671. }
  1672. }
  1673. let data;
  1674. try {
  1675. // Pre-clean: Remove common markdown code block markers if stuck inside
  1676. jsonPart = jsonPart.replace(/^```json\s*/, '').replace(/```$/, '');
  1677. data = JSON.parse(jsonPart);
  1678. } catch (e) {
  1679. // Attempt to fix common JSON errors (e.g. trailing commas, unclosed strings) - simplified
  1680. console.error("JSON parse error. Content:", jsonPart);
  1681. // Force retry on parse error
  1682. throw new Error("JSON 格式解析错误");
  1683. }
  1684. if (isSingleObject && !Array.isArray(data)) {
  1685. data = [data]; // Normalize to array
  1686. } else if (!Array.isArray(data)) {
  1687. data = [data];
  1688. }
  1689. return data;
  1690. } catch (error) {
  1691. if (retryCount < MAX_RETRIES) {
  1692. // Wait 1s and retry
  1693. await new Promise(r => setTimeout(r, 1000));
  1694. return fetchAndParse(url, retryCount + 1);
  1695. }
  1696. throw error;
  1697. }
  1698. }
  1699. try {
  1700. const data = await fetchAndParse(currentImg.url);
  1701. // Use shared processing function
  1702. await processAiData(data);
  1703. // Update local state for persistence during session
  1704. if (images[currentIndex]) {
  1705. images[currentIndex].ai_status = 2;
  1706. images[currentIndex].ai_content = data;
  1707. }
  1708. } catch (error) {
  1709. console.error(error);
  1710. // Append error to log instead of overwriting valid reasoning
  1711. logContent.textContent += `\n\n[Error] ${error.message}`;
  1712. alert('AI 识别过程失败,请重试。\n错误详情: ' + error.message);
  1713. } finally {
  1714. btn.innerHTML = originalContent;
  1715. btn.disabled = false;
  1716. }
  1717. }
  1718. // Check for duplicate name
  1719. let nameCheckTimeout = null;
  1720. const nameInput = document.getElementById('nameInput');
  1721. const nameCheckResult = document.getElementById('nameCheckResult');
  1722. if (nameInput) {
  1723. nameInput.addEventListener('input', function() {
  1724. clearTimeout(nameCheckTimeout);
  1725. const nameVal = this.value.trim();
  1726. if (!nameVal) {
  1727. nameCheckResult.innerHTML = '';
  1728. return;
  1729. }
  1730. nameCheckTimeout = setTimeout(() => {
  1731. fetch(`/manager/api/check_name?name=${encodeURIComponent(nameVal)}`)
  1732. .then(r => r.json())
  1733. .then(data => {
  1734. if (data.success && data.exists) {
  1735. let html = `<div class="alert alert-warning py-2 mb-0 mt-2 small">
  1736. <i class="bi bi-exclamation-triangle-fill"></i> 发现 <strong>${data.matches.length}</strong> 个同名记录,请确认是否为同一人:
  1737. <ul class="mb-0 mt-1 ps-3">`;
  1738. data.matches.forEach(m => {
  1739. let sex = m.sex === 1 ? '男' : (m.sex === 2 ? '女' : '未知');
  1740. let deadStr = m.is_pass_away == 1 ? ' (已故)' : (m.is_pass_away == 2 ? ' (未知)' : '');
  1741. html += `<li><a href="/manager/member_detail/${m.id}" target="_blank" class="alert-link">${m.name}</a> - ${sex} - 出生: ${m.birthday_str}${deadStr}</li>`;
  1742. });
  1743. html += `</ul></div>`;
  1744. nameCheckResult.innerHTML = html;
  1745. } else {
  1746. nameCheckResult.innerHTML = '';
  1747. }
  1748. })
  1749. .catch(err => console.error('Error checking name:', err));
  1750. }, 600);
  1751. });
  1752. }
  1753. // Auto-link spouse from notes if female
  1754. const notesInput = document.querySelector('textarea[name="notes"]');
  1755. const sexSelect = document.querySelector('select[name="sex"]');
  1756. // Attach to window so fillForm can explicitly call it
  1757. window.checkSpouseInNotes = function() {
  1758. if (!notesInput || !sexSelect) return;
  1759. const val = notesInput.value;
  1760. // Check for father information
  1761. const fatherMatch = val.match(/父亲[::\s]*([^\s;;,,。]+)/);
  1762. if (fatherMatch && fatherMatch[1]) {
  1763. const fatherName = fatherMatch[1].trim();
  1764. const relationTypeSelect = document.querySelector('select[name="relation_type"]');
  1765. if (relationTypeSelect) {
  1766. // Find the father in the members list
  1767. fetch(`/manager/api/members?search=${encodeURIComponent(fatherName)}`, {
  1768. credentials: 'include'
  1769. })
  1770. .then(response => response.json())
  1771. .then(data => {
  1772. if (data.members && data.members.length > 0) {
  1773. // Find the best match
  1774. let bestMatch = null;
  1775. for (const member of data.members) {
  1776. const optName = member.name;
  1777. const normalizedOpt = optName.replace(/公$/, '').replace(/^留/, '');
  1778. const normalizedFather = fatherName.replace(/公$/, '').replace(/^留/, '');
  1779. if (optName === fatherName || normalizedOpt === normalizedFather ||
  1780. (normalizedOpt && normalizedFather && (normalizedOpt.includes(normalizedFather) || normalizedFather.includes(normalizedOpt)))) {
  1781. bestMatch = member;
  1782. break;
  1783. }
  1784. }
  1785. if (bestMatch) {
  1786. // Set the related member
  1787. document.getElementById('related-member-display').value = bestMatch.name;
  1788. document.getElementById('related_mid').value = bestMatch.id;
  1789. // Set relation type to father
  1790. relationTypeSelect.value = '1';
  1791. // Trigger the lineage generation reference display
  1792. const relatedMid = document.getElementById('related_mid').value;
  1793. if (relationTypeSelect.value == 1 && relatedMid) {
  1794. fetch(`/manager/api/member/${relatedMid}`, {
  1795. credentials: 'include'
  1796. })
  1797. .then(response => response.json())
  1798. .then(data => {
  1799. if (data.member && data.member.name_word_generation) {
  1800. // 显示父亲的世系世代
  1801. const lineageContainer = document.getElementById('lineage-generations-container');
  1802. const fatherLineageDiv = document.getElementById('father-lineage');
  1803. if (!fatherLineageDiv) {
  1804. const newDiv = document.createElement('div');
  1805. newDiv.id = 'father-lineage';
  1806. newDiv.className = 'father-lineage-hint';
  1807. newDiv.innerHTML = `
  1808. <div class="d-flex align-items-center">
  1809. <i class="bi bi-info-circle me-2 text-info"></i>
  1810. <div>
  1811. <strong class="text-info">父亲世系世代参考:</strong>
  1812. <span>${data.member.name_word_generation}</span>
  1813. </div>
  1814. </div>
  1815. `;
  1816. // Find the add button container
  1817. const addButtonContainer = document.querySelector('#lineage-generations-container .d-flex.justify-content-between.align-items-center');
  1818. if (addButtonContainer) {
  1819. // Insert after the add button container
  1820. addButtonContainer.parentNode.insertBefore(newDiv, addButtonContainer.nextSibling);
  1821. } else if (lineageContainer.firstChild) {
  1822. // Insert after the first child
  1823. lineageContainer.insertBefore(newDiv, lineageContainer.firstChild.nextSibling);
  1824. } else {
  1825. // Append to container
  1826. lineageContainer.appendChild(newDiv);
  1827. }
  1828. } else {
  1829. fatherLineageDiv.innerHTML = `
  1830. <div class="d-flex align-items-center">
  1831. <i class="bi bi-info-circle me-2 text-info"></i>
  1832. <div>
  1833. <strong class="text-info">父亲世系世代参考:</strong>
  1834. <span>${data.member.name_word_generation}</span>
  1835. </div>
  1836. </div>
  1837. `;
  1838. }
  1839. }
  1840. });
  1841. }
  1842. }
  1843. }
  1844. });
  1845. }
  1846. }
  1847. // Only check for spouse if female
  1848. if (sexSelect.value === '2') {
  1849. const spouseMatch = val.match(/配偶[::\s]*([^\s;;,,。]+)/);
  1850. if (spouseMatch && spouseMatch[1]) {
  1851. const spouseName = spouseMatch[1].trim();
  1852. const relationTypeSelect = document.querySelector('select[name="relation_type"]');
  1853. if (relationTypeSelect) {
  1854. // Find the spouse in the members list
  1855. fetch(`/manager/api/members?search=${encodeURIComponent(spouseName)}`, {
  1856. credentials: 'include'
  1857. })
  1858. .then(response => response.json())
  1859. .then(data => {
  1860. if (data.members && data.members.length > 0) {
  1861. // Find the best match
  1862. let bestMatch = null;
  1863. for (const member of data.members) {
  1864. const optName = member.name;
  1865. const normalizedOpt = optName.replace(/公$/, '').replace(/^留/, '');
  1866. const normalizedSpouse = spouseName.replace(/公$/, '').replace(/^留/, '');
  1867. if (optName === spouseName || normalizedOpt === normalizedSpouse ||
  1868. (normalizedOpt && normalizedSpouse && (normalizedOpt.includes(normalizedSpouse) || normalizedSpouse.includes(normalizedOpt)))) {
  1869. bestMatch = member;
  1870. break;
  1871. }
  1872. }
  1873. if (bestMatch) {
  1874. // Set the related member
  1875. document.getElementById('related-member-display').value = bestMatch.name;
  1876. document.getElementById('related_mid').value = bestMatch.id;
  1877. // Set relation type to spouse
  1878. relationTypeSelect.value = '10';
  1879. }
  1880. }
  1881. });
  1882. }
  1883. }
  1884. }
  1885. };
  1886. if (notesInput && sexSelect) {
  1887. notesInput.addEventListener('input', window.checkSpouseInNotes);
  1888. sexSelect.addEventListener('change', window.checkSpouseInNotes);
  1889. }
  1890. </script>
  1891. <script>
  1892. document.addEventListener('DOMContentLoaded', function() {
  1893. const container = document.getElementById('lineage-generations-container');
  1894. const addButton = document.getElementById('add-lineage');
  1895. const inputForm = document.getElementById('lineage-input-form');
  1896. const lineageInput = document.getElementById('lineage-input');
  1897. const confirmButton = document.getElementById('confirm-lineage');
  1898. const cancelButton = document.getElementById('cancel-lineage');
  1899. if (!container || !addButton || !inputForm || !lineageInput || !confirmButton || !cancelButton) return;
  1900. function addLineageTag(value) {
  1901. const tag = document.createElement('span');
  1902. tag.className = 'lineage-tag badge bg-primary bg-opacity-10 text-primary border border-primary border-opacity-25 px-3 py-2 rounded-pill d-inline-flex align-items-center';
  1903. tag.style.fontSize = '0.85rem';
  1904. tag.innerHTML = `${value}<button type="button" class="btn-close ms-2 remove-lineage" style="font-size:0.55rem;filter:none;opacity:0.6;" aria-label="删除"></button><input type="hidden" name="lineage_generations[]" value="${value}">`;
  1905. container.insertBefore(tag, inputForm);
  1906. }
  1907. container.addEventListener('click', function(e) {
  1908. const removeBtn = e.target.closest('.remove-lineage');
  1909. if (removeBtn) {
  1910. e.preventDefault();
  1911. e.stopPropagation();
  1912. const tag = removeBtn.closest('.lineage-tag');
  1913. if (tag) tag.remove();
  1914. }
  1915. });
  1916. addButton.addEventListener('click', function(e) {
  1917. e.preventDefault();
  1918. e.stopPropagation();
  1919. inputForm.classList.remove('d-none');
  1920. addButton.classList.add('d-none');
  1921. lineageInput.value = '';
  1922. lineageInput.focus();
  1923. });
  1924. function confirmInput() {
  1925. const value = lineageInput.value.trim();
  1926. if (value) {
  1927. addLineageTag(value);
  1928. }
  1929. lineageInput.value = '';
  1930. inputForm.classList.add('d-none');
  1931. addButton.classList.remove('d-none');
  1932. }
  1933. confirmButton.addEventListener('click', function(e) {
  1934. e.preventDefault();
  1935. e.stopPropagation();
  1936. confirmInput();
  1937. });
  1938. lineageInput.addEventListener('keydown', function(e) {
  1939. if (e.key === 'Enter') {
  1940. e.preventDefault();
  1941. e.stopPropagation();
  1942. confirmInput();
  1943. }
  1944. if (e.key === 'Escape') {
  1945. e.preventDefault();
  1946. lineageInput.value = '';
  1947. inputForm.classList.add('d-none');
  1948. addButton.classList.remove('d-none');
  1949. }
  1950. });
  1951. cancelButton.addEventListener('click', function(e) {
  1952. e.preventDefault();
  1953. e.stopPropagation();
  1954. lineageInput.value = '';
  1955. inputForm.classList.add('d-none');
  1956. addButton.classList.remove('d-none');
  1957. });
  1958. });
  1959. // 加载成员数据
  1960. function loadMembers(page = 1, search = '') {
  1961. console.log('Loading members...', { page, search });
  1962. fetch(`/manager/api/members?page=${page}&search=${encodeURIComponent(search)}`, {
  1963. credentials: 'include'
  1964. })
  1965. .then(response => {
  1966. console.log('Response status:', response.status);
  1967. return response.json();
  1968. })
  1969. .then(data => {
  1970. console.log('Response data:', data);
  1971. // Check if it's an error response
  1972. if (data.success === false) {
  1973. console.error('API error:', data.message);
  1974. // If unauthorized, redirect to login
  1975. if (data.message === 'Unauthorized') {
  1976. window.location.href = '/manager/login';
  1977. }
  1978. return;
  1979. }
  1980. // Handle success response - check if members and total exist
  1981. if (data.members !== undefined && data.total !== undefined) {
  1982. membersData = data.members;
  1983. totalMembers = data.total;
  1984. totalPages = Math.ceil(totalMembers / 10);
  1985. currentPage = page;
  1986. // 更新成员列表
  1987. updateMemberList();
  1988. // 更新分页
  1989. updatePagination();
  1990. // 更新总数
  1991. document.getElementById('total-members').textContent = totalMembers;
  1992. } else {
  1993. console.error('Invalid response structure:', data);
  1994. // Set default values
  1995. membersData = [];
  1996. totalMembers = 0;
  1997. totalPages = 1;
  1998. currentPage = 1;
  1999. updateMemberList();
  2000. updatePagination();
  2001. document.getElementById('total-members').textContent = 0;
  2002. }
  2003. })
  2004. .catch(error => {
  2005. console.error('Error loading members:', error);
  2006. });
  2007. }
  2008. // 更新成员列表
  2009. function updateMemberList() {
  2010. const memberList = document.getElementById('member-list');
  2011. memberList.innerHTML = '';
  2012. if (membersData.length === 0) {
  2013. memberList.innerHTML = '<div class="list-group-item text-center text-muted">暂无成员数据</div>';
  2014. return;
  2015. }
  2016. membersData.forEach(function(member) {
  2017. const item = document.createElement('div');
  2018. item.className = 'list-group-item list-group-item-action shadow-sm hover:bg-light';
  2019. item.style.transition = 'all 0.2s ease';
  2020. item.onclick = function() {
  2021. selectMemberById(member.id);
  2022. };
  2023. item.innerHTML = `
  2024. <div class="d-flex justify-content-between align-items-center">
  2025. <div>
  2026. <h6 class="mb-0">
  2027. <a href="/manager/member_detail/${member.id}" target="_blank" class="text-primary text-decoration-none" onclick="event.stopPropagation();">
  2028. ${member.name} ${member.simplified_name && member.simplified_name !== member.name ? `(${member.simplified_name})` : ''}
  2029. </a>
  2030. </h6>
  2031. <small class="text-muted">ID: ${member.id} | ${member.sex === 1 ? '男' : '女'}</small>
  2032. ${member.name_word_generation ? `<small class="d-block text-muted">世系世代: ${member.name_word_generation}</small>` : ''}
  2033. ${member.father_name ? `
  2034. <small class="d-block text-muted">
  2035. 父亲: ${member.father_name} ${member.father_simplified_name && member.father_simplified_name !== member.father_name ? `(${member.father_simplified_name})` : ''}
  2036. ${member.father_generation ? ` | 世系世代: ${member.father_generation}` : ''}
  2037. </small>
  2038. ` : ''}
  2039. </div>
  2040. <button type="button" class="btn btn-sm btn-primary" onclick="event.stopPropagation(); selectMemberById(${member.id});">
  2041. 选择
  2042. </button>
  2043. </div>
  2044. `;
  2045. memberList.appendChild(item);
  2046. });
  2047. }
  2048. // 更新分页
  2049. function updatePagination() {
  2050. const pagination = document.querySelector('.pagination');
  2051. pagination.innerHTML = '';
  2052. // 上一页
  2053. const prevLi = document.createElement('li');
  2054. prevLi.className = `page-item ${currentPage === 1 ? 'disabled' : ''}`;
  2055. prevLi.innerHTML = `<a class="page-link" href="#" onclick="changePage(${currentPage - 1})">&laquo;</a>`;
  2056. pagination.appendChild(prevLi);
  2057. // 页码
  2058. for (let i = 1; i <= totalPages; i++) {
  2059. const li = document.createElement('li');
  2060. li.className = `page-item ${i === currentPage ? 'active' : ''}`;
  2061. li.innerHTML = `<a class="page-link" href="#" onclick="changePage(${i})">${i}</a>`;
  2062. pagination.appendChild(li);
  2063. }
  2064. // 下一页
  2065. const nextLi = document.createElement('li');
  2066. nextLi.className = `page-item ${currentPage === totalPages ? 'disabled' : ''}`;
  2067. nextLi.innerHTML = `<a class="page-link" href="#" onclick="changePage(${currentPage + 1})">&raquo;</a>`;
  2068. pagination.appendChild(nextLi);
  2069. }
  2070. // 改变页码
  2071. function changePage(page) {
  2072. if (page < 1 || page > totalPages) return;
  2073. const search = document.getElementById('member-search').value;
  2074. loadMembers(page, search);
  2075. }
  2076. // 搜索成员
  2077. function searchMembers() {
  2078. const search = document.getElementById('member-search').value;
  2079. loadMembers(1, search);
  2080. }
  2081. // 选择成员
  2082. function selectMember(member) {
  2083. document.getElementById('related-member-display').value = member.name;
  2084. document.getElementById('related_mid').value = member.id;
  2085. // 检查是否是父子关系,如果是,显示父亲的世系世代
  2086. const relationType = document.querySelector('select[name="relation_type"]').value;
  2087. if (relationType == 1) { // 父子关系
  2088. fetch(`/manager/api/member/${member.id}`)
  2089. .then(response => response.json())
  2090. .then(data => {
  2091. if (data.member && data.member.name_word_generation) {
  2092. // 显示父亲的世系世代
  2093. const lineageContainer = document.getElementById('lineage-generations-container');
  2094. const fatherLineageDiv = document.getElementById('father-lineage');
  2095. if (!fatherLineageDiv) {
  2096. const newDiv = document.createElement('div');
  2097. newDiv.id = 'father-lineage';
  2098. newDiv.className = 'father-lineage-hint';
  2099. newDiv.innerHTML = `
  2100. <div class="d-flex align-items-center">
  2101. <i class="bi bi-info-circle me-2 text-info"></i>
  2102. <div>
  2103. <strong class="text-info">父亲世系世代参考:</strong>
  2104. <span>${data.member.name_word_generation}</span>
  2105. </div>
  2106. </div>
  2107. `;
  2108. // Find the add button container
  2109. const addButtonContainer = document.querySelector('#lineage-generations-container .d-flex.justify-content-between.align-items-center');
  2110. if (addButtonContainer) {
  2111. // Insert after the add button container
  2112. addButtonContainer.parentNode.insertBefore(newDiv, addButtonContainer.nextSibling);
  2113. } else if (lineageContainer.firstChild) {
  2114. // Insert after the first child
  2115. lineageContainer.insertBefore(newDiv, lineageContainer.firstChild.nextSibling);
  2116. } else {
  2117. // Append to container
  2118. lineageContainer.appendChild(newDiv);
  2119. }
  2120. } else {
  2121. fatherLineageDiv.innerHTML = `
  2122. <div class="d-flex align-items-center">
  2123. <i class="bi bi-info-circle me-2 text-info"></i>
  2124. <div>
  2125. <strong class="text-info">父亲世系世代参考:</strong>
  2126. <span>${data.member.name_word_generation}</span>
  2127. </div>
  2128. </div>
  2129. `;
  2130. }
  2131. }
  2132. });
  2133. }
  2134. // 关闭模态框
  2135. const modal = bootstrap.Modal.getInstance(document.getElementById('memberSelectModal'));
  2136. modal.hide();
  2137. }
  2138. // 通过ID选择成员
  2139. function selectMemberById(memberId) {
  2140. // 先在当前加载的成员中查找
  2141. const member = membersData.find(m => m.id === memberId);
  2142. if (member) {
  2143. selectMember(member);
  2144. } else {
  2145. // 如果没找到,从API获取
  2146. fetch(`/manager/api/member/${memberId}`)
  2147. .then(response => response.json())
  2148. .then(data => {
  2149. if (data.member) {
  2150. selectMember(data.member);
  2151. }
  2152. });
  2153. }
  2154. }
  2155. // 监听关系类型变化
  2156. document.addEventListener('DOMContentLoaded', function() {
  2157. // 监听关系类型变化
  2158. const relationTypeSelect = document.querySelector('select[name="relation_type"]');
  2159. if (relationTypeSelect) {
  2160. relationTypeSelect.addEventListener('change', function() {
  2161. const relatedMid = document.getElementById('related_mid').value;
  2162. if (this.value == 1 && relatedMid) {
  2163. // 如果选择了父子关系且已选择关联成员,显示父亲的世系世代
  2164. fetch(`/manager/api/member/${relatedMid}`, {
  2165. credentials: 'include'
  2166. })
  2167. .then(response => response.json())
  2168. .then(data => {
  2169. if (data.member && data.member.name_word_generation) {
  2170. const lineageContainer = document.getElementById('lineage-generations-container');
  2171. const fatherLineageDiv = document.getElementById('father-lineage');
  2172. if (!fatherLineageDiv) {
  2173. const newDiv = document.createElement('div');
  2174. newDiv.id = 'father-lineage';
  2175. newDiv.className = 'father-lineage-hint';
  2176. newDiv.innerHTML = `
  2177. <div class="d-flex align-items-center">
  2178. <i class="bi bi-info-circle me-2 text-info"></i>
  2179. <div>
  2180. <strong class="text-info">父亲世系世代参考:</strong>
  2181. <span>${data.member.name_word_generation}</span>
  2182. </div>
  2183. </div>
  2184. `;
  2185. // Find the add button container
  2186. const addButtonContainer = document.querySelector('#lineage-generations-container .d-flex.justify-content-between.align-items-center');
  2187. if (addButtonContainer) {
  2188. // Insert after the add button container
  2189. addButtonContainer.parentNode.insertBefore(newDiv, addButtonContainer.nextSibling);
  2190. } else if (lineageContainer.firstChild) {
  2191. // Insert after the first child
  2192. lineageContainer.insertBefore(newDiv, lineageContainer.firstChild.nextSibling);
  2193. } else {
  2194. // Append to container
  2195. lineageContainer.appendChild(newDiv);
  2196. }
  2197. } else {
  2198. fatherLineageDiv.innerHTML = `
  2199. <div class="d-flex align-items-center">
  2200. <i class="bi bi-info-circle me-2 text-info"></i>
  2201. <div>
  2202. <strong class="text-info">父亲世系世代参考:</strong>
  2203. <span>${data.member.name_word_generation}</span>
  2204. </div>
  2205. </div>
  2206. `;
  2207. }
  2208. }
  2209. });
  2210. }
  2211. });
  2212. }
  2213. // 监听成员选择模态框显示
  2214. const memberSelectModal = document.getElementById('memberSelectModal');
  2215. memberSelectModal.addEventListener('shown.bs.modal', function() {
  2216. loadMembers();
  2217. });
  2218. });
  2219. </script>
  2220. {% endblock %}