add_member.html 120 KB

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