shareAiConsult.html 60 KB

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