add_member.html 117 KB

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