add_member.html 103 KB

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