shareAiConsult.html 61 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949
  1. <!DOCTYPE html>
  2. <html lang="zh-CN">
  3. <head>
  4. <meta charset="utf-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover">
  6. <meta name="format-detection" content="telephone=no">
  7. <title>与U宝对话</title>
  8. <meta property="og:title" content="和U宝的对话">
  9. <meta property="og:description" content="点击查看对话内容">
  10. <meta property="og:site_name" content="U店在哪">
  11. <meta name="application-name" content="U店在哪">
  12. <link rel="icon" type="image/png" href="https://alien-volume.oss-cn-beijing.aliyuncs.com/icon/ubao.png">
  13. <link rel="apple-touch-icon" href="https://alien-volume.oss-cn-beijing.aliyuncs.com/icon/ubao.png">
  14. <style>
  15. :root {
  16. --bg: #f4f6fb;
  17. --text: #151515;
  18. --muted: #aaaaaa;
  19. --orange: #f47d1f;
  20. --safe-bottom: env(safe-area-inset-bottom, 0px);
  21. }
  22. * {
  23. margin: 0;
  24. padding: 0;
  25. box-sizing: border-box;
  26. }
  27. html {
  28. height: 100%;
  29. -webkit-tap-highlight-color: transparent;
  30. overflow: hidden;
  31. }
  32. body {
  33. font-family: -apple-system, BlinkMacSystemFont, "PingFang SC", "Microsoft YaHei", sans-serif;
  34. background: var(--bg);
  35. color: var(--text);
  36. height: 100vh;
  37. display: flex;
  38. flex-direction: column;
  39. overflow: hidden;
  40. }
  41. #main {
  42. flex: 1;
  43. min-height: 0;
  44. overflow-x: hidden;
  45. overflow-y: auto;
  46. -webkit-overflow-scrolling: touch;
  47. padding-bottom: calc(100px + var(--safe-bottom));
  48. }
  49. .hero {
  50. padding: 16px 15px 0;
  51. }
  52. .hero__title {
  53. font-size: 20px;
  54. font-weight: 700;
  55. line-height: 1.4;
  56. word-break: break-word;
  57. }
  58. .hero__meta {
  59. margin-top: 8px;
  60. font-size: 12px;
  61. color: var(--muted);
  62. line-height: 1.4;
  63. }
  64. .hero__divider {
  65. margin-top: 14px;
  66. height: 1px;
  67. background: rgba(170, 170, 170, 0.25);
  68. }
  69. .conversation {
  70. padding: 14px 15px 8px;
  71. }
  72. .scroll-spacer {
  73. height: calc(72px + var(--safe-bottom));
  74. flex-shrink: 0;
  75. }
  76. .conversation .row:last-child {
  77. margin-bottom: 0;
  78. }
  79. .row {
  80. display: flex;
  81. margin-bottom: 12px;
  82. }
  83. .row--user {
  84. justify-content: flex-end;
  85. }
  86. .row--ai {
  87. justify-content: flex-start;
  88. }
  89. .user-bubble {
  90. position: relative;
  91. max-width: 78%;
  92. padding: 10px 14px;
  93. background: var(--orange);
  94. border-radius: 8px 8px 2px 8px;
  95. color: #fff;
  96. font-size: 15px;
  97. font-weight: 500;
  98. line-height: 1.5;
  99. white-space: pre-wrap;
  100. word-break: break-word;
  101. }
  102. .user-bubble::after {
  103. content: "";
  104. position: absolute;
  105. right: -6px;
  106. bottom: 8px;
  107. width: 0;
  108. height: 0;
  109. border-style: solid;
  110. border-width: 6px 0 6px 7px;
  111. border-color: transparent transparent transparent var(--orange);
  112. }
  113. .ai-card {
  114. width: 100%;
  115. padding: 14px 13px;
  116. background: #fff;
  117. border-radius: 12px;
  118. box-shadow: 0 1px 6px rgba(0, 0, 0, 0.04);
  119. }
  120. .ai-card__text {
  121. font-size: 14px;
  122. line-height: 1.65;
  123. white-space: pre-wrap;
  124. word-break: break-word;
  125. text-align: left;
  126. }
  127. .ai-card::after {
  128. content: "本回答由AI生成,内容仅供参考,请仔细甄别";
  129. display: block;
  130. margin-top: 8px;
  131. font-size: 12px;
  132. line-height: 1.5;
  133. color: #999999;
  134. text-align: left;
  135. font-style: italic;
  136. }
  137. .ai-card__image {
  138. display: block;
  139. max-width: 100%;
  140. height: auto;
  141. margin: 8px 0;
  142. border-radius: 6px;
  143. }
  144. .user-bubble__image {
  145. display: block;
  146. max-width: 180px;
  147. border-radius: 4px;
  148. }
  149. .user-bubble--images {
  150. padding: 8px 10px;
  151. }
  152. .user-bubble__images {
  153. display: flex;
  154. flex-wrap: nowrap;
  155. gap: 8px;
  156. overflow-x: auto;
  157. overflow-y: hidden;
  158. -webkit-overflow-scrolling: touch;
  159. scrollbar-width: none;
  160. -ms-overflow-style: none;
  161. }
  162. .user-bubble__images::-webkit-scrollbar {
  163. display: none;
  164. }
  165. .user-bubble__images .user-bubble__image {
  166. flex: 0 0 auto;
  167. width: 72px;
  168. height: 72px;
  169. max-width: none;
  170. object-fit: cover;
  171. border-radius: 8px;
  172. }
  173. .fallback-card {
  174. margin: 14px 15px 0;
  175. padding: 14px 13px;
  176. background: #fff;
  177. border-radius: 8px;
  178. box-shadow: 0 1px 6px rgba(0, 0, 0, 0.04);
  179. }
  180. .fallback-card .ai-card__text {
  181. font-size: 14px;
  182. line-height: 1.65;
  183. white-space: pre-wrap;
  184. word-break: break-word;
  185. text-align: left;
  186. }
  187. .empty {
  188. padding: 48px 20px;
  189. text-align: center;
  190. color: var(--muted);
  191. font-size: 14px;
  192. }
  193. .fab-wrap {
  194. position: fixed;
  195. left: 0;
  196. right: 0;
  197. bottom: 0;
  198. z-index: 200;
  199. padding: 12px 24px calc(12px + var(--safe-bottom));
  200. background: linear-gradient(to top, rgba(255, 255, 255, 0.98) 70%, transparent);
  201. pointer-events: none;
  202. }
  203. .fab-dock__slot {
  204. width: 100%;
  205. max-width: 280px;
  206. height: 48px;
  207. margin: 0 auto;
  208. pointer-events: auto;
  209. }
  210. #openApp.fab {
  211. padding: 0 10px;
  212. -webkit-font-smoothing: antialiased;
  213. text-rendering: optimizeLegibility;
  214. }
  215. .fab__brand-clip {
  216. display: block;
  217. flex-shrink: 0;
  218. line-height: 0;
  219. }
  220. .fab__brand-img {
  221. display: block;
  222. height: 20px;
  223. width: auto;
  224. max-width: 90%;
  225. pointer-events: none;
  226. -webkit-user-drag: none;
  227. }
  228. .fab__label {
  229. font-size: 15px;
  230. line-height: 1;
  231. letter-spacing: 0.04em;
  232. white-space: nowrap;
  233. }
  234. #launch-btn {
  235. display: none;
  236. width: 100%;
  237. height: 48px;
  238. min-height: 48px;
  239. border-radius: 999px;
  240. overflow: hidden;
  241. opacity: 1;
  242. }
  243. body.is-wechat.wx-jssdk-ready #launch-btn {
  244. display: block;
  245. }
  246. body.is-wechat.wx-jssdk-ready #openApp {
  247. display: none !important;
  248. }
  249. .fab-wrap .fab {
  250. pointer-events: auto;
  251. }
  252. #openApp {
  253. touch-action: manipulation;
  254. }
  255. .fab {
  256. display: flex;
  257. align-items: center;
  258. justify-content: center;
  259. gap: 4px;
  260. width: 100%;
  261. max-width: 280px;
  262. margin: 0 auto;
  263. height: 48px;
  264. border: none;
  265. border-radius: 999px;
  266. background: linear-gradient(90deg, #ffb84c 0%, #ff6b3e 100%);
  267. color: #fff;
  268. font-size: 16px;
  269. font-weight: 600;
  270. box-shadow: 0 4px 16px rgba(255, 107, 62, 0.32);
  271. cursor: pointer;
  272. }
  273. .home-indicator {
  274. height: 5px;
  275. background: #000;
  276. border-radius: 3px;
  277. width: 134px;
  278. margin: 8px auto 4px;
  279. opacity: 0.2;
  280. }
  281. #openAppToast {
  282. display: none;
  283. position: fixed;
  284. left: 16px;
  285. right: 16px;
  286. bottom: calc(72px + var(--safe-bottom));
  287. z-index: 10001;
  288. padding: 10px 14px;
  289. font-size: 13px;
  290. line-height: 1.45;
  291. color: #fff;
  292. text-align: center;
  293. background: rgba(0, 0, 0, 0.78);
  294. border-radius: 8px;
  295. pointer-events: none;
  296. word-break: break-all;
  297. }
  298. .api-debug-btn {
  299. position: fixed;
  300. top: calc(12px + env(safe-area-inset-top, 0px));
  301. right: 12px;
  302. z-index: 10002;
  303. padding: 6px 10px;
  304. border: none;
  305. border-radius: 6px;
  306. background: rgba(0, 0, 0, 0.55);
  307. color: #fff;
  308. font-size: 12px;
  309. line-height: 1;
  310. cursor: pointer;
  311. }
  312. .api-debug-mask {
  313. display: none;
  314. position: fixed;
  315. inset: 0;
  316. z-index: 10003;
  317. background: rgba(0, 0, 0, 0.45);
  318. }
  319. .api-debug-mask.is-open {
  320. display: block;
  321. }
  322. .api-debug-modal {
  323. position: absolute;
  324. left: 12px;
  325. right: 12px;
  326. top: 50%;
  327. max-height: 80vh;
  328. transform: translateY(-50%);
  329. display: flex;
  330. flex-direction: column;
  331. background: #fff;
  332. border-radius: 12px;
  333. overflow: hidden;
  334. box-shadow: 0 8px 32px rgba(0, 0, 0, 0.18);
  335. }
  336. .api-debug-modal__header {
  337. display: flex;
  338. align-items: center;
  339. justify-content: space-between;
  340. padding: 14px 16px;
  341. border-bottom: 1px solid #eee;
  342. flex-shrink: 0;
  343. }
  344. .api-debug-modal__title {
  345. font-size: 16px;
  346. font-weight: 600;
  347. }
  348. .api-debug-modal__close {
  349. padding: 4px 8px;
  350. border: none;
  351. background: transparent;
  352. color: #666;
  353. font-size: 14px;
  354. cursor: pointer;
  355. }
  356. .api-debug-modal__body {
  357. flex: 1;
  358. min-height: 0;
  359. overflow-y: auto;
  360. -webkit-overflow-scrolling: touch;
  361. padding: 12px 16px 16px;
  362. }
  363. .api-debug-section {
  364. margin-bottom: 14px;
  365. }
  366. .api-debug-section:last-child {
  367. margin-bottom: 0;
  368. }
  369. .api-debug-section__label {
  370. margin-bottom: 6px;
  371. font-size: 13px;
  372. font-weight: 600;
  373. color: #333;
  374. }
  375. .api-debug-section__pre {
  376. margin: 0;
  377. padding: 10px 12px;
  378. background: #f5f6f8;
  379. border-radius: 8px;
  380. font-size: 12px;
  381. line-height: 1.5;
  382. white-space: pre-wrap;
  383. word-break: break-all;
  384. color: #222;
  385. font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
  386. }
  387. </style>
  388. </head>
  389. <body>
  390. <main id="main">
  391. <div class="empty">对话内容加载中…</div>
  392. </main>
  393. <div id="openAppToast" role="status" aria-live="polite"></div>
  394. <button type="button" class="api-debug-btn" id="apiDebugBtn" aria-label="查看接口信息">接口</button>
  395. <div class="api-debug-mask" id="apiDebugMask" aria-hidden="true">
  396. <div class="api-debug-modal" role="dialog" aria-labelledby="apiDebugTitle">
  397. <div class="api-debug-modal__header">
  398. <span class="api-debug-modal__title" id="apiDebugTitle">聊天记录接口</span>
  399. <button type="button" class="api-debug-modal__close" id="apiDebugClose">关闭</button>
  400. </div>
  401. <div class="api-debug-modal__body" id="apiDebugBody"></div>
  402. </div>
  403. </div>
  404. <div class="fab-wrap">
  405. <div class="fab-dock__slot">
  406. <!-- 与 secondShareGoods 相同顺序:openApp 在下,launch-btn 在上,避免挡住点击 -->
  407. <button type="button" class="fab" id="openApp" aria-label="和U宝继续聊">
  408. <span class="fab__brand-clip" aria-hidden="true">
  409. <img class="fab__brand-img" src="images/uCharts.png" alt="和U宝继续聊" decoding="async">
  410. </span>
  411. </button>
  412. <wx-open-launch-app id="launch-btn" appid="wxf5f1efe3a9f5012e" extinfo="">
  413. <script type="text/wxtag-template">
  414. <style>
  415. .wx-open-app-btn {
  416. display: flex;
  417. align-items: center;
  418. justify-content: center;
  419. width: 100%;
  420. height: 48px;
  421. margin: 0;
  422. padding: 0 10px;
  423. border: none;
  424. border-radius: 999px;
  425. background: linear-gradient(90deg, #ffb84c 0%, #ff6b3e 100%);
  426. box-shadow: 0 4px 16px rgba(255, 107, 62, 0.32);
  427. cursor: pointer;
  428. overflow: hidden;
  429. -webkit-tap-highlight-color: transparent;
  430. box-sizing: border-box;
  431. font-family: -apple-system, BlinkMacSystemFont, "PingFang SC", "Helvetica Neue", sans-serif;
  432. -webkit-font-smoothing: antialiased;
  433. }
  434. .wx-open-app-btn .fab__brand-clip {
  435. display: block;
  436. flex-shrink: 0;
  437. line-height: 0;
  438. }
  439. .wx-open-app-btn .fab__brand-img {
  440. display: block;
  441. height: 20px;
  442. width: auto;
  443. max-width: 90%;
  444. pointer-events: none;
  445. -webkit-user-drag: none;
  446. }
  447. </style>
  448. <button class="wx-open-app-btn" aria-label="和U宝继续聊">
  449. <span class="fab__brand-clip" aria-hidden="true">
  450. <img class="fab__brand-img" src="https://prod.ailien.shop/h5/HBuilderProjects/images/uCharts.png" alt="和U宝继续聊" decoding="async">
  451. </span>
  452. </button>
  453. </script>
  454. </wx-open-launch-app>
  455. </div>
  456. <div class="home-indicator" aria-hidden="true"></div>
  457. </div>
  458. <script src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
  459. <script>
  460. (function () {
  461. "use strict";
  462. var API_BASE = "https://prod.ailien.shop/alienStore";
  463. var WECHAT_MP_APP_ID = "wx412792c77f47babd";
  464. var WECHAT_OPEN_APP_ID = "wxf5f1efe3a9f5012e";
  465. var WECHAT_GET_WX_CONFIG_PATH = "/wx/getWxConfig";
  466. var H5_PAGE_BASE_FALLBACK = "https://prod.ailien.shop/h5/HBuilderProjects/";
  467. var WX_GET_CONFIG_SIGN_URL = H5_PAGE_BASE_FALLBACK + "shareAiConsult.html";
  468. var WECHAT_JS_SAFE_HOSTS = ["uat.ailien.shop", "prod.ailien.shop"];
  469. var APP_ANDROID_PACKAGE = "com.alien.Udianzaizhe";
  470. var APP_IOS_URL_SCHEME = "shopro://";
  471. var APP_UNI_AI_PATH = "pages/aiSearchResult/index";
  472. var AI_LEGAL_CONVERSATION_API =
  473. "https://prod.ailien.shop/ai/life-manager/api/v1/legal-consultation/history/conversation";
  474. var AI_UBAO_CONVERSATION_API =
  475. "https://prod.ailien.shop/ai/life-manager/api/v1/ubao-conversation/history/conversation";
  476. var sharePayloadCache = null;
  477. var conversationApiDebugInfo = null;
  478. var weChatJssdkConfigured = false;
  479. var wxConfigSignRetriedBaseUrl = false;
  480. var wxInitLastError = "";
  481. var wxJssdkInitPromise = null;
  482. function escHtml(s) {
  483. return String(s || "")
  484. .replace(/&/g, "&amp;")
  485. .replace(/</g, "&lt;")
  486. .replace(/>/g, "&gt;")
  487. .replace(/"/g, "&quot;");
  488. }
  489. var IMAGE_EXT = "(?:jpe?g|png|gif|webp|bmp|avif)";
  490. var IMAGE_URL_PATTERN =
  491. "https?:\\/\\/[^\\s))\\]]+\\." + IMAGE_EXT + "(?:\\?[^\\s))\\]]*)?";
  492. function isInsideImageUrlSyntax(full, offset) {
  493. if (offset >= 2 && full.slice(offset - 2, offset) === "](") return true;
  494. if (offset >= 1 && full[offset - 1] === "(") return true;
  495. if (offset >= 6 && full.slice(offset - 6, offset) === "{{IMG|") return true;
  496. return false;
  497. }
  498. /** AI 回复常见:店名(https://...jpg) — 转为可渲染的图片占位 */
  499. function embedInlineImageUrls(text) {
  500. if (text == null) return "";
  501. var t = String(text);
  502. t = t.replace(
  503. new RegExp("([^\\n((]+?)\\((" + IMAGE_URL_PATTERN + ")\\)", "gi"),
  504. function (_, label, url) {
  505. var name = String(label).trim();
  506. if (!name) return "\n\n{{IMG|" + url + "|}}\n\n";
  507. var alt = name.length > 24 ? "图片" : name.replace(/[\[\]]/g, "");
  508. return name + "\n\n{{IMG|" + url + "|" + alt + "}}\n\n";
  509. }
  510. );
  511. t = t.replace(
  512. new RegExp("\\((" + IMAGE_URL_PATTERN + ")\\)", "gi"),
  513. function (_, url) {
  514. return "\n\n{{IMG|" + url + "|}}\n\n";
  515. }
  516. );
  517. t = t.replace(new RegExp(IMAGE_URL_PATTERN, "gi"), function (url, offset, full) {
  518. if (isInsideImageUrlSyntax(full, offset)) return url;
  519. return "\n\n{{IMG|" + url + "|}}\n\n";
  520. });
  521. return t.replace(/\n{3,}/g, "\n\n");
  522. }
  523. function formatTextBlockHtml(text) {
  524. return escHtml(text).replace(/\n/g, "<br>");
  525. }
  526. function buildAiImageTag(url, alt) {
  527. var safeUrl = escHtml(url);
  528. var safeAlt = escHtml(alt || "图片");
  529. return (
  530. '<img class="ai-card__image" src="' +
  531. safeUrl +
  532. '" alt="' +
  533. safeAlt +
  534. '" loading="lazy" decoding="async" />'
  535. );
  536. }
  537. function renderAiContentHtml(text) {
  538. var t = embedInlineImageUrls(text);
  539. var html = "";
  540. var tokenRe = /\{\{IMG\|([^|]+)\|([^}]*)\}\}/g;
  541. var lastIndex = 0;
  542. var match;
  543. while ((match = tokenRe.exec(t)) !== null) {
  544. if (match.index > lastIndex) {
  545. html += formatTextBlockHtml(t.slice(lastIndex, match.index));
  546. }
  547. html += buildAiImageTag(match[1], match[2]);
  548. lastIndex = tokenRe.lastIndex;
  549. }
  550. if (lastIndex < t.length) {
  551. html += formatTextBlockHtml(t.slice(lastIndex));
  552. }
  553. return html;
  554. }
  555. function q(name) {
  556. try {
  557. var v = new URLSearchParams(location.search || "").get(name);
  558. return v == null ? "" : String(v);
  559. } catch (e) {
  560. return "";
  561. }
  562. }
  563. function getQueryParam(name) {
  564. var m = new RegExp("[?&]" + name + "=([^&]*)").exec(window.location.search);
  565. if (!m) return "";
  566. try {
  567. return decodeURIComponent(m[1].replace(/\+/g, " "));
  568. } catch (e) {
  569. return "";
  570. }
  571. }
  572. function parsePayload() {
  573. var raw = getQueryParam("payload");
  574. if (!raw) return null;
  575. try {
  576. return JSON.parse(raw);
  577. } catch (e) {
  578. return null;
  579. }
  580. }
  581. function getConversationQueryParams() {
  582. var sessionId = String(q("session_id") || q("sessionId") || "").trim();
  583. var userId = String(q("user_id") || q("userId") || "").trim();
  584. var type = String(q("type") || "").trim();
  585. if (!sessionId || !userId) return null;
  586. return { sessionId: sessionId, userId: userId, type: type };
  587. }
  588. function parseMessageIdsFromQuery() {
  589. var raw = String(q("message_ids") || q("messageIds") || "").trim();
  590. if (!raw) return null;
  591. return raw
  592. .split(",")
  593. .map(function (s) {
  594. return String(s || "").trim();
  595. })
  596. .filter(Boolean);
  597. }
  598. function getMessageImageUrls(msg) {
  599. if (!msg) return [];
  600. if (Array.isArray(msg.imageUrls) && msg.imageUrls.length) {
  601. return msg.imageUrls
  602. .map(function (u) {
  603. return String(u || "").trim();
  604. })
  605. .filter(Boolean);
  606. }
  607. if (msg.imageUrl) return [String(msg.imageUrl)];
  608. return [];
  609. }
  610. function buildUserBubbleImagesHtml(imageUrls) {
  611. if (!Array.isArray(imageUrls) || !imageUrls.length) return "";
  612. var imgs = "";
  613. for (var j = 0; j < imageUrls.length; j++) {
  614. imgs +=
  615. '<img class="user-bubble__image" src="' +
  616. escHtml(imageUrls[j]) +
  617. '" alt="图片" loading="lazy" decoding="async" />';
  618. }
  619. return '<div class="user-bubble__images">' + imgs + "</div>";
  620. }
  621. function normalizeHistoryRowImageUrls(item) {
  622. var raw = item.image_urls || item.imageUrls || item.images;
  623. if (Array.isArray(raw)) {
  624. return raw
  625. .map(function (u) {
  626. return String(u || "").trim();
  627. })
  628. .filter(Boolean);
  629. }
  630. if (typeof raw === "string" && raw.trim()) {
  631. return raw
  632. .split(",")
  633. .map(function (s) {
  634. return s.trim();
  635. })
  636. .filter(Boolean);
  637. }
  638. return [];
  639. }
  640. function filterConversationMessagesByIds(messages, idList) {
  641. if (!Array.isArray(idList) || !idList.length) return messages;
  642. var idSet = {};
  643. for (var i = 0; i < idList.length; i++) {
  644. idSet[String(idList[i])] = true;
  645. }
  646. return (Array.isArray(messages) ? messages : []).filter(function (msg) {
  647. if (!msg || msg.id == null || msg.id === "") return false;
  648. return !!idSet[String(msg.id)];
  649. });
  650. }
  651. function getConversationApiBase(type) {
  652. return String(type || "").trim() === "1"
  653. ? AI_UBAO_CONVERSATION_API
  654. : AI_LEGAL_CONVERSATION_API;
  655. }
  656. function buildConversationApiUrl(sessionId, userId, type) {
  657. var params = new URLSearchParams();
  658. params.set("session_id", sessionId);
  659. params.set("user_id", userId);
  660. return getConversationApiBase(type) + "?" + params.toString();
  661. }
  662. function normalizeConversationRole(raw) {
  663. var role = String(raw || "").trim().toLowerCase();
  664. if (
  665. role === "user" ||
  666. role === "human" ||
  667. role === "customer" ||
  668. role === "question" ||
  669. role === "1" ||
  670. role === "我"
  671. ) {
  672. return "user";
  673. }
  674. if (
  675. role === "ai" ||
  676. role === "assistant" ||
  677. role === "bot" ||
  678. role === "ubao" ||
  679. role === "answer" ||
  680. role === "2" ||
  681. role === "system"
  682. ) {
  683. return "ai";
  684. }
  685. return "";
  686. }
  687. function normalizeConversationApiPayload(res) {
  688. if (!res || typeof res !== "object") return null;
  689. if (res.code != null) {
  690. var code = Number(res.code);
  691. if (code !== 200 && code !== 0 && res.success !== true) {
  692. throw new Error(res.msg || res.message || "对话接口返回 code " + code);
  693. }
  694. }
  695. var root = res.data != null && typeof res.data === "object" ? res.data : res;
  696. var rawList =
  697. (Array.isArray(root) && root) ||
  698. (Array.isArray(root.messages) && root.messages) ||
  699. (Array.isArray(root.messageList) && root.messageList) ||
  700. (Array.isArray(root.conversation) && root.conversation) ||
  701. (Array.isArray(root.conversations) && root.conversations) ||
  702. (Array.isArray(root.records) && root.records) ||
  703. (Array.isArray(root.list) && root.list) ||
  704. null;
  705. if (!rawList) return null;
  706. var messages = [];
  707. for (var i = 0; i < rawList.length; i++) {
  708. var item = rawList[i];
  709. if (!item || typeof item !== "object") continue;
  710. var msgId = item.id != null ? item.id : item.message_id;
  711. var role = normalizeConversationRole(
  712. item.role || item.sender || item.messageRole || item.type || item.messageType || item.senderType
  713. );
  714. var content = String(
  715. item.content != null
  716. ? item.content
  717. : item.message != null
  718. ? item.message
  719. : item.text != null
  720. ? item.text
  721. : ""
  722. ).trim();
  723. if (!role && item.question) {
  724. role = "user";
  725. content = String(item.question).trim();
  726. } else if (!role && item.answer) {
  727. role = "ai";
  728. content = String(item.answer).trim();
  729. } else if (!role && item.userMessage) {
  730. role = "user";
  731. content = String(item.userMessage).trim();
  732. } else if (!role && (item.aiMessage || item.assistantMessage)) {
  733. role = "ai";
  734. content = String(item.aiMessage || item.assistantMessage).trim();
  735. }
  736. var imageUrls = normalizeHistoryRowImageUrls(item);
  737. if (imageUrls.length) {
  738. messages.push({
  739. id: msgId,
  740. role: role || "user",
  741. isImage: true,
  742. imageUrls: imageUrls,
  743. imageUrl: imageUrls[0],
  744. content: content,
  745. });
  746. continue;
  747. }
  748. if (!content) continue;
  749. var imageUrl = item.imageUrl || item.image || item.imgUrl || item.url;
  750. if (imageUrl && /^(https?:)?\/\//i.test(String(imageUrl))) {
  751. messages.push({
  752. id: msgId,
  753. role: role || "user",
  754. isImage: true,
  755. imageUrls: [String(imageUrl)],
  756. imageUrl: String(imageUrl),
  757. });
  758. continue;
  759. }
  760. messages.push({
  761. id: msgId,
  762. role: role || (messages.length % 2 === 0 ? "user" : "ai"),
  763. content: content,
  764. });
  765. }
  766. if (!messages.length) return null;
  767. return {
  768. messages: messages,
  769. shareTime:
  770. root.shareTime ||
  771. root.createdAt ||
  772. root.createTime ||
  773. root.updateTime ||
  774. root.timestamp ||
  775. res.timestamp,
  776. firstQuestion: root.firstQuestion || root.title || root.topic || "",
  777. sessionId: root.sessionId || root.session_id || "",
  778. userId: root.userId || root.user_id || "",
  779. };
  780. }
  781. function formatJsonForDebug(value) {
  782. if (value == null) return "(无)";
  783. try {
  784. return JSON.stringify(value, null, 2);
  785. } catch (e) {
  786. return String(value);
  787. }
  788. }
  789. function setConversationApiDebugInfo(info) {
  790. conversationApiDebugInfo = info;
  791. renderApiDebugModal();
  792. }
  793. function renderApiDebugModal() {
  794. var body = document.getElementById("apiDebugBody");
  795. if (!body) return;
  796. if (!conversationApiDebugInfo) {
  797. body.innerHTML =
  798. '<div class="api-debug-section"><div class="api-debug-section__label">说明</div>' +
  799. '<pre class="api-debug-section__pre">尚未请求聊天记录接口(缺少 session_id / user_id 参数时使用 payload 渲染)</pre></div>';
  800. return;
  801. }
  802. var info = conversationApiDebugInfo;
  803. var html =
  804. '<div class="api-debug-section"><div class="api-debug-section__label">接口地址</div>' +
  805. '<pre class="api-debug-section__pre">' +
  806. escHtml(info.apiBase || info.requestUrl || "(无)") +
  807. "</pre></div>" +
  808. '<div class="api-debug-section"><div class="api-debug-section__label">请求方式</div>' +
  809. '<pre class="api-debug-section__pre">' +
  810. escHtml(info.method || "GET") +
  811. "</pre></div>" +
  812. '<div class="api-debug-section"><div class="api-debug-section__label">完整请求 URL</div>' +
  813. '<pre class="api-debug-section__pre">' +
  814. escHtml(info.requestUrl || "(无)") +
  815. "</pre></div>" +
  816. '<div class="api-debug-section"><div class="api-debug-section__label">请求参数</div>' +
  817. '<pre class="api-debug-section__pre">' +
  818. escHtml(formatJsonForDebug(info.params)) +
  819. "</pre></div>";
  820. if (info.error) {
  821. html +=
  822. '<div class="api-debug-section"><div class="api-debug-section__label">请求错误</div>' +
  823. '<pre class="api-debug-section__pre">' +
  824. escHtml(info.error) +
  825. "</pre></div>";
  826. }
  827. html +=
  828. '<div class="api-debug-section"><div class="api-debug-section__label">接口返回数据</div>' +
  829. '<pre class="api-debug-section__pre">' +
  830. escHtml(formatJsonForDebug(info.response)) +
  831. "</pre></div>";
  832. body.innerHTML = html;
  833. }
  834. function showApiDebugModal() {
  835. renderApiDebugModal();
  836. var mask = document.getElementById("apiDebugMask");
  837. if (mask) {
  838. mask.classList.add("is-open");
  839. mask.setAttribute("aria-hidden", "false");
  840. }
  841. }
  842. function hideApiDebugModal() {
  843. var mask = document.getElementById("apiDebugMask");
  844. if (mask) {
  845. mask.classList.remove("is-open");
  846. mask.setAttribute("aria-hidden", "true");
  847. }
  848. }
  849. function bindApiDebugModalEvents() {
  850. var btn = document.getElementById("apiDebugBtn");
  851. var closeBtn = document.getElementById("apiDebugClose");
  852. var mask = document.getElementById("apiDebugMask");
  853. if (btn) btn.addEventListener("click", showApiDebugModal);
  854. if (closeBtn) closeBtn.addEventListener("click", hideApiDebugModal);
  855. if (mask) {
  856. mask.addEventListener("click", function (e) {
  857. if (e.target === mask) hideApiDebugModal();
  858. });
  859. }
  860. }
  861. function fetchConversationHistory(sessionId, userId, type) {
  862. var requestUrl = buildConversationApiUrl(sessionId, userId, type);
  863. var apiBase = getConversationApiBase(type);
  864. var params = {
  865. session_id: sessionId,
  866. user_id: userId,
  867. type: type || "",
  868. };
  869. setConversationApiDebugInfo({
  870. apiBase: apiBase,
  871. requestUrl: requestUrl,
  872. method: "GET",
  873. params: params,
  874. response: null,
  875. error: null,
  876. });
  877. console.log("[conversation-api] GET", requestUrl);
  878. return fetch(requestUrl, {
  879. method: "GET",
  880. mode: "cors",
  881. credentials: "omit",
  882. headers: { Accept: "application/json" },
  883. })
  884. .then(function (r) {
  885. if (r.ok) return r.json();
  886. return r
  887. .text()
  888. .catch(function () {
  889. return "";
  890. })
  891. .then(function (text) {
  892. var hint = "";
  893. var parsed = null;
  894. try {
  895. parsed = JSON.parse(text);
  896. hint = parsed.msg || parsed.message || "";
  897. } catch (eP) {
  898. if (text) hint = text.slice(0, 120);
  899. }
  900. setConversationApiDebugInfo({
  901. apiBase: apiBase,
  902. requestUrl: requestUrl,
  903. method: "GET",
  904. params: params,
  905. response: parsed || text || null,
  906. error: "HTTP " + r.status + (hint ? ":" + hint : ""),
  907. });
  908. throw new Error("对话接口 HTTP " + r.status + (hint ? ":" + hint : ""));
  909. });
  910. })
  911. .then(function (res) {
  912. setConversationApiDebugInfo({
  913. apiBase: apiBase,
  914. requestUrl: requestUrl,
  915. method: "GET",
  916. params: params,
  917. response: res,
  918. error: null,
  919. });
  920. var data = normalizeConversationApiPayload(res);
  921. if (!data) {
  922. throw new Error("对话接口返回数据为空或格式无法解析");
  923. }
  924. return data;
  925. })
  926. .catch(function (e) {
  927. if (!conversationApiDebugInfo || !conversationApiDebugInfo.error) {
  928. setConversationApiDebugInfo({
  929. apiBase: apiBase,
  930. requestUrl: requestUrl,
  931. method: "GET",
  932. params: params,
  933. response: conversationApiDebugInfo && conversationApiDebugInfo.response,
  934. error: e && e.message ? e.message : String(e),
  935. });
  936. }
  937. throw e;
  938. });
  939. }
  940. function loadPageData() {
  941. var main = document.getElementById("main");
  942. var params = getConversationQueryParams();
  943. if (!params) {
  944. setConversationApiDebugInfo(null);
  945. render(parsePayload());
  946. return;
  947. }
  948. var filterIds = parseMessageIdsFromQuery();
  949. main.innerHTML = '<div class="empty">对话内容加载中…</div>';
  950. fetchConversationHistory(params.sessionId, params.userId, params.type)
  951. .then(function (data) {
  952. if (filterIds && filterIds.length) {
  953. var filtered = filterConversationMessagesByIds(data.messages, filterIds);
  954. if (!filtered.length) {
  955. throw new Error("未找到所选对话内容");
  956. }
  957. data = Object.assign({}, data, { messages: filtered });
  958. }
  959. render(data);
  960. })
  961. .catch(function (e) {
  962. var tip = e && e.message ? e.message : "对话加载失败,请稍后重试";
  963. console.warn("[conversation-api]", tip, e);
  964. main.innerHTML = '<div class="empty">' + escHtml(tip) + "</div>";
  965. refreshWxLaunchTagAttrs();
  966. });
  967. }
  968. function getFirstUserQuestion(messages) {
  969. var list = Array.isArray(messages) ? messages : [];
  970. for (var i = 0; i < list.length; i++) {
  971. var m = list[i];
  972. if (!m || m.role !== "user") continue;
  973. if (m.isImage) return "[图片]";
  974. var t = String(m.content || "").trim();
  975. if (t) return t;
  976. }
  977. return "";
  978. }
  979. function formatDiscussionTitle(question) {
  980. var qText = String(question || "").trim();
  981. if (!qText) return "与AI助手对话";
  982. if (qText.slice(-3) === "的讨论") return qText;
  983. return qText + "的讨论";
  984. }
  985. function normalizeShareTimestamp(ts) {
  986. if (ts == null || ts === "") return null;
  987. var n = Number(ts);
  988. if (!isFinite(n) || n <= 0) return null;
  989. if (n < 1e12) n = n * 1000;
  990. var d = new Date(n);
  991. if (isNaN(d.getTime()) || d.getFullYear() < 2020) return null;
  992. return n;
  993. }
  994. function resolveDisplayShareTime(data) {
  995. var fromUrl = q("shareTime") || q("share_time");
  996. var urlTs = normalizeShareTimestamp(fromUrl);
  997. if (urlTs != null) return urlTs;
  998. var dataTs = normalizeShareTimestamp(data && data.shareTime);
  999. if (dataTs != null) return dataTs;
  1000. return Date.now();
  1001. }
  1002. function formatDate(ts) {
  1003. var normalized = normalizeShareTimestamp(ts);
  1004. var d = normalized != null ? new Date(normalized) : new Date();
  1005. return d.getFullYear() + "年" + (d.getMonth() + 1) + "月" + d.getDate() + "日";
  1006. }
  1007. function renderMessages(messages) {
  1008. var html = "";
  1009. var list = Array.isArray(messages) ? messages : [];
  1010. for (var i = 0; i < list.length; i++) {
  1011. var msg = list[i];
  1012. if (!msg) continue;
  1013. if (msg.role === "user") {
  1014. var imageUrls = getMessageImageUrls(msg);
  1015. if (msg.isImage && imageUrls.length) {
  1016. html +=
  1017. '<div class="row row--user"><div class="user-bubble user-bubble--images">' +
  1018. buildUserBubbleImagesHtml(imageUrls) +
  1019. "</div></div>";
  1020. var imageUserText = String(msg.content || "").trim();
  1021. if (imageUserText) {
  1022. html +=
  1023. '<div class="row row--user"><div class="user-bubble">' +
  1024. escHtml(imageUserText) +
  1025. "</div></div>";
  1026. }
  1027. continue;
  1028. }
  1029. var userText = String(msg.content || "").trim();
  1030. if (!userText) continue;
  1031. html +=
  1032. '<div class="row row--user"><div class="user-bubble">' +
  1033. escHtml(userText) +
  1034. "</div></div>";
  1035. continue;
  1036. }
  1037. if (msg.role === "ai" || msg.role === "assistant") {
  1038. var aiText = String(msg.content || "").trim();
  1039. if (!aiText) continue;
  1040. html +=
  1041. '<div class="row row--ai"><div class="ai-card"><div class="ai-card__text">' +
  1042. renderAiContentHtml(aiText) +
  1043. "</div></div></div>";
  1044. }
  1045. }
  1046. return html;
  1047. }
  1048. function applyWeixinShareMeta() {
  1049. var siteName = "U店在哪";
  1050. var iconUrl =
  1051. "https://alien-volume.oss-cn-beijing.aliyuncs.com/icon/ubao.png";
  1052. var setMeta = function (key, content) {
  1053. var el =
  1054. document.querySelector('meta[property="' + key + '"]') ||
  1055. document.querySelector('meta[name="' + key + '"]');
  1056. if (!el) {
  1057. el = document.createElement("meta");
  1058. if (key.indexOf("og:") === 0) {
  1059. el.setAttribute("property", key);
  1060. } else {
  1061. el.setAttribute("name", key);
  1062. }
  1063. document.head.appendChild(el);
  1064. }
  1065. el.setAttribute("content", content);
  1066. };
  1067. setMeta("og:site_name", siteName);
  1068. setMeta("application-name", siteName);
  1069. setMeta("og:title", "和U宝的对话");
  1070. setMeta("og:description", "点击查看对话内容");
  1071. var links = document.querySelectorAll('link[rel="icon"], link[rel="apple-touch-icon"]');
  1072. for (var i = 0; i < links.length; i++) {
  1073. links[i].setAttribute("href", iconUrl);
  1074. }
  1075. }
  1076. function countDisplayableMessages(messages) {
  1077. var list = Array.isArray(messages) ? messages : [];
  1078. var count = 0;
  1079. for (var i = 0; i < list.length; i++) {
  1080. var msg = list[i];
  1081. if (!msg) continue;
  1082. if (msg.role === "user") {
  1083. if (msg.isImage && getMessageImageUrls(msg).length) {
  1084. count += 1;
  1085. continue;
  1086. }
  1087. if (String(msg.content || "").trim()) count += 1;
  1088. continue;
  1089. }
  1090. if (msg.role === "ai" || msg.role === "assistant") {
  1091. if (String(msg.content || "").trim()) count += 1;
  1092. }
  1093. }
  1094. return count;
  1095. }
  1096. function parseMessagesFromContent(text) {
  1097. var raw = String(text || "").trim();
  1098. if (!raw) return [];
  1099. var list = [];
  1100. var blocks = raw.split(/\n\n+/);
  1101. for (var i = 0; i < blocks.length; i++) {
  1102. var block = String(blocks[i] || "").trim();
  1103. if (!block) continue;
  1104. var userMatch = block.match(/^我[::]\s*([\s\S]*)$/);
  1105. if (userMatch) {
  1106. var userText = String(userMatch[1] || "").trim();
  1107. if (userText) list.push({ role: "user", content: userText });
  1108. continue;
  1109. }
  1110. var aiMatch = block.match(/^UBAO[::]\s*([\s\S]*)$/i);
  1111. if (aiMatch) {
  1112. var aiText = String(aiMatch[1] || "").trim();
  1113. if (aiText) list.push({ role: "ai", content: aiText });
  1114. }
  1115. }
  1116. if (list.length) return list;
  1117. var current = null;
  1118. var lines = raw.split(/\n/);
  1119. for (var j = 0; j < lines.length; j++) {
  1120. var line = String(lines[j] || "");
  1121. var userLine = line.match(/^我[::]\s*(.*)$/);
  1122. var aiLine = line.match(/^UBAO[::]\s*(.*)$/i);
  1123. if (userLine) {
  1124. if (current) list.push(current);
  1125. current = { role: "user", content: String(userLine[1] || "").trim() };
  1126. continue;
  1127. }
  1128. if (aiLine) {
  1129. if (current) list.push(current);
  1130. current = { role: "ai", content: String(aiLine[1] || "").trim() };
  1131. continue;
  1132. }
  1133. if (current && line.trim()) {
  1134. current.content = (current.content ? current.content + "\n" : "") + line.trim();
  1135. }
  1136. }
  1137. if (current && String(current.content || "").trim()) list.push(current);
  1138. return list;
  1139. }
  1140. function resolveShareMessagesForDisplay(data) {
  1141. var fromArray = Array.isArray(data && data.messages) ? data.messages : [];
  1142. var fromContent = parseMessagesFromContent((data && data.content) || "");
  1143. var arrayCount = countDisplayableMessages(fromArray);
  1144. var contentCount = countDisplayableMessages(fromContent);
  1145. // 分享链接超长时 messages 会被截断,但 content 仍保留完整对话文本
  1146. if (contentCount > arrayCount) return fromContent;
  1147. if (arrayCount) return fromArray;
  1148. return fromContent;
  1149. }
  1150. function render(data) {
  1151. applyWeixinShareMeta();
  1152. sharePayloadCache = data || null;
  1153. var main = document.getElementById("main");
  1154. if (!data) {
  1155. main.innerHTML = '<div class="empty">对话内容不存在或链接已失效</div>';
  1156. refreshWxLaunchTagAttrs();
  1157. return;
  1158. }
  1159. var messages = resolveShareMessagesForDisplay(data);
  1160. var firstQuestion =
  1161. String(data.firstQuestion || "").trim() ||
  1162. getFirstUserQuestion(messages) ||
  1163. (function () {
  1164. var text = String(data.content || "").trim();
  1165. var m = text.match(/^我[::]([\s\S]+?)(?:\n\n|$)/);
  1166. return m ? String(m[1] || "").trim() : "";
  1167. })();
  1168. var pageTitle = formatDiscussionTitle(firstQuestion);
  1169. var dateText = formatDate(resolveDisplayShareTime(data));
  1170. document.title = pageTitle;
  1171. var bodyHtml =
  1172. '<section class="hero">' +
  1173. '<h1 class="hero__title">' +
  1174. escHtml(pageTitle) +
  1175. "</h1>" +
  1176. '<p class="hero__meta">' +
  1177. escHtml(dateText) +
  1178. " · 内容由AI生成,不能完全保障真实</p>" +
  1179. '<div class="hero__divider"></div>' +
  1180. "</section>";
  1181. var convHtml = renderMessages(messages);
  1182. if (convHtml) {
  1183. bodyHtml +=
  1184. '<section class="conversation">' +
  1185. convHtml +
  1186. '</section><div class="scroll-spacer" aria-hidden="true"></div>';
  1187. } else {
  1188. bodyHtml += '<div class="empty">暂无对话内容</div>';
  1189. }
  1190. main.innerHTML = bodyHtml;
  1191. refreshWxLaunchTagAttrs();
  1192. }
  1193. function buildAiConsultOpenParams() {
  1194. var params = new URLSearchParams();
  1195. params.set("pageType", "home");
  1196. params.set("fromShareAiConsult", "1");
  1197. return params;
  1198. }
  1199. function buildAppDeepLink() {
  1200. var path = APP_UNI_AI_PATH;
  1201. var qs = buildAiConsultOpenParams().toString();
  1202. var root = APP_IOS_URL_SCHEME.replace(/\/$/, "");
  1203. return root + "/" + path + (qs ? "?" + qs : "");
  1204. }
  1205. function buildWeChatLaunchExtinfo(useBarePathOnly) {
  1206. var path = APP_UNI_AI_PATH.replace(/^\//, "");
  1207. if (useBarePathOnly) return path;
  1208. var qs = buildAiConsultOpenParams().toString();
  1209. var uniPage = qs ? path + "?" + qs : path;
  1210. if (uniPage.length <= 1024) return uniPage;
  1211. return path + "?pageType=home&fromShareAiConsult=1";
  1212. }
  1213. function isWeChatInAppBrowser() {
  1214. return /MicroMessenger/i.test(navigator.userAgent || "");
  1215. }
  1216. function getWxShareEntryFrom() {
  1217. var from = q("from");
  1218. if (from) return String(from).trim().toLowerCase();
  1219. try {
  1220. var h = location.hash || "";
  1221. var qi = h.indexOf("?");
  1222. if (qi >= 0) {
  1223. var hf = new URLSearchParams(h.slice(qi + 1)).get("from");
  1224. if (hf) return String(hf).trim().toLowerCase();
  1225. }
  1226. } catch (eH) {}
  1227. return "";
  1228. }
  1229. function logWxEntryDiagnostics() {
  1230. if (!isWeChatInAppBrowser()) return;
  1231. console.log("[wx-entry]", {
  1232. entryFrom: getWxShareEntryFrom() || "(无)",
  1233. wxJssdkReady: weChatJssdkConfigured,
  1234. signUrl: getWxConfigSignUrl(),
  1235. });
  1236. }
  1237. function isIOSWeChatBrowser() {
  1238. var ua = navigator.userAgent || "";
  1239. return /MicroMessenger/i.test(ua) && /iPhone|iPad|iPod/i.test(ua);
  1240. }
  1241. function isWxDebugOn() {
  1242. return q("wxDebug") === "1";
  1243. }
  1244. function isWxForceDebug() {
  1245. return q("wxForce") === "1";
  1246. }
  1247. function isWxConfigOnClickDebug() {
  1248. return q("wxConfigOnClick") === "1";
  1249. }
  1250. function isWxPcAutoDebugHost() {
  1251. var h = (location.hostname || "").toLowerCase();
  1252. if (h === "localhost" || h === "127.0.0.1") return true;
  1253. for (var i = 0; i < WECHAT_JS_SAFE_HOSTS.length; i++) {
  1254. if (WECHAT_JS_SAFE_HOSTS[i] === h) return true;
  1255. }
  1256. return false;
  1257. }
  1258. function isWxPcBrowser() {
  1259. return !isWeChatInAppBrowser();
  1260. }
  1261. function shouldInitWeChatJssdkOnLoad() {
  1262. if (isWeChatInAppBrowser()) return true;
  1263. return isWxForceDebug() || isWxPcAutoDebugHost();
  1264. }
  1265. function shouldFetchWxConfig(fromUserClick) {
  1266. if (isWeChatInAppBrowser()) return true;
  1267. if (fromUserClick) return true;
  1268. return isWxForceDebug() || isWxPcAutoDebugHost();
  1269. }
  1270. function getWxHtmlUrl() {
  1271. var forced = String(q("wxSignUrl") || "").trim();
  1272. if (forced) return forced.split("#")[0];
  1273. return String(location.href || "").split("#")[0];
  1274. }
  1275. function getWxSignPageUrlForApi() {
  1276. var htmlUrl = getWxHtmlUrl();
  1277. if (htmlUrl && /^https?:\/\//i.test(htmlUrl)) return htmlUrl;
  1278. return WX_GET_CONFIG_SIGN_URL;
  1279. }
  1280. function getWxHtmlUrlBase() {
  1281. var htmlUrl = getWxSignPageUrlForApi();
  1282. try {
  1283. var u = new URL(htmlUrl);
  1284. return u.origin + u.pathname;
  1285. } catch (eU) {
  1286. return WX_GET_CONFIG_SIGN_URL;
  1287. }
  1288. }
  1289. /** 与 secondShareGoods 一致:默认用当前页完整 URL 验签(须与微信地址栏一致,含 query) */
  1290. function getWxConfigSignUrl() {
  1291. if (String(q("wxSignBaseOnly") || "") === "1") return getWxHtmlUrlBase();
  1292. return getWxSignPageUrlForApi();
  1293. }
  1294. function getWxGetConfigApiUrl() {
  1295. return API_BASE.replace(/\/$/, "") + WECHAT_GET_WX_CONFIG_PATH;
  1296. }
  1297. function buildWxGetConfigRequestBody(htmlUrl) {
  1298. return {
  1299. url: String(htmlUrl || "").split("#")[0].trim(),
  1300. };
  1301. }
  1302. function resolveWxConfigAppIdFromSignData(d) {
  1303. if (!d || typeof d !== "object") return "";
  1304. var mp =
  1305. d.mpAppId ||
  1306. d.mpAppid ||
  1307. d.officialAppId ||
  1308. d.gzhAppId ||
  1309. d.serviceAppId;
  1310. if (mp != null && String(mp).trim() !== "") return String(mp).trim();
  1311. var fromQuery = String(q("wxMpAppId") || WECHAT_MP_APP_ID || "").trim();
  1312. if (fromQuery) return fromQuery;
  1313. var raw = d.appId || d.appid || d.wxAppId;
  1314. return raw != null && String(raw).trim() !== "" ? String(raw).trim() : "";
  1315. }
  1316. function normalizeWxJssdkSignPayload(res, signUrlUsed) {
  1317. if (!res || typeof res !== "object") return null;
  1318. var d = res.data != null && typeof res.data === "object" ? res.data : res;
  1319. if (!d || typeof d !== "object") return null;
  1320. var appId = resolveWxConfigAppIdFromSignData(d);
  1321. var timestamp = d.timestamp != null ? d.timestamp : d.timeStamp;
  1322. var nonceStr =
  1323. d.nonceStr != null && String(d.nonceStr) !== ""
  1324. ? d.nonceStr
  1325. : d.noncestr != null && String(d.noncestr) !== ""
  1326. ? d.noncestr
  1327. : d.nonce;
  1328. var signature = d.signature || d.sign;
  1329. if (!appId || timestamp == null || nonceStr == null || nonceStr === "" || !signature) {
  1330. return null;
  1331. }
  1332. return {
  1333. appId: String(appId),
  1334. timestamp: Number(timestamp),
  1335. nonceStr: String(nonceStr),
  1336. signature: String(signature),
  1337. signUrl: String(signUrlUsed || "")
  1338. .split("#")[0]
  1339. .trim(),
  1340. };
  1341. }
  1342. function getWxErrMsg(err) {
  1343. if (!err) return "";
  1344. if (err.errMsg) return String(err.errMsg);
  1345. if (typeof err === "string") return err;
  1346. try {
  1347. return JSON.stringify(err);
  1348. } catch (e) {
  1349. return String(err);
  1350. }
  1351. }
  1352. function formatWxConfigErrorTip(err, signPageUrl) {
  1353. var errMsg = getWxErrMsg(err);
  1354. var tip = "微信 JSSDK 配置失败";
  1355. if (/invalid signature/i.test(errMsg)) {
  1356. return (
  1357. tip +
  1358. ":签名无效。请核对:①后端用与前端相同的 url 签名;②url=" +
  1359. (signPageUrl || getWxHtmlUrl()) +
  1360. ";③nonceStr/timestamp 与接口返回一致;④appId=" +
  1361. WECHAT_MP_APP_ID
  1362. );
  1363. }
  1364. if (/require\s*subscribe/i.test(errMsg)) {
  1365. return tip + ":" + errMsg + "(服务号需用户已关注)";
  1366. }
  1367. return errMsg ? tip + ":" + errMsg : tip;
  1368. }
  1369. function setWxInitError(msg) {
  1370. wxInitLastError = String(msg || "").trim();
  1371. if (wxInitLastError) console.warn("[wx]", wxInitLastError);
  1372. }
  1373. function requestWeChatJssdkSignAndConfig(htmlUrlOptional) {
  1374. var htmlUrl = String(htmlUrlOptional != null ? htmlUrlOptional : getWxConfigSignUrl())
  1375. .split("#")[0]
  1376. .trim();
  1377. if (!htmlUrl || !/^https?:\/\//i.test(htmlUrl)) {
  1378. htmlUrl = WX_GET_CONFIG_SIGN_URL;
  1379. }
  1380. if (isWxDebugOn()) {
  1381. try {
  1382. window.alert("htmlUrl(签名用,应与地址栏一致):\n" + htmlUrl);
  1383. } catch (eDbg) {}
  1384. }
  1385. var requestUrl = getWxGetConfigApiUrl();
  1386. var requestBody = buildWxGetConfigRequestBody(htmlUrl);
  1387. console.log("[wx] htmlUrl=", htmlUrl);
  1388. console.log("[wx] POST getWxConfig →", requestUrl, requestBody);
  1389. return fetch(requestUrl, {
  1390. method: "POST",
  1391. mode: "cors",
  1392. credentials: "omit",
  1393. headers: {
  1394. Accept: "application/json",
  1395. "Content-Type": "application/json;charset=UTF-8",
  1396. },
  1397. body: JSON.stringify(requestBody),
  1398. })
  1399. .then(function (r) {
  1400. if (r.ok) return r.json();
  1401. return r
  1402. .text()
  1403. .catch(function () {
  1404. return "";
  1405. })
  1406. .then(function (text) {
  1407. var hint = "";
  1408. try {
  1409. var j = JSON.parse(text);
  1410. hint = j.msg || j.message || "";
  1411. } catch (eP) {
  1412. if (text) hint = text.slice(0, 120);
  1413. }
  1414. throw new Error("getWxConfig HTTP " + r.status + (hint ? ":" + hint : ""));
  1415. });
  1416. })
  1417. .then(function (res) {
  1418. if (res && res.code != null) {
  1419. var c = Number(res.code);
  1420. if (c !== 200 && c !== 0 && res.success !== true) {
  1421. throw new Error(res.msg || res.message || "getWxConfig code " + c);
  1422. }
  1423. }
  1424. var sign = normalizeWxJssdkSignPayload(res, htmlUrl);
  1425. if (!sign) {
  1426. console.warn("[wx] getWxConfig 响应字段不全", res, "htmlUrl=", htmlUrl);
  1427. throw new Error("getWxConfig 缺少 appId/timestamp/nonceStr/signature(见控制台)");
  1428. }
  1429. if (sign.appId !== WECHAT_MP_APP_ID) {
  1430. console.warn(
  1431. "[wx] 后端 appId=" + sign.appId + ",期望服务号 " + WECHAT_MP_APP_ID
  1432. );
  1433. }
  1434. if (typeof wx === "undefined") {
  1435. if (isWxPcBrowser()) {
  1436. console.log("[wx] PC getWxConfig 成功(无 jweixin)", sign);
  1437. return true;
  1438. }
  1439. setWxInitError("jweixin.js 未加载");
  1440. return false;
  1441. }
  1442. return applyWxConfigFromSign(sign, htmlUrl);
  1443. });
  1444. }
  1445. function applyWxConfigFromSign(sign, htmlUrl) {
  1446. var wxConfigParams = {
  1447. debug: isWxDebugOn(),
  1448. appId: String(sign.appId),
  1449. timestamp: sign.timestamp,
  1450. nonceStr: String(sign.nonceStr),
  1451. signature: String(sign.signature),
  1452. jsApiList: [],
  1453. openTagList: ["wx-open-launch-app"],
  1454. };
  1455. return new Promise(function (resolve) {
  1456. wx.config(wxConfigParams);
  1457. wx.ready(function () {
  1458. weChatJssdkConfigured = true;
  1459. document.body.classList.add("wx-jssdk-ready");
  1460. refreshWxLaunchTagAttrs();
  1461. console.log("[wx.config] ready, htmlUrl=", htmlUrl);
  1462. resolve(true);
  1463. });
  1464. wx.error(function (err) {
  1465. weChatJssdkConfigured = false;
  1466. document.body.classList.remove("wx-jssdk-ready");
  1467. wxJssdkInitPromise = null;
  1468. var errMsg = getWxErrMsg(err);
  1469. setWxInitError(formatWxConfigErrorTip(err, htmlUrl));
  1470. if (isWxDebugOn()) window.alert(wxInitLastError);
  1471. console.warn("[wx.config]", errMsg, "htmlUrl=", htmlUrl);
  1472. var baseUrl = getWxHtmlUrlBase();
  1473. var fullUrl = getWxSignPageUrlForApi();
  1474. if (
  1475. !/invalid signature/i.test(errMsg) ||
  1476. wxConfigSignRetriedBaseUrl ||
  1477. baseUrl === fullUrl ||
  1478. htmlUrl === baseUrl
  1479. ) {
  1480. resolve(false);
  1481. return;
  1482. }
  1483. wxConfigSignRetriedBaseUrl = true;
  1484. requestWeChatJssdkSignAndConfig(baseUrl).then(resolve);
  1485. });
  1486. });
  1487. }
  1488. function refreshWxLaunchTagAttrs(useBarePathOnly) {
  1489. var tag = document.getElementById("launch-btn");
  1490. if (!tag) return;
  1491. try {
  1492. tag.setAttribute("appid", WECHAT_OPEN_APP_ID);
  1493. tag.setAttribute("extinfo", buildWeChatLaunchExtinfo(!!useBarePathOnly));
  1494. console.log("[wx-open-launch-app] extinfo=", tag.getAttribute("extinfo"));
  1495. } catch (eA) {}
  1496. }
  1497. function bindWeChatLaunchTagEvents() {
  1498. var tag = document.getElementById("launch-btn");
  1499. if (!tag || tag._wxLaunchBound) return;
  1500. tag._wxLaunchBound = true;
  1501. refreshWxLaunchTagAttrs();
  1502. tag.addEventListener("launch", function () {
  1503. console.log("[wx-open-launch-app] launch ok");
  1504. });
  1505. tag.addEventListener("error", function (e) {
  1506. var detail = e && e.detail;
  1507. var errMsg =
  1508. detail && detail.errMsg
  1509. ? String(detail.errMsg)
  1510. : detail && detail.errmsg
  1511. ? String(detail.errmsg)
  1512. : "";
  1513. console.warn(
  1514. "[wx-open-launch-app]",
  1515. detail,
  1516. "extinfo=",
  1517. tag.getAttribute("extinfo")
  1518. );
  1519. if (/launch:fail_check/i.test(errMsg)) {
  1520. showAppOpenFailTip(
  1521. "请用微信分享卡片进入,或确认已安装最新版「U店在哪」"
  1522. );
  1523. return;
  1524. }
  1525. // if (
  1526. // /launch:fail/i.test(errMsg) &&
  1527. // !tag._wxLaunchBareRetried &&
  1528. // tag.getAttribute("extinfo") !== buildWeChatLaunchExtinfo(true)
  1529. // ) {
  1530. // tag._wxLaunchBareRetried = true;
  1531. // refreshWxLaunchTagAttrs(true);
  1532. // showFabToast("请再点一次「和U宝继续聊」");
  1533. // return;
  1534. // }
  1535. if (/launch:fail/i.test(errMsg) && !getWxShareEntryFrom()) {
  1536. showAppOpenFailTip("请前往应用商店下载U店在哪app");
  1537. return;
  1538. }
  1539. showAppOpenFailTip(
  1540. errMsg
  1541. ? "未能打开 App:" + errMsg
  1542. : "未能打开 App,请确认已安装最新版「U店在哪」"
  1543. );
  1544. });
  1545. }
  1546. function initWeChatOpenLaunchApp(fromUserClick) {
  1547. if (!shouldFetchWxConfig(!!fromUserClick)) {
  1548. return Promise.resolve(false);
  1549. }
  1550. if (wxJssdkInitPromise && !fromUserClick) return wxJssdkInitPromise;
  1551. wxConfigSignRetriedBaseUrl = false;
  1552. wxInitLastError = "";
  1553. var htmlUrl = getWxConfigSignUrl();
  1554. bindWeChatLaunchTagEvents();
  1555. wxJssdkInitPromise = requestWeChatJssdkSignAndConfig(htmlUrl)
  1556. .then(function (ok) {
  1557. if (ok === true) return true;
  1558. if (!wxInitLastError) {
  1559. setWxInitError("wx.config 失败,可加 ?wxDebug=1 查看 htmlUrl");
  1560. }
  1561. return false;
  1562. })
  1563. .catch(function (e) {
  1564. var msg = e && e.message ? e.message : "getWxConfig 请求失败";
  1565. setWxInitError(msg);
  1566. console.warn("[wx] requestWeChatJssdkSignAndConfig failed", msg, "htmlUrl=", htmlUrl);
  1567. if (isWeChatInAppBrowser() && isWxDebugOn()) window.alert(msg);
  1568. return false;
  1569. })
  1570. .finally(function () {
  1571. if (!weChatJssdkConfigured) wxJssdkInitPromise = null;
  1572. });
  1573. return wxJssdkInitPromise;
  1574. }
  1575. function scheduleWeChatJssdkBootstrap() {
  1576. if (!shouldInitWeChatJssdkOnLoad()) return;
  1577. var attempts = 0;
  1578. function tick() {
  1579. attempts += 1;
  1580. if (weChatJssdkConfigured) return;
  1581. initWeChatOpenLaunchApp();
  1582. if (!weChatJssdkConfigured && attempts < 8 && typeof wx === "undefined") {
  1583. setTimeout(tick, 400);
  1584. }
  1585. }
  1586. if (isIOSWeChatBrowser()) {
  1587. setTimeout(tick, 350);
  1588. } else {
  1589. tick();
  1590. }
  1591. }
  1592. function showFabToast(msg, ms) {
  1593. var tip = String(msg || "").trim();
  1594. if (!tip) return;
  1595. var el = document.getElementById("openAppToast");
  1596. if (el) {
  1597. el.textContent = tip;
  1598. el.style.display = "block";
  1599. if (showFabToast._t) clearTimeout(showFabToast._t);
  1600. showFabToast._t = setTimeout(function () {
  1601. el.style.display = "none";
  1602. }, ms || 2800);
  1603. }
  1604. console.log("[openApp]", tip);
  1605. }
  1606. function showDownloadTip() {
  1607. var msg = "请到应用商店下载「U店在哪」";
  1608. if (typeof uni !== "undefined" && typeof uni.showToast === "function") {
  1609. uni.showToast({ title: msg, icon: "none", duration: 2500 });
  1610. } else {
  1611. window.alert(msg);
  1612. }
  1613. }
  1614. function showAppOpenFailTip(msg) {
  1615. var tip = msg || "未能打开 App,请确认已安装最新版「U店在哪」。";
  1616. if (typeof uni !== "undefined" && typeof uni.showToast === "function") {
  1617. uni.showToast({ title: msg, icon: "none", duration: 2800 });
  1618. } else if (isWeChatInAppBrowser()) {
  1619. window.alert(tip);
  1620. } else {
  1621. showFabToast(tip);
  1622. }
  1623. }
  1624. function launchAppDeepLink(deepLink) {
  1625. try {
  1626. var a = document.createElement("a");
  1627. a.href = deepLink;
  1628. a.setAttribute("target", "_self");
  1629. document.body.appendChild(a);
  1630. a.click();
  1631. document.body.removeChild(a);
  1632. } catch (e1) {}
  1633. try {
  1634. window.location.href = deepLink;
  1635. } catch (e2) {}
  1636. }
  1637. function tryOpenHBuilderAppViaScheme() {
  1638. var deepLink = buildAppDeepLink();
  1639. if (typeof plus !== "undefined" && plus.runtime) {
  1640. var installed = null;
  1641. try {
  1642. if (typeof plus.runtime.isApplicationExist === "function") {
  1643. installed = plus.runtime.isApplicationExist({
  1644. pname: APP_ANDROID_PACKAGE,
  1645. action: APP_IOS_URL_SCHEME,
  1646. });
  1647. }
  1648. } catch (e) {
  1649. console.warn(e);
  1650. }
  1651. if (installed === false) {
  1652. showDownloadTip();
  1653. return;
  1654. }
  1655. try {
  1656. plus.runtime.openURL(deepLink);
  1657. } catch (e2) {
  1658. console.warn(e2);
  1659. showDownloadTip();
  1660. }
  1661. return;
  1662. }
  1663. var done = false;
  1664. function finish() {
  1665. if (done) return;
  1666. done = true;
  1667. document.removeEventListener("visibilitychange", onVis);
  1668. window.removeEventListener("pagehide", onHide);
  1669. }
  1670. function onVis() {
  1671. if (document.visibilityState === "hidden") finish();
  1672. }
  1673. function onHide() {
  1674. finish();
  1675. }
  1676. document.addEventListener("visibilitychange", onVis);
  1677. window.addEventListener("pagehide", onHide);
  1678. try {
  1679. launchAppDeepLink(deepLink);
  1680. } catch (e3) {
  1681. finish();
  1682. showDownloadTip();
  1683. return;
  1684. }
  1685. window.setTimeout(function () {
  1686. finish();
  1687. }, 3200);
  1688. }
  1689. function tryFetchWxConfigOnPcClick() {
  1690. if (!isWxPcBrowser()) return Promise.resolve(false);
  1691. showFabToast("正在请求 getWxConfig…");
  1692. wxJssdkInitPromise = null;
  1693. return initWeChatOpenLaunchApp(true).then(function (ok) {
  1694. if (ok) {
  1695. showFabToast(
  1696. weChatJssdkConfigured
  1697. ? "getWxConfig 成功,wx.config 已就绪"
  1698. : "getWxConfig 成功"
  1699. );
  1700. } else {
  1701. showFabToast(wxInitLastError || "getWxConfig 失败");
  1702. }
  1703. return ok;
  1704. });
  1705. }
  1706. function tryOpenHBuilderApp() {
  1707. if (isWeChatInAppBrowser()) return;
  1708. if (!isWxPcBrowser()) {
  1709. tryOpenHBuilderAppViaScheme();
  1710. return;
  1711. }
  1712. tryFetchWxConfigOnPcClick().then(function () {
  1713. if (isWxConfigOnClickDebug() && !isWxForceDebug() && !isWxPcAutoDebugHost()) {
  1714. return;
  1715. }
  1716. tryOpenHBuilderAppViaScheme();
  1717. });
  1718. }
  1719. function boot() {
  1720. var launchTag = document.getElementById("launch-btn");
  1721. if (launchTag) launchTag.setAttribute("appid", WECHAT_OPEN_APP_ID);
  1722. bindWeChatLaunchTagEvents();
  1723. if (isWeChatInAppBrowser()) {
  1724. document.body.classList.add("is-wechat");
  1725. logWxEntryDiagnostics();
  1726. }
  1727. if (shouldInitWeChatJssdkOnLoad()) {
  1728. if (isWxPcBrowser() && (isWxForceDebug() || isWxPcAutoDebugHost())) {
  1729. document.body.classList.add("wx-pc-debug");
  1730. }
  1731. scheduleWeChatJssdkBootstrap();
  1732. }
  1733. document.addEventListener("WeixinOpenTagsError", function (e) {
  1734. console.warn("[WeixinOpenTagsError]", e && e.detail);
  1735. });
  1736. if (isWeChatInAppBrowser()) {
  1737. var openBtnWx = document.getElementById("openApp");
  1738. if (openBtnWx) {
  1739. openBtnWx.addEventListener("click", function () {
  1740. if (!weChatJssdkConfigured) {
  1741. showFabToast(
  1742. wxInitLastError || "微信 SDK 初始化中,请稍候再点底部按钮"
  1743. );
  1744. }
  1745. });
  1746. }
  1747. } else {
  1748. var openAppBtn = document.getElementById("openApp");
  1749. if (openAppBtn) {
  1750. openAppBtn.addEventListener("click", tryOpenHBuilderApp);
  1751. }
  1752. }
  1753. bindApiDebugModalEvents();
  1754. loadPageData();
  1755. }
  1756. if (document.readyState === "complete") {
  1757. boot();
  1758. } else {
  1759. window.addEventListener("load", boot);
  1760. }
  1761. })();
  1762. </script>
  1763. </body>
  1764. </html>