shareAiConsult.html 67 KB

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