add_member.html 86 KB

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