add_member.html 91 KB

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