add_member.html 117 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419
  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">
  408. <div class="modal-header">
  409. <h5 class="modal-title"><i class="bi bi-people me-2"></i>选择关联成员</h5>
  410. <button type="button" class="btn-close" 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-outline-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">
  428. <li class="page-item disabled">
  429. <a class="page-link" href="#" onclick="changePage(0)">上一页</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)">下一页</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. let currentParsedPeople = [];
  541. // Image State
  542. let imgRotation = 0;
  543. let imgBrightness = 100;
  544. let imgContrast = 100;
  545. // Dragging State
  546. let isDragging = false;
  547. let hasDragged = false;
  548. let startX = 0, startY = 0;
  549. let currentX = 0, currentY = 0; // Relative to center (offsets)
  550. // Zoom State
  551. let isZoomedIn = false;
  552. const ZOOM_LEVEL = 2.0;
  553. // Magnifier Logic
  554. const viewer = document.getElementById('viewer');
  555. const magnifier = document.getElementById('magnifier');
  556. const magnifierSwitch = document.getElementById('magnifierSwitch');
  557. const imageWrapper = document.getElementById('imageWrapper');
  558. // Initialize Dragging and Zooming
  559. if (imageWrapper) {
  560. // Center initial position
  561. imageWrapper.style.left = '50%';
  562. imageWrapper.style.top = '50%';
  563. viewer.style.cursor = 'zoom-in';
  564. viewer.addEventListener('mousedown', (e) => {
  565. if (e.target.closest('.image-toolbar') || e.target.closest('.magnifier-glass')) return;
  566. isDragging = true;
  567. hasDragged = false;
  568. startX = e.clientX;
  569. startY = e.clientY;
  570. viewer.style.cursor = 'grabbing';
  571. e.preventDefault(); // Prevent text selection
  572. });
  573. window.addEventListener('mousemove', (e) => {
  574. if (!isDragging) return;
  575. const dx = e.clientX - startX;
  576. const dy = e.clientY - startY;
  577. // Threshold to consider it a drag
  578. if (Math.abs(dx) > 2 || Math.abs(dy) > 2) {
  579. hasDragged = true;
  580. }
  581. currentX += dx;
  582. currentY += dy;
  583. startX = e.clientX;
  584. startY = e.clientY;
  585. updateImageTransform();
  586. });
  587. window.addEventListener('mouseup', (e) => {
  588. if (isDragging) {
  589. isDragging = false;
  590. viewer.style.cursor = isZoomedIn ? 'grab' : 'zoom-in';
  591. // If it was a click (not a drag) and clicked inside the viewer
  592. if (!hasDragged && viewer.contains(e.target)) {
  593. toggleZoom();
  594. }
  595. }
  596. });
  597. }
  598. function toggleZoom() {
  599. isZoomedIn = !isZoomedIn;
  600. if (!isZoomedIn) {
  601. // Reset position when zooming out to center
  602. currentX = 0;
  603. currentY = 0;
  604. }
  605. updateImageTransform();
  606. // Update cursor immediately
  607. viewer.style.cursor = isZoomedIn ? 'grab' : 'zoom-in';
  608. }
  609. viewer.addEventListener('mousemove', function(e) {
  610. if (!magnifierSwitch.checked) {
  611. magnifier.style.display = 'none';
  612. return;
  613. }
  614. if (isDragging) {
  615. magnifier.style.display = 'none';
  616. return;
  617. }
  618. const img = document.getElementById('refImage');
  619. if (!img) return;
  620. // Calculate position relative to the image
  621. const rect = img.getBoundingClientRect();
  622. const x = e.clientX - rect.left;
  623. const y = e.clientY - rect.top;
  624. // Only show if inside image rect (approximate for rotated)
  625. if (x < 0 || x > rect.width || y < 0 || y > rect.height) {
  626. magnifier.style.display = 'none';
  627. return;
  628. }
  629. magnifier.style.display = 'block';
  630. // Position the glass near mouse
  631. const glassOffset = 20;
  632. const viewerRect = viewer.getBoundingClientRect();
  633. magnifier.style.left = (e.clientX - viewerRect.left + glassOffset) + 'px';
  634. magnifier.style.top = (e.clientY - viewerRect.top + glassOffset) + 'px';
  635. // Background logic (Zoom 2x)
  636. const zoom = 2.5;
  637. magnifier.style.backgroundImage = `url('${img.src}')`;
  638. magnifier.style.backgroundSize = `${rect.width * zoom}px ${rect.height * zoom}px`;
  639. // Simple version (imperfect for rotation)
  640. magnifier.style.backgroundPosition = `-${x * zoom - 75}px -${y * zoom - 75}px`;
  641. });
  642. // Image Manipulation
  643. function rotateImage(deg) {
  644. imgRotation = (imgRotation + deg) % 360;
  645. updateImageTransform();
  646. }
  647. function updateImageFilter() {
  648. imgBrightness = document.getElementById('brightnessRange').value;
  649. imgContrast = document.getElementById('contrastRange').value;
  650. applyImageFilters();
  651. }
  652. function resetFilters() {
  653. imgRotation = 0;
  654. imgBrightness = 100;
  655. imgContrast = 100;
  656. currentX = 0;
  657. currentY = 0;
  658. isZoomedIn = false;
  659. document.getElementById('brightnessRange').value = 100;
  660. document.getElementById('contrastRange').value = 100;
  661. updateImageTransform();
  662. applyImageFilters();
  663. }
  664. function updateImageTransform() {
  665. const wrapper = document.getElementById('imageWrapper');
  666. if (wrapper) {
  667. const scale = isZoomedIn ? ZOOM_LEVEL : 1;
  668. wrapper.style.transform = `translate(calc(-50% + ${currentX}px), calc(-50% + ${currentY}px)) rotate(${imgRotation}deg) scale(${scale})`;
  669. // Adjust cursor based on state
  670. if (!isDragging) {
  671. viewer.style.cursor = isZoomedIn ? 'grab' : 'zoom-in';
  672. }
  673. }
  674. }
  675. function applyImageFilters() {
  676. const img = document.getElementById('refImage');
  677. if (img) {
  678. img.style.filter = `brightness(${imgBrightness}%) contrast(${imgContrast}%)`;
  679. }
  680. }
  681. // Reuse applyImageStyles as alias for compatibility if called elsewhere
  682. function applyImageStyles() {
  683. updateImageTransform();
  684. applyImageFilters();
  685. }
  686. const fieldMapping = {
  687. name: '姓名(繁体)',
  688. simplified_name: '姓名(简体)',
  689. sex: '性别',
  690. birthday: '出生日期',
  691. father_name: '父亲姓名',
  692. spouse_name: '配偶姓名',
  693. generation: '堂内排行(代数)',
  694. name_word: '字辈',
  695. education: '学历/功名',
  696. title: '官职/称号',
  697. death_date: '逝世日期',
  698. note: '备注'
  699. };
  700. // --- Keyboard Shortcuts ---
  701. document.addEventListener('keydown', (e) => {
  702. // Ctrl/Cmd + Enter: Save
  703. if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') {
  704. e.preventDefault();
  705. const submitBtn = document.querySelector('form button[type="submit"]');
  706. if (submitBtn && !submitBtn.disabled) {
  707. submitBtn.click(); // Trigger form submit listener
  708. }
  709. }
  710. // Ctrl/Cmd + Right Arrow: Next Image
  711. if ((e.ctrlKey || e.metaKey) && e.key === 'ArrowRight') {
  712. e.preventDefault();
  713. nextImage();
  714. }
  715. // Ctrl/Cmd + Left Arrow: Prev Image
  716. if ((e.ctrlKey || e.metaKey) && e.key === 'ArrowLeft') {
  717. e.preventDefault();
  718. prevImage();
  719. }
  720. // Alt + 1: Auto Fill First person in list
  721. if (e.altKey && e.key === '1') {
  722. e.preventDefault();
  723. // Try to find the first "fill" button that is not disabled/success
  724. const firstBtn = document.querySelector('button[id^="btn-fill-"]:not(.btn-success)');
  725. if (firstBtn) firstBtn.click();
  726. }
  727. });
  728. // --- AJAX Form Submission ---
  729. document.addEventListener('DOMContentLoaded', () => {
  730. const form = document.querySelector('form');
  731. form.addEventListener('submit', async (e) => {
  732. e.preventDefault();
  733. // Collect form data
  734. const formData = new FormData(form);
  735. // Visual feedback on button
  736. const submitBtn = form.querySelector('button[type="submit"]');
  737. const originalBtnHtml = submitBtn.innerHTML;
  738. submitBtn.disabled = true;
  739. submitBtn.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> 保存中...';
  740. try {
  741. // Use form.action to support both add and edit URLs
  742. const targetUrl = form.action || window.location.href;
  743. const response = await fetch(targetUrl, {
  744. method: 'POST',
  745. body: formData,
  746. headers: {
  747. 'X-Requested-With': 'XMLHttpRequest'
  748. }
  749. });
  750. const result = await response.json();
  751. if (result.success) {
  752. // Success!
  753. // 1. Show a toast or small alert
  754. const toast = document.createElement('div');
  755. toast.className = 'position-fixed bottom-0 start-50 translate-middle-x mb-4 p-3 bg-success text-white rounded shadow';
  756. toast.style.zIndex = '2000';
  757. toast.innerHTML = `<i class="bi bi-check-circle me-2"></i> ${result.message}`;
  758. document.body.appendChild(toast);
  759. setTimeout(() => toast.remove(), 3000);
  760. // 2. Mark the AI list item as "Saved" if applicable
  761. if (window.lastFilledIndex !== undefined) {
  762. const btn = document.getElementById(`btn-fill-${window.lastFilledIndex}`);
  763. if (btn) {
  764. btn.className = 'btn btn-sm btn-success text-white ms-2 disabled';
  765. btn.innerHTML = '<i class="bi bi-check-lg"></i> 已录入';
  766. btn.onclick = null;
  767. }
  768. // Update local data state so it persists if we switch images/filters
  769. if (currentParsedPeople[window.lastFilledIndex]) {
  770. currentParsedPeople[window.lastFilledIndex].is_imported = true;
  771. currentParsedPeople[window.lastFilledIndex].imported_member_id = result.member_id;
  772. // Sync back to images array to persist across image switching
  773. if (images[currentIndex]) {
  774. images[currentIndex].ai_content = currentParsedPeople;
  775. }
  776. }
  777. }
  778. // 3. Clear form (reset to defaults) or keep some fields?
  779. // Usually for genealogy, Surname/Generation might be same, but let's clear for safety
  780. // Resetting form but keeping "related_mid" might be useful for siblings?
  781. // For now, simple reset.
  782. // --- Update Local Matches before resetting form ---
  783. // If we just saved a person, check if this person is the father/spouse of anyone else in the list
  784. // and update their matches so 'fillForm' will work for them.
  785. const savedName = formData.get('name'); // Traditional (Raw)
  786. const savedSimplifiedName = formData.get('simplified_name'); // Simplified (Cleaned)
  787. const savedId = result.member_id;
  788. const savedSex = formData.get('sex'); // 1: Male, 2: Female
  789. if (savedId) {
  790. currentParsedPeople.forEach(p => {
  791. if (!p.matches) p.matches = {};
  792. // Check Father Match
  793. // Try matching against Simplified Name (p.father_name is Simplified Cleaned)
  794. // Or fallback to savedName if p.father_name happened to be Traditional (rare but possible)
  795. if (p.father_name && (p.father_name === savedSimplifiedName || p.father_name === savedName)) {
  796. // Assume simple match logic here (usually father is male)
  797. if (savedSex === '1') {
  798. if (!p.matches.father) p.matches.father = [];
  799. // Add to matches if not exists
  800. if (!p.matches.father.find(m => m.id === savedId)) {
  801. p.matches.father.push({ id: savedId, name: savedName, sex: 1 }); // Mock DB object
  802. }
  803. }
  804. }
  805. // Check Spouse Match
  806. if (p.spouse_name && (p.spouse_name === savedSimplifiedName || p.spouse_name === savedName)) {
  807. // Spouse logic...
  808. if (!p.matches.spouse) p.matches.spouse = [];
  809. if (!p.matches.spouse.find(m => m.id === savedId)) {
  810. p.matches.spouse.push({ id: savedId, name: savedName, sex: parseInt(savedSex) });
  811. }
  812. }
  813. });
  814. // Also, we need to add this new member to the <select> options for future manual selection!
  815. // This is tricky because the select is rendered by Jinja2.
  816. // We can append an option via JS.
  817. const relatedSelect = document.querySelector('select[name="related_mid"]');
  818. if (relatedSelect) {
  819. const newOption = document.createElement('option');
  820. newOption.value = savedId;
  821. newOption.textContent = `${savedName} (ID: ${savedId})`;
  822. // Add birthday data if available for validation
  823. newOption.dataset.birthday = new Date(formData.get('birthday')).getTime() / 1000;
  824. relatedSelect.add(newOption); // Add to end
  825. }
  826. }
  827. // --- End Local Match Update ---
  828. form.reset();
  829. // Clear lineage generation tags
  830. document.querySelectorAll('#lineage-generations-container .lineage-tag').forEach(t => t.remove());
  831. const lgInput = document.getElementById('lineage-input-form');
  832. if (lgInput) lgInput.classList.add('d-none');
  833. const lgAdd = document.getElementById('add-lineage');
  834. if (lgAdd) lgAdd.classList.remove('d-none');
  835. form.querySelector('[name="personal_achievements"]').value = '';
  836. form.querySelector('[name="notes"]').value = '';
  837. form.querySelector('[name="tags"]').value = '';
  838. form.querySelector('[name="family_rank"]').value = '';
  839. // Update the source_record_id field to the current image's ID after reset
  840. const sourceRecordIdField = document.querySelector('input[name="source_record_id"]');
  841. if (sourceRecordIdField && images.length > 0) {
  842. sourceRecordIdField.value = images[currentIndex].id;
  843. }
  844. // Close detail panel
  845. document.getElementById('aiCurrentDetail').style.display = 'none';
  846. // 4. Auto-Next Logic
  847. // Find the next available person in the list to fill
  848. if (window.lastFilledIndex !== undefined) {
  849. const nextIndex = window.lastFilledIndex + 1;
  850. if (currentParsedPeople[nextIndex]) {
  851. // Automatically fill the next one!
  852. fillForm(nextIndex);
  853. // Scroll list to show the new active item if needed
  854. const btn = document.getElementById(`btn-fill-${nextIndex}`);
  855. if(btn) btn.scrollIntoView({ behavior: 'smooth', block: 'center' });
  856. }
  857. }
  858. } else {
  859. alert('保存失败: ' + result.message);
  860. }
  861. } catch (error) {
  862. console.error('Error submitting form:', error);
  863. alert('网络或服务器错误,请稍后重试');
  864. } finally {
  865. submitBtn.disabled = false;
  866. submitBtn.innerHTML = originalBtnHtml;
  867. }
  868. });
  869. });
  870. // --- End AJAX Form Submission ---
  871. function updateDisplay() {
  872. if (images.length > 0) {
  873. const img = images[currentIndex];
  874. document.getElementById('refImage').src = img.url;
  875. document.getElementById('currentPage').innerText = currentIndex + 1;
  876. // Update metadata display
  877. const metaContainer = document.getElementById('imageMetadata');
  878. if (img.genealogy_version || img.genealogy_source || img.upload_person) {
  879. metaContainer.style.display = 'block';
  880. document.getElementById('metaVersion').innerText = img.genealogy_version || '未提供';
  881. document.getElementById('metaSource').innerText = img.genealogy_source || '未提供';
  882. document.getElementById('metaPerson').innerText = img.upload_person || '未提供';
  883. } else {
  884. metaContainer.style.display = 'none';
  885. }
  886. // Update the source_record_id hidden field in the form
  887. const sourceRecordIdField = document.querySelector('input[name="source_record_id"]');
  888. if (sourceRecordIdField) {
  889. sourceRecordIdField.value = img.id;
  890. }
  891. // Reset image state on switch
  892. resetFilters();
  893. // AI Button Logic
  894. const aiBtn = document.getElementById('aiBtn');
  895. const aiPanel = document.getElementById('aiLogPanel');
  896. const resultList = document.getElementById('aiResultList');
  897. const resultCount = document.getElementById('resultCount');
  898. // Hide panel when switching images to avoid confusion
  899. if (aiPanel) aiPanel.style.display = 'none';
  900. // Clear current data
  901. currentParsedPeople = [];
  902. if (resultCount) resultCount.innerText = '0';
  903. if (resultList) resultList.innerHTML = '';
  904. if (img.ai_status === 2 && img.ai_content) {
  905. // Determine content
  906. let content = img.ai_content;
  907. // Parse if string (it might be a string if double encoded or stored as JSON string in DB)
  908. if (typeof content === 'string') {
  909. try { content = JSON.parse(content); } catch(e) { content = []; }
  910. }
  911. if (!Array.isArray(content) && content) content = [content];
  912. if (content && content.length > 0) {
  913. // Update Button to "View Results"
  914. aiBtn.innerHTML = '<i class="bi bi-list-check"></i> 查看解析结果';
  915. aiBtn.className = 'btn btn-sm btn-success text-white ms-2 me-2';
  916. aiBtn.onclick = function() {
  917. // Show panel with loading
  918. if (aiPanel) aiPanel.style.display = 'block';
  919. if (resultList) resultList.innerHTML = '<div class="text-center p-3"><div class="spinner-border text-primary" role="status"></div></div>';
  920. // Process (small delay to allow UI update)
  921. setTimeout(() => processAiData(content), 10);
  922. };
  923. return; // Done
  924. }
  925. }
  926. // Default: Reset to "AI Recognition"
  927. aiBtn.innerHTML = '<i class="bi bi-magic"></i> AI 识别';
  928. aiBtn.className = 'btn btn-sm btn-info text-white ms-2 me-2';
  929. aiBtn.onclick = recognizeImage;
  930. }
  931. }
  932. function nextImage() {
  933. if (currentIndex < images.length - 1) {
  934. currentIndex++;
  935. updateDisplay();
  936. }
  937. }
  938. function prevImage() {
  939. if (currentIndex > 0) {
  940. currentIndex--;
  941. updateDisplay();
  942. }
  943. }
  944. function gotoPage() {
  945. const val = document.getElementById('pageInput').value;
  946. if (!val) return;
  947. const page = parseInt(val);
  948. const index = images.findIndex(img => img.page === page);
  949. if (index !== -1) {
  950. currentIndex = index;
  951. updateDisplay();
  952. } else {
  953. alert('未找到该页码对应的图片');
  954. }
  955. }
  956. function closeAiLog() {
  957. document.getElementById('aiLogPanel').style.display = 'none';
  958. }
  959. function toggleAiPanel() {
  960. const panel = document.getElementById('aiLogPanel');
  961. if (panel.style.display === 'none') {
  962. panel.style.display = 'block';
  963. } else {
  964. panel.style.display = 'none';
  965. }
  966. }
  967. function updateAiButtonState(hasResults) {
  968. const btn = document.getElementById('aiBtn');
  969. if (!btn) return;
  970. if (hasResults) {
  971. btn.innerHTML = '<i class="bi bi-list-check"></i> 查看识别结果';
  972. btn.onclick = toggleAiPanel;
  973. btn.classList.remove('btn-info');
  974. btn.classList.add('btn-success');
  975. } else {
  976. // Revert state if needed (usually on new image load if we clear data)
  977. btn.innerHTML = '<i class="bi bi-magic"></i> AI 识别';
  978. btn.onclick = recognizeImage;
  979. btn.classList.remove('btn-success');
  980. btn.classList.add('btn-info');
  981. }
  982. }
  983. function fillForm(index) {
  984. window.lastFilledIndex = index;
  985. const person = currentParsedPeople[index];
  986. if (!person) return;
  987. const form = document.querySelector('form');
  988. form.reset(); // Clear previous data first
  989. if (tomSelectInstance) {
  990. tomSelectInstance.clear();
  991. }
  992. // Set Source Index
  993. const sourceIndexInput = form.querySelector('[name="source_index"]');
  994. if (sourceIndexInput) sourceIndexInput.value = index;
  995. // 1. 姓名
  996. if (person.name) {
  997. const nameInput = form.querySelector('[name="name"]');
  998. nameInput.value = person.name;
  999. nameInput.dispatchEvent(new Event('input')); // 触发重名检测
  1000. }
  1001. if (person.simplified_name) {
  1002. const snInput = form.querySelector('[name="simplified_name"]');
  1003. if (snInput) snInput.value = person.simplified_name;
  1004. } else {
  1005. // Fallback: if no simplified_name explicitly, generate it
  1006. if (person.name) {
  1007. const snInput = form.querySelector('[name="simplified_name"]');
  1008. if (snInput) snInput.value = cleanName(person.name);
  1009. }
  1010. }
  1011. // 2. 性别
  1012. if (person.sex) {
  1013. const sexSelect = form.querySelector('[name="sex"]');
  1014. if (person.sex.includes('女')) sexSelect.value = '2';
  1015. else if (person.sex.includes('男')) sexSelect.value = '1';
  1016. }
  1017. // 3. 生日 & 自动推断过世
  1018. // Reset unknown toggle first
  1019. const birthdayUnknownCb = document.getElementById('birthdayUnknown');
  1020. if (birthdayUnknownCb) {
  1021. birthdayUnknownCb.checked = false;
  1022. toggleBirthdayUnknown();
  1023. }
  1024. let isDeceased = false;
  1025. let isDeceasedUnknown = true;
  1026. if (person.birthday) {
  1027. let dateVal = person.birthday;
  1028. // Handle partial dates like "1890年" or "1890年?月?日"
  1029. const partialYearMatch = dateVal.match(/^(\d{4})[^\d]*$/) || dateVal.match(/(\d{4})年\s*[??Xxx]\s*月/i);
  1030. if (partialYearMatch) {
  1031. dateVal = `${partialYearMatch[1]}-01-01`;
  1032. } else {
  1033. // 尝试标准化完整日期
  1034. const dateMatch = dateVal.match(/(\d{4})[-/年](\d{1,2})[-/月](\d{1,2})/);
  1035. if (dateMatch) {
  1036. const y = dateMatch[1];
  1037. const m = dateMatch[2].padStart(2, '0');
  1038. const d = dateMatch[3].padStart(2, '0');
  1039. dateVal = `${y}-${m}-${d}`;
  1040. }
  1041. }
  1042. // 只有当日期格式正确时才填充
  1043. if (/^\d{4}-\d{2}-\d{2}$/.test(dateVal)) {
  1044. form.querySelector('[name="birthday"]').value = dateVal;
  1045. // Auto "Is Deceased" Logic (e.g. older than 100 years from now)
  1046. const birthYear = parseInt(dateVal.substring(0, 4));
  1047. const currentYear = new Date().getFullYear();
  1048. if (currentYear - birthYear > 100) {
  1049. isDeceased = true;
  1050. }
  1051. isDeceasedUnknown = false;
  1052. } else {
  1053. // Parse failed, set to unknown
  1054. if (birthdayUnknownCb) {
  1055. birthdayUnknownCb.checked = true;
  1056. toggleBirthdayUnknown();
  1057. }
  1058. }
  1059. } else {
  1060. // No birthday found, automatically check unknown
  1061. if (birthdayUnknownCb) {
  1062. birthdayUnknownCb.checked = true;
  1063. toggleBirthdayUnknown();
  1064. }
  1065. }
  1066. // 当自己年龄不详时,通过父母年龄推断是否在世
  1067. if (isDeceasedUnknown && person.matches && person.matches.father && person.matches.father.length > 0) {
  1068. const father = person.matches.father[0];
  1069. if (father.birthday) {
  1070. const fatherBirthYear = new Date(father.birthday * 1000).getFullYear();
  1071. const currentYear = new Date().getFullYear();
  1072. // 假设如果父亲是120年前出生的,子女大概率也已超过100岁
  1073. if (currentYear - fatherBirthYear > 120) {
  1074. isDeceased = true;
  1075. isDeceasedUnknown = false;
  1076. }
  1077. }
  1078. }
  1079. // 已故状态
  1080. const passAwaySelect = form.querySelector('[name="is_pass_away"]');
  1081. if (passAwaySelect) {
  1082. // "殁", "葬", "卒" in raw text usually means deceased. If AI extracted death_date, also true.
  1083. if (isDeceased || person.death_date) {
  1084. passAwaySelect.value = '1'; // 已故
  1085. } else if (isDeceasedUnknown) {
  1086. passAwaySelect.value = '2'; // 未知
  1087. } else {
  1088. passAwaySelect.value = '0'; // 默认健在,除非有证据
  1089. }
  1090. }
  1091. // 4. 婚姻状况
  1092. const maritalSelect = form.querySelector('[name="marital_status"]');
  1093. if (maritalSelect) {
  1094. if (person.spouse_name) {
  1095. maritalSelect.value = '2'; // 已婚
  1096. } else {
  1097. maritalSelect.value = '0'; // 未知
  1098. }
  1099. }
  1100. // 4. 代数 -> 堂内排行
  1101. if (person.generation) {
  1102. const genMatch = person.generation.match(/\d+/);
  1103. // 这里将 AI 解析的 'generation' 填入 'family_rank' (堂内排行)
  1104. // 'name_word_generation' (世系世代) 保持为空
  1105. form.querySelector('[name="family_rank"]').value = person.generation;
  1106. }
  1107. // 4.5 字辈 (name_word)
  1108. let zibei = person.name_word;
  1109. if (!zibei && person.name) {
  1110. // Heuristic: If name starts with "留" and is 3 chars long (e.g. 留学勤), Zibei is index 1.
  1111. // If name starts with "留" and is > 3 chars, we can't be sure, but index 1 is a good guess for generation char.
  1112. // "留学公" -> "留" + "学" + "公". Zibei "学".
  1113. // "留学勤" -> "留" + "学" + "勤". Zibei "学".
  1114. // Let's use a safe heuristic: if name starts with '留' and length >= 3
  1115. if (person.name.startsWith('留') && person.name.length >= 3) {
  1116. zibei = person.name.charAt(1);
  1117. }
  1118. }
  1119. if (zibei) {
  1120. form.querySelector('[name="name_word"]').value = zibei;
  1121. person.name_word = zibei; // Update data object for display
  1122. }
  1123. // 5. 其他信息
  1124. if (person.education) form.querySelector('[name="educational"]').value = person.education;
  1125. if (person.title) form.querySelector('[name="occupation"]').value = person.title;
  1126. // 个人成就/备注字段追加信息
  1127. let extraInfo = [];
  1128. if (person.father_name) extraInfo.push(`父亲: ${person.father_name}`);
  1129. if (person.spouse_name) extraInfo.push(`配偶: ${person.spouse_name}`);
  1130. // 将亲属关系存入 'notes' (人员备注) 字段
  1131. const notesField = form.querySelector('[name="notes"]');
  1132. const currentNotes = notesField.value;
  1133. const newInfo = extraInfo.join('; ');
  1134. if (newInfo && !currentNotes.includes(newInfo)) {
  1135. notesField.value = currentNotes ? (currentNotes + '\n' + newInfo) : newInfo;
  1136. }
  1137. // 确保无论如何都触发一遍自动匹配事件
  1138. notesField.dispatchEvent(new Event('input', {bubbles: true}));
  1139. if (window.checkSpouseInNotes) {
  1140. window.checkSpouseInNotes();
  1141. }
  1142. // --- Auto-Linking Logic ---
  1143. if (person.matches) {
  1144. // Priority: Father > Spouse (Configurable?)
  1145. // For now, if father matches, select father.
  1146. if (person.matches.father && person.matches.father.length > 0) {
  1147. // Pick the first one for now (could show UI to choose if multiple)
  1148. const father = person.matches.father[0];
  1149. const relTypeSelect = form.querySelector('[name="relation_type"]');
  1150. if (relTypeSelect) {
  1151. // Set the related member
  1152. document.getElementById('related-member-display').value = father.name;
  1153. document.getElementById('related_mid').value = father.id;
  1154. // Set relation type to father
  1155. relTypeSelect.value = '1'; // 父子
  1156. // Trigger the lineage generation reference display
  1157. const relatedMid = document.getElementById('related_mid').value;
  1158. if (relTypeSelect.value == 1 && relatedMid) {
  1159. fetch(`/manager/api/member/${relatedMid}`)
  1160. .then(response => response.json())
  1161. .then(data => {
  1162. if (data.member && data.member.name_word_generation) {
  1163. // 显示父亲的世系世代
  1164. const lineageContainer = document.getElementById('lineage-generations-container');
  1165. const fatherLineageDiv = document.getElementById('father-lineage');
  1166. if (!fatherLineageDiv) {
  1167. const newDiv = document.createElement('div');
  1168. newDiv.id = 'father-lineage';
  1169. newDiv.className = 'father-lineage-hint';
  1170. newDiv.innerHTML = `
  1171. <div class="d-flex align-items-center">
  1172. <i class="bi bi-info-circle me-2 text-info"></i>
  1173. <div>
  1174. <strong class="text-info">父亲世系世代参考:</strong>
  1175. <span>${data.member.name_word_generation}</span>
  1176. </div>
  1177. </div>
  1178. `;
  1179. // Find the add button container
  1180. const addButtonContainer = document.querySelector('#lineage-generations-container .d-flex.justify-content-between.align-items-center');
  1181. if (addButtonContainer) {
  1182. // Insert after the add button container
  1183. addButtonContainer.parentNode.insertBefore(newDiv, addButtonContainer.nextSibling);
  1184. } else if (lineageContainer.firstChild) {
  1185. // Insert after the first child
  1186. lineageContainer.insertBefore(newDiv, lineageContainer.firstChild.nextSibling);
  1187. } else {
  1188. // Append to container
  1189. lineageContainer.appendChild(newDiv);
  1190. }
  1191. } else {
  1192. fatherLineageDiv.innerHTML = `
  1193. <div class="d-flex align-items-center">
  1194. <i class="bi bi-info-circle me-2 text-info"></i>
  1195. <div>
  1196. <strong class="text-info">父亲世系世代参考:</strong>
  1197. <span>${data.member.name_word_generation}</span>
  1198. </div>
  1199. </div>
  1200. `;
  1201. }
  1202. }
  1203. });
  1204. }
  1205. }
  1206. } else if (person.matches.spouse && person.matches.spouse.length > 0) {
  1207. const spouse = person.matches.spouse[0];
  1208. const relTypeSelect = form.querySelector('[name="relation_type"]');
  1209. if (relTypeSelect) {
  1210. // Set the related member
  1211. document.getElementById('related-member-display').value = spouse.name;
  1212. document.getElementById('related_mid').value = spouse.id;
  1213. // Set relation type to spouse
  1214. relTypeSelect.value = '10'; // 夫妻
  1215. }
  1216. }
  1217. }
  1218. // --- Show Details Panel ---
  1219. const detailContainer = document.getElementById('aiCurrentDetail');
  1220. const detailContent = document.getElementById('aiDetailContent');
  1221. let html = '<ul class="list-unstyled mb-0 font-monospace" style="font-size: 0.85rem;">';
  1222. const getLabel = (k) => fieldMapping[k] || (k === 'children' ? '子女' : k);
  1223. // 遍历属性显示
  1224. for (const key in person) {
  1225. // 隐藏内部属性
  1226. if (key.startsWith('_')) continue;
  1227. let val = person[key];
  1228. const label = getLabel(key);
  1229. // 特殊处理 children
  1230. if (key === 'children') {
  1231. if (Array.isArray(val) && val.length > 0) {
  1232. let childrenHtml = '<div class="d-flex flex-wrap gap-1 mt-1">';
  1233. val.forEach(child => {
  1234. // 使用 child._originalIndex 进行跳转填充
  1235. 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>`;
  1236. });
  1237. childrenHtml += '</div>';
  1238. html += `<li class="mb-1"><span class="text-info opacity-75">${label}:</span> ${childrenHtml}</li>`;
  1239. }
  1240. continue;
  1241. }
  1242. // 默认显示
  1243. if (!val || val === '') val = '-';
  1244. html += `<li class="mb-1"><span class="text-info opacity-75">${label}:</span> <span class="text-white ms-1">${val}</span></li>`;
  1245. }
  1246. html += '</ul>';
  1247. detailContent.innerHTML = html;
  1248. detailContainer.style.display = 'block';
  1249. // Visual feedback
  1250. const btn = document.getElementById(`btn-fill-${index}`);
  1251. if(btn) {
  1252. const originalHtml = btn.innerHTML;
  1253. btn.innerHTML = '<i class="bi bi-check"></i> 已填';
  1254. btn.classList.remove('btn-outline-info');
  1255. btn.classList.add('btn-info', 'text-white');
  1256. setTimeout(() => {
  1257. btn.innerHTML = originalHtml;
  1258. btn.classList.add('btn-outline-info');
  1259. btn.classList.remove('btn-info', 'text-white');
  1260. }, 1000);
  1261. }
  1262. }
  1263. // --- Pre-fill Logic from Backend (Async AI Result) ---
  1264. const prefilledContent = {{ prefilled_content | tojson | safe if prefilled_content else 'null' }};
  1265. const sourceOssUrl = "{{ source_oss_url if source_oss_url else '' }}";
  1266. const sourceRecordId = "{{ source_record_id if source_record_id else '' }}";
  1267. if (prefilledContent && sourceOssUrl) {
  1268. // We have prefilled content from DB, simulate "Recognize Image" success
  1269. document.addEventListener('DOMContentLoaded', async () => {
  1270. // Wait a bit for UI to settle
  1271. setTimeout(async () => {
  1272. // Find image index
  1273. const imgIndex = images.findIndex(img => img.url === sourceOssUrl);
  1274. if (imgIndex !== -1) {
  1275. currentIndex = imgIndex;
  1276. updateDisplay();
  1277. }
  1278. // Parse and display results
  1279. try {
  1280. let data = prefilledContent;
  1281. if (typeof data === 'string') {
  1282. try {
  1283. data = JSON.parse(data);
  1284. } catch(e) {
  1285. console.error("Prefilled content parse error", e);
  1286. return;
  1287. }
  1288. }
  1289. if (!Array.isArray(data)) data = [data];
  1290. await processAiData(data);
  1291. // Open the log panel to show results
  1292. const aiPanel = document.getElementById('aiLogPanel');
  1293. if (aiPanel) aiPanel.style.display = 'block';
  1294. const status = document.getElementById('reasoningStatus');
  1295. if(status) {
  1296. status.textContent = '已加载历史解析';
  1297. status.className = 'badge bg-success ms-2';
  1298. }
  1299. const logContent = document.getElementById('aiLogContent');
  1300. if(logContent) logContent.textContent = "已加载历史 AI 解析记录。";
  1301. } catch (e) {
  1302. console.error("Error processing prefilled content", e);
  1303. }
  1304. }, 500);
  1305. });
  1306. } else {
  1307. // No prefilled content, initialize display for the first image
  1308. document.addEventListener('DOMContentLoaded', () => {
  1309. updateDisplay();
  1310. });
  1311. }
  1312. // --- Name Cleaning Logic (Matching Backend) ---
  1313. // 仅做繁 -> 简转换,不动姓氏/“公”处理,用于配偶等非留氏族人
  1314. function manualSimplify(text) {
  1315. if (!text) return text;
  1316. text = text.trim();
  1317. const mapping = {
  1318. '學': '学', '國': '国', '萬': '万', '寶': '宝', '興': '兴',
  1319. '華': '华', '會': '会', '葉': '叶', '藝': '艺', '號': '号',
  1320. '處': '处', '見': '见', '視': '视', '言': '言', '語': '语',
  1321. '貝': '贝', '車': '车', '長': '长', '門': '门', '韋': '韦',
  1322. '頁': '页', '風': '风', '飛': '飞', '食': '食', '馬': '马',
  1323. '魚': '鱼', '鳥': '鸟', '麥': '麦', '黃': '黄', '齊': '齐',
  1324. '齒': '齿', '龍': '龙', '龜': '龟', '壽': '寿', '榮': '荣',
  1325. '愛': '爱', '慶': '庆', '衛': '卫', '賢': '贤', '義': '义',
  1326. '禮': '礼', '樂': '乐', '靈': '灵', '滅': '灭', '氣': '气',
  1327. '智': '智', '信': '信', '仁': '仁', '勇': '勇', '嚴': '严',
  1328. '劉': '刘'
  1329. };
  1330. let result = '';
  1331. for (const ch of text) {
  1332. result += mapping[ch] || ch;
  1333. }
  1334. return result;
  1335. }
  1336. // 留氏本人姓名清洗:在 manualSimplify 基础上,处理“留”姓和“公”
  1337. function cleanName(name) {
  1338. if (!name) return name;
  1339. name = manualSimplify(name);
  1340. const exceptions = ['学公', '留学公'];
  1341. if (exceptions.includes(name)) {
  1342. if (!name.startsWith('留')) {
  1343. name = '留' + name;
  1344. }
  1345. return name;
  1346. }
  1347. // Remove '公' suffix
  1348. if (name.endsWith('公')) {
  1349. name = name.slice(0, -1);
  1350. }
  1351. // Ensure '留' prefix
  1352. if (!name.startsWith('留')) {
  1353. name = '留' + name;
  1354. }
  1355. return name;
  1356. }
  1357. function isFemaleSex(sexValue) {
  1358. if (sexValue === null || sexValue === undefined) return false;
  1359. const s = String(sexValue).trim().toLowerCase();
  1360. return s === '女' || s === '2' || s === 'female' || s === 'f';
  1361. }
  1362. function normalizeLookupName(name) {
  1363. if (!name) return '';
  1364. return manualSimplify(String(name)).trim();
  1365. }
  1366. // Extracted function to process AI data and render tree
  1367. async function processAiData(data) {
  1368. const spouseNameSet = new Set();
  1369. data.forEach(p => {
  1370. const n = normalizeLookupName(p.spouse_name);
  1371. if (n) spouseNameSet.add(n);
  1372. });
  1373. // Clean Names First
  1374. data.forEach(p => {
  1375. // Determine "Original" (Raw) and "Simplified" (Cleaned)
  1376. let rawName = p.original_name || p.name;
  1377. let simName = p.name || p.original_name; // Prefer AI simplified name; fallback to raw
  1378. const ownName1 = normalizeLookupName(p.name);
  1379. const ownName2 = normalizeLookupName(p.original_name);
  1380. const isFemaleSpouse = isFemaleSex(p.sex) && (
  1381. !!normalizeLookupName(p.spouse_name) ||
  1382. (ownName1 && spouseNameSet.has(ownName1)) ||
  1383. (ownName2 && spouseNameSet.has(ownName2))
  1384. );
  1385. // 女性配偶:只繁转简,不拼接“留”;其他人维持原规则
  1386. p.simplified_name = isFemaleSpouse ? manualSimplify(simName) : cleanName(simName);
  1387. // Set the name to be the Raw Name for storage in 'name' column
  1388. p.name = rawName;
  1389. // 父亲:同族,用 cleanName(加“留”、去“公”)
  1390. if (p.father_name) p.father_name = cleanName(p.father_name);
  1391. // 配偶:只做繁体 -> 简体,不拼接“留”姓
  1392. if (p.spouse_name) p.spouse_name = manualSimplify(p.spouse_name);
  1393. });
  1394. // Call Relation Check API
  1395. try {
  1396. // Send simplified_name for checking relations if available, or name?
  1397. // The API checks against DB 'name' column.
  1398. // Wait, DB 'name' column is now Traditional Raw.
  1399. // But existing data in DB is Simplified Cleaned.
  1400. // New data will be Traditional Raw in 'name', Simplified Cleaned in 'simplified_name'.
  1401. // The check_relations API uses `WHERE name IN (...)`.
  1402. // The AI returns `father_name` as Simplified (usually).
  1403. // So we are checking Simplified Father Name against...
  1404. // If DB 'name' is mixed (Old Simplified, New Traditional), this is messy.
  1405. // But `check_relations` logic:
  1406. // `names_to_check.add(p['father_name'])` -> Simplified.
  1407. // `SELECT ... WHERE name IN ...`
  1408. // If DB 'name' contains Traditional, we won't find match if we search Simplified.
  1409. // Unless we search `simplified_name` column too?
  1410. // I should update `check_relations` in app.py to search both `name` and `simplified_name`.
  1411. const checkRes = await fetch('/manager/api/check_relations', {
  1412. method: 'POST',
  1413. headers: { 'Content-Type': 'application/json' },
  1414. body: JSON.stringify({ people: data })
  1415. });
  1416. const checkResult = await checkRes.json();
  1417. if (checkResult.success && checkResult.matches) {
  1418. // Merge matches into data
  1419. for (const idx in checkResult.matches) {
  1420. const match = checkResult.matches[idx];
  1421. if (data[idx]) {
  1422. data[idx].matches = match;
  1423. }
  1424. }
  1425. }
  1426. } catch (e) {
  1427. console.warn("Auto-linking failed:", e);
  1428. }
  1429. currentParsedPeople = data;
  1430. document.getElementById('resultCount').innerText = data.length;
  1431. // Update Button State to "View Results"
  1432. updateAiButtonState(true);
  1433. // Build Relationship Tree
  1434. const personMap = {};
  1435. const roots = [];
  1436. // 1. Initialize map
  1437. data.forEach((p, index) => {
  1438. p._originalIndex = index; // Store original index for fillForm
  1439. p.children = [];
  1440. // Use simplified_name as key if available, otherwise name (for consistent lookup)
  1441. const lookupKey = p.simplified_name || p.name;
  1442. personMap[lookupKey] = p;
  1443. });
  1444. // 2. Build Hierarchy
  1445. data.forEach(p => {
  1446. let parentFound = false;
  1447. if (p.father_name) {
  1448. // Try exact match using simplified name (since father_name is usually simplified)
  1449. let father = personMap[p.father_name];
  1450. // Try loose match
  1451. if (!father) {
  1452. for (const name in personMap) {
  1453. if (name.includes(p.father_name) || p.father_name.includes(name)) {
  1454. father = personMap[name];
  1455. break;
  1456. }
  1457. }
  1458. }
  1459. if (father && father !== p) {
  1460. father.children.push(p);
  1461. parentFound = true;
  1462. }
  1463. }
  1464. if (!parentFound) {
  1465. roots.push(p);
  1466. }
  1467. });
  1468. // 3. Recursive Render Function
  1469. function renderNode(p, level = 0) {
  1470. const indent = level * 20;
  1471. let html = `
  1472. <div class="card bg-dark border-secondary mb-1" style="margin-left: ${indent}px; background-color: #2c3034;">
  1473. <div class="card-body p-2 d-flex justify-content-between align-items-center">
  1474. <div class="text-white">
  1475. <div class="fw-bold">
  1476. ${level > 0 ? '<i class="bi bi-arrow-return-right text-secondary me-1"></i>' : ''}
  1477. ${p.name || '未知姓名'}
  1478. <span class="badge bg-secondary text-light ms-1" style="font-size: 0.7rem">${p.sex || '-'}</span>
  1479. </div>
  1480. <div class="small text-white-50" style="font-size: 0.75rem; padding-left: ${level > 0 ? 18 : 0}px;">
  1481. ${p.generation ? '第'+p.generation+'世 ' : ''}
  1482. ${p.father_name ? '父:'+p.father_name : ''}
  1483. </div>
  1484. </div>
  1485. <button id="btn-fill-${p._originalIndex}"
  1486. class="btn btn-sm ${p.is_imported ? 'btn-success disabled' : 'btn-outline-info'} text-nowrap ms-2"
  1487. onclick="${p.is_imported ? '' : `fillForm(${p._originalIndex})`}">
  1488. ${p.is_imported ? '<i class="bi bi-check-lg"></i> 已录入' : '<i class="bi bi-pencil-square"></i> 填充'}
  1489. </button>
  1490. </div>
  1491. </div>
  1492. `;
  1493. if (p.children && p.children.length > 0) {
  1494. p.children.forEach(child => {
  1495. html += renderNode(child, level + 1);
  1496. });
  1497. }
  1498. return html;
  1499. }
  1500. // Render List
  1501. const resultList = document.getElementById('aiResultList');
  1502. const resultSection = document.getElementById('aiResultSection');
  1503. resultList.innerHTML = '';
  1504. // Fix: Use data directly if root finding logic fails or returns empty but data exists
  1505. if (roots.length === 0 && data.length > 0) {
  1506. // Just dump everything flat if tree building fails
  1507. data.forEach(p => resultList.innerHTML += renderNode(p, 0));
  1508. } else {
  1509. roots.forEach(p => {
  1510. resultList.innerHTML += renderNode(p, 0);
  1511. });
  1512. }
  1513. resultSection.style.display = 'block';
  1514. }
  1515. async function recognizeImage() {
  1516. if (images.length === 0) {
  1517. alert('没有可用的图片');
  1518. return;
  1519. }
  1520. const currentImg = images[currentIndex];
  1521. const btn = document.getElementById('aiBtn');
  1522. const originalContent = btn.innerHTML;
  1523. const logPanel = document.getElementById('aiLogPanel');
  1524. const logContent = document.getElementById('aiLogContent');
  1525. const resultSection = document.getElementById('aiResultSection');
  1526. const resultList = document.getElementById('aiResultList');
  1527. const reasoningStatus = document.getElementById('reasoningStatus');
  1528. btn.disabled = true;
  1529. btn.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> 识别中...';
  1530. // Reset UI
  1531. logContent.textContent = '';
  1532. resultList.innerHTML = '';
  1533. resultSection.style.display = 'none';
  1534. logPanel.style.display = 'block';
  1535. reasoningStatus.textContent = '连接中...';
  1536. reasoningStatus.className = 'badge bg-secondary ms-2';
  1537. // Ensure reasoning panel is open
  1538. const collapseReasoning = document.getElementById('collapseReasoning');
  1539. if (collapseReasoning && !collapseReasoning.classList.contains('show')) {
  1540. new bootstrap.Collapse(collapseReasoning, { show: true });
  1541. }
  1542. // Retry logic function
  1543. async function fetchAndParse(url, retryCount = 0) {
  1544. const MAX_RETRIES = 2;
  1545. let fullText = '';
  1546. let jsonPart = '';
  1547. let hasJsonStarted = false;
  1548. try {
  1549. if (retryCount > 0) {
  1550. logContent.textContent = `\n[System] 解析失败,正在进行第 ${retryCount} 次重试...\n` + logContent.textContent;
  1551. reasoningStatus.textContent = `重试 ${retryCount}...`;
  1552. }
  1553. const response = await fetch('/manager/api/recognize_image', {
  1554. method: 'POST',
  1555. headers: { 'Content-Type': 'application/json' },
  1556. body: JSON.stringify({ image_url: url })
  1557. });
  1558. if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
  1559. const reader = response.body.getReader();
  1560. const decoder = new TextDecoder();
  1561. const separator = "|||JSON_START|||";
  1562. while (true) {
  1563. const { value, done } = await reader.read();
  1564. if (done) break;
  1565. const chunk = decoder.decode(value, { stream: true });
  1566. fullText += chunk;
  1567. // Only update display if not parsing JSON part yet or just started
  1568. if (!hasJsonStarted) {
  1569. const sepIndex = fullText.indexOf(separator);
  1570. if (sepIndex !== -1) {
  1571. hasJsonStarted = true;
  1572. reasoningStatus.textContent = '解析中...';
  1573. reasoningStatus.className = 'badge bg-info ms-2';
  1574. // Split content for display - only once
  1575. const reasoningPart = fullText.substring(0, sepIndex);
  1576. logContent.textContent = reasoningPart;
  1577. if (collapseReasoning) {
  1578. new bootstrap.Collapse(collapseReasoning, { hide: true });
  1579. }
  1580. } else {
  1581. // Update reasoning text
  1582. logContent.textContent = fullText;
  1583. logContent.scrollTop = logContent.scrollHeight;
  1584. }
  1585. }
  1586. }
  1587. // Parsing Logic
  1588. if (hasJsonStarted) {
  1589. const sepIndex = fullText.indexOf(separator);
  1590. jsonPart = fullText.substring(sepIndex + separator.length);
  1591. reasoningStatus.textContent = '完成';
  1592. reasoningStatus.className = 'badge bg-success ms-2';
  1593. } else {
  1594. // Fallback
  1595. jsonPart = fullText;
  1596. }
  1597. // Clean JSON
  1598. // 1. Try finding [...] array
  1599. let start = jsonPart.indexOf('[');
  1600. let end = jsonPart.lastIndexOf(']');
  1601. // 2. If not found, try finding {...} object and wrap it
  1602. let isSingleObject = false;
  1603. if (start === -1 || end === -1 || end <= start) {
  1604. start = jsonPart.indexOf('{');
  1605. end = jsonPart.lastIndexOf('}');
  1606. isSingleObject = true;
  1607. }
  1608. if (start !== -1 && end !== -1 && end > start) {
  1609. jsonPart = jsonPart.substring(start, end + 1);
  1610. } else {
  1611. // Try to extract any JSON-like array/object structure using regex as fallback
  1612. const jsonMatch = jsonPart.match(/(\[.*\]|\{.*\})/s);
  1613. if (jsonMatch) {
  1614. jsonPart = jsonMatch[0];
  1615. if (jsonPart.trim().startsWith('{')) isSingleObject = true;
  1616. } else {
  1617. // No valid JSON structure found
  1618. console.warn("No JSON brackets found in:", jsonPart);
  1619. throw new Error("未找到有效的 JSON 数据结构");
  1620. }
  1621. }
  1622. let data;
  1623. try {
  1624. // Pre-clean: Remove common markdown code block markers if stuck inside
  1625. jsonPart = jsonPart.replace(/^```json\s*/, '').replace(/```$/, '');
  1626. data = JSON.parse(jsonPart);
  1627. } catch (e) {
  1628. // Attempt to fix common JSON errors (e.g. trailing commas, unclosed strings) - simplified
  1629. console.error("JSON parse error. Content:", jsonPart);
  1630. // Force retry on parse error
  1631. throw new Error("JSON 格式解析错误");
  1632. }
  1633. if (isSingleObject && !Array.isArray(data)) {
  1634. data = [data]; // Normalize to array
  1635. } else if (!Array.isArray(data)) {
  1636. data = [data];
  1637. }
  1638. return data;
  1639. } catch (error) {
  1640. if (retryCount < MAX_RETRIES) {
  1641. // Wait 1s and retry
  1642. await new Promise(r => setTimeout(r, 1000));
  1643. return fetchAndParse(url, retryCount + 1);
  1644. }
  1645. throw error;
  1646. }
  1647. }
  1648. try {
  1649. const data = await fetchAndParse(currentImg.url);
  1650. // Use shared processing function
  1651. await processAiData(data);
  1652. // Update local state for persistence during session
  1653. if (images[currentIndex]) {
  1654. images[currentIndex].ai_status = 2;
  1655. images[currentIndex].ai_content = data;
  1656. }
  1657. } catch (error) {
  1658. console.error(error);
  1659. // Append error to log instead of overwriting valid reasoning
  1660. logContent.textContent += `\n\n[Error] ${error.message}`;
  1661. alert('AI 识别过程失败,请重试。\n错误详情: ' + error.message);
  1662. } finally {
  1663. btn.innerHTML = originalContent;
  1664. btn.disabled = false;
  1665. }
  1666. }
  1667. // Check for duplicate name
  1668. let nameCheckTimeout = null;
  1669. const nameInput = document.getElementById('nameInput');
  1670. const nameCheckResult = document.getElementById('nameCheckResult');
  1671. if (nameInput) {
  1672. nameInput.addEventListener('input', function() {
  1673. clearTimeout(nameCheckTimeout);
  1674. const nameVal = this.value.trim();
  1675. if (!nameVal) {
  1676. nameCheckResult.innerHTML = '';
  1677. return;
  1678. }
  1679. nameCheckTimeout = setTimeout(() => {
  1680. fetch(`/manager/api/check_name?name=${encodeURIComponent(nameVal)}`)
  1681. .then(r => r.json())
  1682. .then(data => {
  1683. if (data.success && data.exists) {
  1684. let html = `<div class="alert alert-warning py-2 mb-0 mt-2 small">
  1685. <i class="bi bi-exclamation-triangle-fill"></i> 发现 <strong>${data.matches.length}</strong> 个同名记录,请确认是否为同一人:
  1686. <ul class="mb-0 mt-1 ps-3">`;
  1687. data.matches.forEach(m => {
  1688. let sex = m.sex === 1 ? '男' : (m.sex === 2 ? '女' : '未知');
  1689. let deadStr = m.is_pass_away == 1 ? ' (已故)' : (m.is_pass_away == 2 ? ' (未知)' : '');
  1690. html += `<li><a href="/manager/member_detail/${m.id}" target="_blank" class="alert-link">${m.name}</a> - ${sex} - 出生: ${m.birthday_str}${deadStr}</li>`;
  1691. });
  1692. html += `</ul></div>`;
  1693. nameCheckResult.innerHTML = html;
  1694. } else {
  1695. nameCheckResult.innerHTML = '';
  1696. }
  1697. })
  1698. .catch(err => console.error('Error checking name:', err));
  1699. }, 600);
  1700. });
  1701. }
  1702. // Auto-link spouse from notes if female
  1703. const notesInput = document.querySelector('textarea[name="notes"]');
  1704. const sexSelect = document.querySelector('select[name="sex"]');
  1705. // Attach to window so fillForm can explicitly call it
  1706. window.checkSpouseInNotes = function() {
  1707. if (!notesInput || !sexSelect) return;
  1708. const val = notesInput.value;
  1709. // Check for father information
  1710. const fatherMatch = val.match(/父亲[::\s]*([^\s;;,,。]+)/);
  1711. if (fatherMatch && fatherMatch[1]) {
  1712. const fatherName = fatherMatch[1].trim();
  1713. const relationTypeSelect = document.querySelector('select[name="relation_type"]');
  1714. if (relationTypeSelect) {
  1715. // Find the father in the members list
  1716. fetch(`/manager/api/members?search=${encodeURIComponent(fatherName)}`)
  1717. .then(response => response.json())
  1718. .then(data => {
  1719. if (data.members && data.members.length > 0) {
  1720. // Find the best match
  1721. let bestMatch = null;
  1722. for (const member of data.members) {
  1723. const optName = member.name;
  1724. const normalizedOpt = optName.replace(/公$/, '').replace(/^留/, '');
  1725. const normalizedFather = fatherName.replace(/公$/, '').replace(/^留/, '');
  1726. if (optName === fatherName || normalizedOpt === normalizedFather ||
  1727. (normalizedOpt && normalizedFather && (normalizedOpt.includes(normalizedFather) || normalizedFather.includes(normalizedOpt)))) {
  1728. bestMatch = member;
  1729. break;
  1730. }
  1731. }
  1732. if (bestMatch) {
  1733. // Set the related member
  1734. document.getElementById('related-member-display').value = bestMatch.name;
  1735. document.getElementById('related_mid').value = bestMatch.id;
  1736. // Set relation type to father
  1737. relationTypeSelect.value = '1';
  1738. // Trigger the lineage generation reference display
  1739. const relatedMid = document.getElementById('related_mid').value;
  1740. if (relationTypeSelect.value == 1 && relatedMid) {
  1741. fetch(`/manager/api/member/${relatedMid}`)
  1742. .then(response => response.json())
  1743. .then(data => {
  1744. if (data.member && data.member.name_word_generation) {
  1745. // 显示父亲的世系世代
  1746. const lineageContainer = document.getElementById('lineage-generations-container');
  1747. const fatherLineageDiv = document.getElementById('father-lineage');
  1748. if (!fatherLineageDiv) {
  1749. const newDiv = document.createElement('div');
  1750. newDiv.id = 'father-lineage';
  1751. newDiv.className = 'father-lineage-hint';
  1752. newDiv.innerHTML = `
  1753. <div class="d-flex align-items-center">
  1754. <i class="bi bi-info-circle me-2 text-info"></i>
  1755. <div>
  1756. <strong class="text-info">父亲世系世代参考:</strong>
  1757. <span>${data.member.name_word_generation}</span>
  1758. </div>
  1759. </div>
  1760. `;
  1761. // Find the add button container
  1762. const addButtonContainer = document.querySelector('#lineage-generations-container .d-flex.justify-content-between.align-items-center');
  1763. if (addButtonContainer) {
  1764. // Insert after the add button container
  1765. addButtonContainer.parentNode.insertBefore(newDiv, addButtonContainer.nextSibling);
  1766. } else if (lineageContainer.firstChild) {
  1767. // Insert after the first child
  1768. lineageContainer.insertBefore(newDiv, lineageContainer.firstChild.nextSibling);
  1769. } else {
  1770. // Append to container
  1771. lineageContainer.appendChild(newDiv);
  1772. }
  1773. } else {
  1774. fatherLineageDiv.innerHTML = `
  1775. <div class="d-flex align-items-center">
  1776. <i class="bi bi-info-circle me-2 text-info"></i>
  1777. <div>
  1778. <strong class="text-info">父亲世系世代参考:</strong>
  1779. <span>${data.member.name_word_generation}</span>
  1780. </div>
  1781. </div>
  1782. `;
  1783. }
  1784. }
  1785. });
  1786. }
  1787. }
  1788. }
  1789. });
  1790. }
  1791. }
  1792. // Only check for spouse if female
  1793. if (sexSelect.value === '2') {
  1794. const spouseMatch = val.match(/配偶[::\s]*([^\s;;,,。]+)/);
  1795. if (spouseMatch && spouseMatch[1]) {
  1796. const spouseName = spouseMatch[1].trim();
  1797. const relationTypeSelect = document.querySelector('select[name="relation_type"]');
  1798. if (relationTypeSelect) {
  1799. // Find the spouse in the members list
  1800. fetch(`/manager/api/members?search=${encodeURIComponent(spouseName)}`)
  1801. .then(response => response.json())
  1802. .then(data => {
  1803. if (data.members && data.members.length > 0) {
  1804. // Find the best match
  1805. let bestMatch = null;
  1806. for (const member of data.members) {
  1807. const optName = member.name;
  1808. const normalizedOpt = optName.replace(/公$/, '').replace(/^留/, '');
  1809. const normalizedSpouse = spouseName.replace(/公$/, '').replace(/^留/, '');
  1810. if (optName === spouseName || normalizedOpt === normalizedSpouse ||
  1811. (normalizedOpt && normalizedSpouse && (normalizedOpt.includes(normalizedSpouse) || normalizedSpouse.includes(normalizedOpt)))) {
  1812. bestMatch = member;
  1813. break;
  1814. }
  1815. }
  1816. if (bestMatch) {
  1817. // Set the related member
  1818. document.getElementById('related-member-display').value = bestMatch.name;
  1819. document.getElementById('related_mid').value = bestMatch.id;
  1820. // Set relation type to spouse
  1821. relationTypeSelect.value = '10';
  1822. }
  1823. }
  1824. });
  1825. }
  1826. }
  1827. }
  1828. };
  1829. if (notesInput && sexSelect) {
  1830. notesInput.addEventListener('input', window.checkSpouseInNotes);
  1831. sexSelect.addEventListener('change', window.checkSpouseInNotes);
  1832. }
  1833. </script>
  1834. <script>
  1835. document.addEventListener('DOMContentLoaded', function() {
  1836. const container = document.getElementById('lineage-generations-container');
  1837. const addButton = document.getElementById('add-lineage');
  1838. const inputForm = document.getElementById('lineage-input-form');
  1839. const lineageInput = document.getElementById('lineage-input');
  1840. const confirmButton = document.getElementById('confirm-lineage');
  1841. const cancelButton = document.getElementById('cancel-lineage');
  1842. if (!container || !addButton || !inputForm || !lineageInput || !confirmButton || !cancelButton) return;
  1843. function addLineageTag(value) {
  1844. const tag = document.createElement('span');
  1845. 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';
  1846. tag.style.fontSize = '0.85rem';
  1847. 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}">`;
  1848. container.insertBefore(tag, inputForm);
  1849. }
  1850. container.addEventListener('click', function(e) {
  1851. const removeBtn = e.target.closest('.remove-lineage');
  1852. if (removeBtn) {
  1853. e.preventDefault();
  1854. e.stopPropagation();
  1855. const tag = removeBtn.closest('.lineage-tag');
  1856. if (tag) tag.remove();
  1857. }
  1858. });
  1859. addButton.addEventListener('click', function(e) {
  1860. e.preventDefault();
  1861. e.stopPropagation();
  1862. inputForm.classList.remove('d-none');
  1863. addButton.classList.add('d-none');
  1864. lineageInput.value = '';
  1865. lineageInput.focus();
  1866. });
  1867. function confirmInput() {
  1868. const value = lineageInput.value.trim();
  1869. if (value) {
  1870. addLineageTag(value);
  1871. }
  1872. lineageInput.value = '';
  1873. inputForm.classList.add('d-none');
  1874. addButton.classList.remove('d-none');
  1875. }
  1876. confirmButton.addEventListener('click', function(e) {
  1877. e.preventDefault();
  1878. e.stopPropagation();
  1879. confirmInput();
  1880. });
  1881. lineageInput.addEventListener('keydown', function(e) {
  1882. if (e.key === 'Enter') {
  1883. e.preventDefault();
  1884. e.stopPropagation();
  1885. confirmInput();
  1886. }
  1887. if (e.key === 'Escape') {
  1888. e.preventDefault();
  1889. lineageInput.value = '';
  1890. inputForm.classList.add('d-none');
  1891. addButton.classList.remove('d-none');
  1892. }
  1893. });
  1894. cancelButton.addEventListener('click', function(e) {
  1895. e.preventDefault();
  1896. e.stopPropagation();
  1897. lineageInput.value = '';
  1898. inputForm.classList.add('d-none');
  1899. addButton.classList.remove('d-none');
  1900. });
  1901. });
  1902. // 加载成员数据
  1903. function loadMembers(page = 1, search = '') {
  1904. console.log('Loading members...', { page, search });
  1905. fetch(`/manager/api/members?page=${page}&search=${encodeURIComponent(search)}`)
  1906. .then(response => {
  1907. console.log('Response status:', response.status);
  1908. return response.json();
  1909. })
  1910. .then(data => {
  1911. console.log('Response data:', data);
  1912. // Check if it's an error response
  1913. if (data.message && data.success === false) {
  1914. console.error('API error:', data.message);
  1915. // If unauthorized, redirect to login
  1916. if (data.message === 'Unauthorized') {
  1917. window.location.href = '/manager/login';
  1918. }
  1919. return;
  1920. }
  1921. // Handle success response - check if members and total exist
  1922. if (data.members !== undefined && data.total !== undefined) {
  1923. membersData = data.members;
  1924. totalMembers = data.total;
  1925. totalPages = Math.ceil(totalMembers / 10);
  1926. currentPage = page;
  1927. // 更新成员列表
  1928. updateMemberList();
  1929. // 更新分页
  1930. updatePagination();
  1931. // 更新总数
  1932. document.getElementById('total-members').textContent = totalMembers;
  1933. } else {
  1934. console.error('Invalid response structure:', data);
  1935. // Set default values
  1936. membersData = [];
  1937. totalMembers = 0;
  1938. totalPages = 1;
  1939. currentPage = 1;
  1940. updateMemberList();
  1941. updatePagination();
  1942. document.getElementById('total-members').textContent = 0;
  1943. }
  1944. })
  1945. .catch(error => {
  1946. console.error('Error loading members:', error);
  1947. });
  1948. }
  1949. // 更新成员列表
  1950. function updateMemberList() {
  1951. const memberList = document.getElementById('member-list');
  1952. memberList.innerHTML = '';
  1953. if (membersData.length === 0) {
  1954. memberList.innerHTML = '<div class="list-group-item text-center text-muted">暂无成员数据</div>';
  1955. return;
  1956. }
  1957. membersData.forEach(function(member) {
  1958. const item = document.createElement('div');
  1959. item.className = 'list-group-item list-group-item-action';
  1960. item.onclick = function() {
  1961. selectMemberById(member.id);
  1962. };
  1963. item.innerHTML = `
  1964. <div class="d-flex justify-content-between align-items-center">
  1965. <div>
  1966. <h6 class="mb-0">${member.name}</h6>
  1967. <small class="text-muted">ID: ${member.id} | ${member.sex === 1 ? '男' : '女'}</small>
  1968. </div>
  1969. <button type="button" class="btn btn-sm btn-outline-primary" onclick="event.stopPropagation(); selectMemberById(${member.id});">
  1970. 选择
  1971. </button>
  1972. </div>
  1973. `;
  1974. memberList.appendChild(item);
  1975. });
  1976. }
  1977. // 更新分页
  1978. function updatePagination() {
  1979. const pagination = document.querySelector('.pagination');
  1980. pagination.innerHTML = '';
  1981. // 上一页
  1982. const prevLi = document.createElement('li');
  1983. prevLi.className = `page-item ${currentPage === 1 ? 'disabled' : ''}`;
  1984. prevLi.innerHTML = `<a class="page-link" href="#" onclick="changePage(${currentPage - 1})">&laquo;</a>`;
  1985. pagination.appendChild(prevLi);
  1986. // 页码
  1987. for (let i = 1; i <= totalPages; i++) {
  1988. const li = document.createElement('li');
  1989. li.className = `page-item ${i === currentPage ? 'active' : ''}`;
  1990. li.innerHTML = `<a class="page-link" href="#" onclick="changePage(${i})">${i}</a>`;
  1991. pagination.appendChild(li);
  1992. }
  1993. // 下一页
  1994. const nextLi = document.createElement('li');
  1995. nextLi.className = `page-item ${currentPage === totalPages ? 'disabled' : ''}`;
  1996. nextLi.innerHTML = `<a class="page-link" href="#" onclick="changePage(${currentPage + 1})">&raquo;</a>`;
  1997. pagination.appendChild(nextLi);
  1998. }
  1999. // 改变页码
  2000. function changePage(page) {
  2001. if (page < 1 || page > totalPages) return;
  2002. const search = document.getElementById('member-search').value;
  2003. loadMembers(page, search);
  2004. }
  2005. // 搜索成员
  2006. function searchMembers() {
  2007. const search = document.getElementById('member-search').value;
  2008. loadMembers(1, search);
  2009. }
  2010. // 选择成员
  2011. function selectMember(member) {
  2012. document.getElementById('related-member-display').value = member.name;
  2013. document.getElementById('related_mid').value = member.id;
  2014. // 检查是否是父子关系,如果是,显示父亲的世系世代
  2015. const relationType = document.querySelector('select[name="relation_type"]').value;
  2016. if (relationType == 1) { // 父子关系
  2017. fetch(`/manager/api/member/${member.id}`)
  2018. .then(response => response.json())
  2019. .then(data => {
  2020. if (data.member && data.member.name_word_generation) {
  2021. // 显示父亲的世系世代
  2022. const lineageContainer = document.getElementById('lineage-generations-container');
  2023. const fatherLineageDiv = document.getElementById('father-lineage');
  2024. if (!fatherLineageDiv) {
  2025. const newDiv = document.createElement('div');
  2026. newDiv.id = 'father-lineage';
  2027. newDiv.className = 'father-lineage-hint';
  2028. newDiv.innerHTML = `
  2029. <div class="d-flex align-items-center">
  2030. <i class="bi bi-info-circle me-2 text-info"></i>
  2031. <div>
  2032. <strong class="text-info">父亲世系世代参考:</strong>
  2033. <span>${data.member.name_word_generation}</span>
  2034. </div>
  2035. </div>
  2036. `;
  2037. // Find the add button container
  2038. const addButtonContainer = document.querySelector('#lineage-generations-container .d-flex.justify-content-between.align-items-center');
  2039. if (addButtonContainer) {
  2040. // Insert after the add button container
  2041. addButtonContainer.parentNode.insertBefore(newDiv, addButtonContainer.nextSibling);
  2042. } else if (lineageContainer.firstChild) {
  2043. // Insert after the first child
  2044. lineageContainer.insertBefore(newDiv, lineageContainer.firstChild.nextSibling);
  2045. } else {
  2046. // Append to container
  2047. lineageContainer.appendChild(newDiv);
  2048. }
  2049. } else {
  2050. fatherLineageDiv.innerHTML = `
  2051. <div class="d-flex align-items-center">
  2052. <i class="bi bi-info-circle me-2 text-info"></i>
  2053. <div>
  2054. <strong class="text-info">父亲世系世代参考:</strong>
  2055. <span>${data.member.name_word_generation}</span>
  2056. </div>
  2057. </div>
  2058. `;
  2059. }
  2060. }
  2061. });
  2062. }
  2063. // 关闭模态框
  2064. const modal = bootstrap.Modal.getInstance(document.getElementById('memberSelectModal'));
  2065. modal.hide();
  2066. }
  2067. // 通过ID选择成员
  2068. function selectMemberById(memberId) {
  2069. // 先在当前加载的成员中查找
  2070. const member = membersData.find(m => m.id === memberId);
  2071. if (member) {
  2072. selectMember(member);
  2073. } else {
  2074. // 如果没找到,从API获取
  2075. fetch(`/manager/api/member/${memberId}`)
  2076. .then(response => response.json())
  2077. .then(data => {
  2078. if (data.member) {
  2079. selectMember(data.member);
  2080. }
  2081. });
  2082. }
  2083. }
  2084. // 监听关系类型变化
  2085. document.addEventListener('DOMContentLoaded', function() {
  2086. // 监听关系类型变化
  2087. const relationTypeSelect = document.querySelector('select[name="relation_type"]');
  2088. if (relationTypeSelect) {
  2089. relationTypeSelect.addEventListener('change', function() {
  2090. const relatedMid = document.getElementById('related_mid').value;
  2091. if (this.value == 1 && relatedMid) {
  2092. // 如果选择了父子关系且已选择关联成员,显示父亲的世系世代
  2093. fetch(`/manager/api/member/${relatedMid}`)
  2094. .then(response => response.json())
  2095. .then(data => {
  2096. if (data.member && data.member.name_word_generation) {
  2097. const lineageContainer = document.getElementById('lineage-generations-container');
  2098. const fatherLineageDiv = document.getElementById('father-lineage');
  2099. if (!fatherLineageDiv) {
  2100. const newDiv = document.createElement('div');
  2101. newDiv.id = 'father-lineage';
  2102. newDiv.className = 'father-lineage-hint';
  2103. newDiv.innerHTML = `
  2104. <div class="d-flex align-items-center">
  2105. <i class="bi bi-info-circle me-2 text-info"></i>
  2106. <div>
  2107. <strong class="text-info">父亲世系世代参考:</strong>
  2108. <span>${data.member.name_word_generation}</span>
  2109. </div>
  2110. </div>
  2111. `;
  2112. // Find the add button container
  2113. const addButtonContainer = document.querySelector('#lineage-generations-container .d-flex.justify-content-between.align-items-center');
  2114. if (addButtonContainer) {
  2115. // Insert after the add button container
  2116. addButtonContainer.parentNode.insertBefore(newDiv, addButtonContainer.nextSibling);
  2117. } else if (lineageContainer.firstChild) {
  2118. // Insert after the first child
  2119. lineageContainer.insertBefore(newDiv, lineageContainer.firstChild.nextSibling);
  2120. } else {
  2121. // Append to container
  2122. lineageContainer.appendChild(newDiv);
  2123. }
  2124. } else {
  2125. fatherLineageDiv.innerHTML = `
  2126. <div class="d-flex align-items-center">
  2127. <i class="bi bi-info-circle me-2 text-info"></i>
  2128. <div>
  2129. <strong class="text-info">父亲世系世代参考:</strong>
  2130. <span>${data.member.name_word_generation}</span>
  2131. </div>
  2132. </div>
  2133. `;
  2134. }
  2135. }
  2136. });
  2137. }
  2138. });
  2139. }
  2140. // 监听成员选择模态框显示
  2141. const memberSelectModal = document.getElementById('memberSelectModal');
  2142. memberSelectModal.addEventListener('shown.bs.modal', function() {
  2143. loadMembers();
  2144. });
  2145. });
  2146. </script>
  2147. {% endblock %}