Explorar el Código

增加ai客服h5页面

lxr hace 2 días
padre
commit
6a7848a733
Se han modificado 1 ficheros con 1808 adiciones y 0 borrados
  1. 1808 0
      HBuilderProjects/shareAiKfChat.html

+ 1808 - 0
HBuilderProjects/shareAiKfChat.html

@@ -0,0 +1,1808 @@
+<!DOCTYPE html>
+<html lang="zh-CN">
+<head>
+  <meta charset="utf-8">
+  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover">
+  <meta name="format-detection" content="telephone=no">
+  <title>与AI客服对话</title>
+  <meta property="og:title" content="和AI客服的对话">
+  <meta property="og:description" content="点击查看对话内容">
+  <meta property="og:site_name" content="U店在哪">
+  <meta name="application-name" content="U店在哪">
+  <link rel="icon" type="image/png" href="https://alien-volume.oss-cn-beijing.aliyuncs.com/icon/ubao.png">
+  <link rel="apple-touch-icon" href="https://alien-volume.oss-cn-beijing.aliyuncs.com/icon/ubao.png">
+  <style>
+    :root {
+      --bg: #f4f6fb;
+      --text: #151515;
+      --muted: #aaaaaa;
+      --orange: #f47d1f;
+      --safe-bottom: env(safe-area-inset-bottom, 0px);
+    }
+
+    * {
+      margin: 0;
+      padding: 0;
+      box-sizing: border-box;
+    }
+
+    html {
+      height: 100%;
+      -webkit-tap-highlight-color: transparent;
+      overflow: hidden;
+    }
+
+    body {
+      font-family: -apple-system, BlinkMacSystemFont, "PingFang SC", "Microsoft YaHei", sans-serif;
+      background: var(--bg);
+      color: var(--text);
+      height: 100vh;
+      display: flex;
+      flex-direction: column;
+      overflow: hidden;
+    }
+
+    #main {
+      flex: 1;
+      min-height: 0;
+      overflow-x: hidden;
+      overflow-y: auto;
+      -webkit-overflow-scrolling: touch;
+      padding-bottom: calc(100px + var(--safe-bottom));
+    }
+
+    .hero {
+      padding: 16px 15px 0;
+    }
+
+    .hero__title {
+      font-size: 20px;
+      font-weight: 700;
+      line-height: 1.4;
+      word-break: break-word;
+    }
+
+    .hero__meta {
+      margin-top: 8px;
+      font-size: 12px;
+      color: var(--muted);
+      line-height: 1.4;
+    }
+
+    .hero__divider {
+      margin-top: 14px;
+      height: 1px;
+      background: rgba(170, 170, 170, 0.25);
+    }
+
+    .conversation {
+      padding: 14px 15px 8px;
+    }
+
+    .scroll-spacer {
+      height: calc(72px + var(--safe-bottom));
+      flex-shrink: 0;
+    }
+
+    .conversation .row:last-child {
+      margin-bottom: 0;
+    }
+
+    .row {
+      display: flex;
+      margin-bottom: 12px;
+    }
+
+    .row--user {
+      justify-content: flex-end;
+    }
+
+    .row--ai {
+      justify-content: flex-start;
+    }
+
+    .user-bubble {
+      position: relative;
+      max-width: 78%;
+      padding: 10px 14px;
+      background: var(--orange);
+      border-radius: 8px 8px 2px 8px;
+      color: #fff;
+      font-size: 15px;
+      font-weight: 500;
+      line-height: 1.5;
+      white-space: pre-wrap;
+      word-break: break-word;
+    }
+
+    .user-bubble::after {
+      content: "";
+      position: absolute;
+      right: -6px;
+      bottom: 8px;
+      width: 0;
+      height: 0;
+      border-style: solid;
+      border-width: 6px 0 6px 7px;
+      border-color: transparent transparent transparent var(--orange);
+    }
+
+    .ai-card {
+      width: 100%;
+      padding: 14px 13px;
+      background: #fff;
+      border-radius: 12px;
+      box-shadow: 0 1px 6px rgba(0, 0, 0, 0.04);
+    }
+
+    .ai-card__text {
+      font-size: 14px;
+      line-height: 1.65;
+      white-space: pre-wrap;
+      word-break: break-word;
+      text-align: left;
+    }
+
+    .ai-card::after {
+      content: "本回答由AI生成,内容仅供参考,请仔细甄别";
+      display: block;
+      margin-top: 8px;
+      font-size: 12px;
+      line-height: 1.5;
+      color: #999999;
+      text-align: left;
+      font-style: italic;
+    }
+
+    .ai-card__image {
+      display: block;
+      max-width: 100%;
+      height: auto;
+      margin: 8px 0;
+      border-radius: 6px;
+    }
+
+    .user-bubble__image {
+      display: block;
+      max-width: 180px;
+      border-radius: 4px;
+    }
+
+    .fallback-card {
+      margin: 14px 15px 0;
+      padding: 14px 13px;
+      background: #fff;
+      border-radius: 8px;
+      box-shadow: 0 1px 6px rgba(0, 0, 0, 0.04);
+    }
+
+    .fallback-card .ai-card__text {
+      font-size: 14px;
+      line-height: 1.65;
+      white-space: pre-wrap;
+      word-break: break-word;
+      text-align: left;
+    }
+
+    .empty {
+      padding: 48px 20px;
+      text-align: center;
+      color: var(--muted);
+      font-size: 14px;
+    }
+
+    .fab-wrap {
+      position: fixed;
+      left: 0;
+      right: 0;
+      bottom: 0;
+      z-index: 200;
+      padding: 12px 24px calc(12px + var(--safe-bottom));
+      background: linear-gradient(to top, rgba(255, 255, 255, 0.98) 70%, transparent);
+      pointer-events: none;
+    }
+
+    .fab-dock__slot {
+      width: 100%;
+      max-width: 280px;
+      height: 48px;
+      margin: 0 auto;
+      pointer-events: auto;
+    }
+
+    #openApp.fab {
+      padding: 0 10px;
+      -webkit-font-smoothing: antialiased;
+      text-rendering: optimizeLegibility;
+    }
+
+    .fab__brand-clip {
+      display: block;
+      flex-shrink: 0;
+      line-height: 0;
+    }
+
+    .fab__brand-img {
+      display: block;
+      height: 20px;
+      width: auto;
+      max-width: 90%;
+      pointer-events: none;
+      -webkit-user-drag: none;
+    }
+
+    .fab__label {
+      font-size: 15px;
+      line-height: 1;
+      letter-spacing: 0.04em;
+      white-space: nowrap;
+    }
+
+    #launch-btn {
+      display: none;
+      width: 100%;
+      height: 48px;
+      min-height: 48px;
+      border-radius: 999px;
+      overflow: hidden;
+      opacity: 1;
+    }
+
+    body.is-wechat.wx-jssdk-ready #launch-btn {
+      display: block;
+    }
+
+    body.is-wechat.wx-jssdk-ready #openApp {
+      display: none !important;
+    }
+
+    .fab-wrap .fab {
+      pointer-events: auto;
+    }
+
+    #openApp {
+      touch-action: manipulation;
+    }
+
+    .fab {
+      display: flex;
+      align-items: center;
+      justify-content: center;
+      gap: 4px;
+      width: 100%;
+      max-width: 280px;
+      margin: 0 auto;
+      height: 48px;
+      border: none;
+      border-radius: 999px;
+      background: linear-gradient(90deg, #ffb84c 0%, #ff6b3e 100%);
+      color: #fff;
+      font-size: 16px;
+      font-weight: 600;
+      box-shadow: 0 4px 16px rgba(255, 107, 62, 0.32);
+      cursor: pointer;
+    }
+
+    .home-indicator {
+      height: 5px;
+      background: #000;
+      border-radius: 3px;
+      width: 134px;
+      margin: 8px auto 4px;
+      opacity: 0.2;
+    }
+
+    #openAppToast {
+      display: none;
+      position: fixed;
+      left: 16px;
+      right: 16px;
+      bottom: calc(72px + var(--safe-bottom));
+      z-index: 10001;
+      padding: 10px 14px;
+      font-size: 13px;
+      line-height: 1.45;
+      color: #fff;
+      text-align: center;
+      background: rgba(0, 0, 0, 0.78);
+      border-radius: 8px;
+      pointer-events: none;
+      word-break: break-all;
+    }
+
+    .api-debug-mask {
+      display: none;
+      position: fixed;
+      inset: 0;
+      z-index: 10050;
+      background: rgba(0, 0, 0, 0.45);
+      align-items: flex-end;
+      justify-content: center;
+      padding: 0;
+    }
+
+    .api-debug-mask.is-open {
+      display: flex;
+    }
+
+    .api-debug-sheet {
+      width: 100%;
+      max-height: 78vh;
+      background: #fff;
+      border-radius: 16px 16px 0 0;
+      display: flex;
+      flex-direction: column;
+      overflow: hidden;
+      padding-bottom: var(--safe-bottom);
+    }
+
+    .api-debug-sheet__head {
+      display: flex;
+      align-items: center;
+      justify-content: space-between;
+      padding: 16px 16px 10px;
+      border-bottom: 1px solid rgba(170, 170, 170, 0.25);
+      flex-shrink: 0;
+    }
+
+    .api-debug-sheet__title {
+      font-size: 16px;
+      font-weight: 700;
+      color: var(--text);
+    }
+
+    .api-debug-sheet__close {
+      width: 32px;
+      height: 32px;
+      border: none;
+      background: transparent;
+      font-size: 22px;
+      line-height: 1;
+      color: #999;
+      cursor: pointer;
+    }
+
+    .api-debug-sheet__body {
+      flex: 1;
+      min-height: 0;
+      overflow-y: auto;
+      -webkit-overflow-scrolling: touch;
+      padding: 12px 16px 20px;
+    }
+
+    .api-debug-block {
+      margin-bottom: 14px;
+    }
+
+    .api-debug-block__label {
+      font-size: 13px;
+      font-weight: 600;
+      color: var(--text);
+      margin-bottom: 6px;
+    }
+
+    .api-debug-block__content {
+      font-size: 12px;
+      line-height: 1.55;
+      color: #444;
+      background: #f7f8fa;
+      border-radius: 8px;
+      padding: 10px 12px;
+      white-space: pre-wrap;
+      word-break: break-all;
+      font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
+      max-height: 240px;
+      overflow-y: auto;
+    }
+  </style>
+</head>
+<body>
+  <main id="main">
+    <div class="empty">对话内容加载中…</div>
+  </main>
+
+  <div id="openAppToast" role="status" aria-live="polite"></div>
+
+  <div class="api-debug-mask" id="apiDebugMask" aria-hidden="true">
+    <div class="api-debug-sheet" role="dialog" aria-labelledby="apiDebugTitle">
+      <div class="api-debug-sheet__head">
+        <span class="api-debug-sheet__title" id="apiDebugTitle">接口调试信息</span>
+        <button type="button" class="api-debug-sheet__close" id="apiDebugClose" aria-label="关闭">×</button>
+      </div>
+      <div class="api-debug-sheet__body">
+        <div class="api-debug-block">
+          <div class="api-debug-block__label">接口完整地址</div>
+          <pre class="api-debug-block__content" id="apiDebugUrl"></pre>
+        </div>
+        <div class="api-debug-block">
+          <div class="api-debug-block__label">请求参数</div>
+          <pre class="api-debug-block__content" id="apiDebugParams"></pre>
+        </div>
+        <div class="api-debug-block">
+          <div class="api-debug-block__label">接口返回数据</div>
+          <pre class="api-debug-block__content" id="apiDebugResponse"></pre>
+        </div>
+      </div>
+    </div>
+  </div>
+
+  <div class="fab-wrap">
+    <div class="fab-dock__slot">
+      <!-- 与 secondShareGoods 相同顺序:openApp 在下,launch-btn 在上,避免挡住点击 -->
+      <button type="button" class="fab" id="openApp" aria-label="和AI客服继续聊">
+        <span class="fab__brand-clip" aria-hidden="true">
+          <img class="fab__brand-img" src="images/uCharts.png" alt="和AI客服继续聊" decoding="async">
+        </span>
+      </button>
+      <wx-open-launch-app id="launch-btn" appid="wxf5f1efe3a9f5012e" extinfo="">
+        <script type="text/wxtag-template">
+          <style>
+            .wx-open-app-btn {
+              display: flex;
+              align-items: center;
+              justify-content: center;
+              width: 100%;
+              height: 48px;
+              margin: 0;
+              padding: 0 10px;
+              border: none;
+              border-radius: 999px;
+              background: linear-gradient(90deg, #ffb84c 0%, #ff6b3e 100%);
+              box-shadow: 0 4px 16px rgba(255, 107, 62, 0.32);
+              cursor: pointer;
+              overflow: hidden;
+              -webkit-tap-highlight-color: transparent;
+              box-sizing: border-box;
+              font-family: -apple-system, BlinkMacSystemFont, "PingFang SC", "Helvetica Neue", sans-serif;
+              -webkit-font-smoothing: antialiased;
+            }
+            .wx-open-app-btn .fab__brand-clip {
+              display: block;
+              flex-shrink: 0;
+              line-height: 0;
+            }
+            .wx-open-app-btn .fab__brand-img {
+              display: block;
+              height: 20px;
+              width: auto;
+              max-width: 90%;
+              pointer-events: none;
+              -webkit-user-drag: none;
+            }
+          </style>
+          <button class="wx-open-app-btn" aria-label="和AI客服继续聊">
+            <span class="fab__brand-clip" aria-hidden="true">
+              <img class="fab__brand-img" src="https://prod.ailien.shop/h5/HBuilderProjects/images/uCharts.png" alt="和AI客服继续聊" decoding="async">
+            </span>
+          </button>
+        </script>
+      </wx-open-launch-app>
+    </div>
+    <div class="home-indicator" aria-hidden="true"></div>
+  </div>
+
+  <script src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
+  <script>
+    (function () {
+      "use strict";
+
+      var API_BASE = "https://prod.ailien.shop/alienStore";
+      var WECHAT_MP_APP_ID = "wx412792c77f47babd";
+      var WECHAT_OPEN_APP_ID = "wxf5f1efe3a9f5012e";
+      var WECHAT_GET_WX_CONFIG_PATH = "/wx/getWxConfig";
+      var H5_PAGE_BASE_FALLBACK = "https://prod.ailien.shop/h5/HBuilderProjects/";
+      var WX_GET_CONFIG_SIGN_URL = H5_PAGE_BASE_FALLBACK + "shareAiKfChat.html";
+      var WECHAT_JS_SAFE_HOSTS = ["uat.ailien.shop", "prod.ailien.shop"];
+      var APP_ANDROID_PACKAGE = "com.alien.Udianzaizhe";
+      var APP_IOS_URL_SCHEME = "shopro://";
+      var APP_UNI_AI_PATH = "pages/aiKfChat/index";
+      var AI_KF_CS_CONVERSATION_API =
+        "https://prod.ailien.shop/ai/life-manager/api/v1/udian-cs-conversation/history/conversation";
+
+      var sharePayloadCache = null;
+      var weChatJssdkConfigured = false;
+      var wxConfigSignRetriedBaseUrl = false;
+      var wxInitLastError = "";
+      var wxJssdkInitPromise = null;
+      var lastApiDebugInfo = null;
+
+      function escHtml(s) {
+        return String(s || "")
+          .replace(/&/g, "&amp;")
+          .replace(/</g, "&lt;")
+          .replace(/>/g, "&gt;")
+          .replace(/"/g, "&quot;");
+      }
+
+      var IMAGE_EXT = "(?:jpe?g|png|gif|webp|bmp|avif)";
+      var IMAGE_URL_PATTERN =
+        "https?:\\/\\/[^\\s))\\]]+\\." + IMAGE_EXT + "(?:\\?[^\\s))\\]]*)?";
+
+      function isInsideImageUrlSyntax(full, offset) {
+        if (offset >= 2 && full.slice(offset - 2, offset) === "](") return true;
+        if (offset >= 1 && full[offset - 1] === "(") return true;
+        if (offset >= 6 && full.slice(offset - 6, offset) === "{{IMG|") return true;
+        return false;
+      }
+
+      /** AI 回复常见:店名(https://...jpg) — 转为可渲染的图片占位 */
+      function embedInlineImageUrls(text) {
+        if (text == null) return "";
+        var t = String(text);
+
+        t = t.replace(
+          new RegExp("([^\\n((]+?)\\((" + IMAGE_URL_PATTERN + ")\\)", "gi"),
+          function (_, label, url) {
+            var name = String(label).trim();
+            if (!name) return "\n\n{{IMG|" + url + "|}}\n\n";
+            var alt = name.length > 24 ? "图片" : name.replace(/[\[\]]/g, "");
+            return name + "\n\n{{IMG|" + url + "|" + alt + "}}\n\n";
+          }
+        );
+
+        t = t.replace(
+          new RegExp("\\((" + IMAGE_URL_PATTERN + ")\\)", "gi"),
+          function (_, url) {
+            return "\n\n{{IMG|" + url + "|}}\n\n";
+          }
+        );
+
+        t = t.replace(new RegExp(IMAGE_URL_PATTERN, "gi"), function (url, offset, full) {
+          if (isInsideImageUrlSyntax(full, offset)) return url;
+          return "\n\n{{IMG|" + url + "|}}\n\n";
+        });
+
+        return t.replace(/\n{3,}/g, "\n\n");
+      }
+
+      function formatTextBlockHtml(text) {
+        return escHtml(text).replace(/\n/g, "<br>");
+      }
+
+      function buildAiImageTag(url, alt) {
+        var safeUrl = escHtml(url);
+        var safeAlt = escHtml(alt || "图片");
+        return (
+          '<img class="ai-card__image" src="' +
+          safeUrl +
+          '" alt="' +
+          safeAlt +
+          '" loading="lazy" decoding="async" />'
+        );
+      }
+
+      function renderAiContentHtml(text) {
+        var t = embedInlineImageUrls(text);
+        var html = "";
+        var tokenRe = /\{\{IMG\|([^|]+)\|([^}]*)\}\}/g;
+        var lastIndex = 0;
+        var match;
+        while ((match = tokenRe.exec(t)) !== null) {
+          if (match.index > lastIndex) {
+            html += formatTextBlockHtml(t.slice(lastIndex, match.index));
+          }
+          html += buildAiImageTag(match[1], match[2]);
+          lastIndex = tokenRe.lastIndex;
+        }
+        if (lastIndex < t.length) {
+          html += formatTextBlockHtml(t.slice(lastIndex));
+        }
+        return html;
+      }
+
+      function q(name) {
+        try {
+          var v = new URLSearchParams(location.search || "").get(name);
+          return v == null ? "" : String(v);
+        } catch (e) {
+          return "";
+        }
+      }
+
+      function getQueryParam(name) {
+        var m = new RegExp("[?&]" + name + "=([^&]*)").exec(window.location.search);
+        if (!m) return "";
+        try {
+          return decodeURIComponent(m[1].replace(/\+/g, " "));
+        } catch (e) {
+          return "";
+        }
+      }
+
+      function parsePayload() {
+        var raw = getQueryParam("payload");
+        if (!raw) return null;
+        try {
+          return JSON.parse(raw);
+        } catch (e) {
+          return null;
+        }
+      }
+
+      function getConversationQueryParams() {
+        var sessionId = String(q("session_id") || q("sessionId") || "").trim();
+        var userId = String(q("user_id") || q("userId") || "").trim();
+        var clientType = String(q("client_type") || q("clientType") || "0").trim();
+        if (!sessionId || !userId) return null;
+        return { sessionId: sessionId, userId: userId, clientType: clientType };
+      }
+
+      function parseMessageIdsFromQuery() {
+        var raw = String(q("message_ids") || q("messageIds") || "").trim();
+        if (!raw) return null;
+        return raw
+          .split(",")
+          .map(function (s) {
+            return String(s || "").trim();
+          })
+          .filter(Boolean);
+      }
+
+      function normalizeHistoryRowImageUrls(item) {
+        var raw = item.image_urls || item.imageUrls || item.images;
+        if (Array.isArray(raw)) {
+          return raw
+            .map(function (u) {
+              return String(u || "").trim();
+            })
+            .filter(Boolean);
+        }
+        if (typeof raw === "string" && raw.trim()) {
+          return raw
+            .split(",")
+            .map(function (s) {
+              return s.trim();
+            })
+            .filter(Boolean);
+        }
+        return [];
+      }
+
+      function filterConversationMessagesByIds(messages, idList) {
+        if (!Array.isArray(idList) || !idList.length) return messages;
+        var idSet = {};
+        for (var i = 0; i < idList.length; i++) {
+          idSet[String(idList[i])] = true;
+        }
+        return (Array.isArray(messages) ? messages : []).filter(function (msg) {
+          if (!msg || msg.id == null || msg.id === "") return false;
+          return !!idSet[String(msg.id)];
+        });
+      }
+
+      function buildConversationApiUrl(sessionId, userId, clientType) {
+        var params = new URLSearchParams();
+        params.set("client_type", String(clientType != null && clientType !== "" ? clientType : "0"));
+        params.set("session_id", sessionId);
+        params.set("user_id", userId);
+        return AI_KF_CS_CONVERSATION_API + "?" + params.toString();
+      }
+
+      function buildConversationRequestParams(sessionId, userId, clientType) {
+        return {
+          client_type: String(clientType != null && clientType !== "" ? clientType : "0"),
+          session_id: sessionId,
+          user_id: userId,
+        };
+      }
+
+      function showApiDebugPopup(info) {
+        lastApiDebugInfo = info || null;
+        var mask = document.getElementById("apiDebugMask");
+        var urlEl = document.getElementById("apiDebugUrl");
+        var paramsEl = document.getElementById("apiDebugParams");
+        var respEl = document.getElementById("apiDebugResponse");
+        if (!mask || !urlEl || !paramsEl || !respEl) return;
+        urlEl.textContent = info && info.url ? String(info.url) : "";
+        paramsEl.textContent = info && info.params
+          ? JSON.stringify(info.params, null, 2)
+          : "";
+        respEl.textContent = info && info.response != null
+          ? JSON.stringify(info.response, null, 2)
+          : "";
+        mask.classList.add("is-open");
+        mask.setAttribute("aria-hidden", "false");
+      }
+
+      function hideApiDebugPopup() {
+        var mask = document.getElementById("apiDebugMask");
+        if (!mask) return;
+        mask.classList.remove("is-open");
+        mask.setAttribute("aria-hidden", "true");
+      }
+
+      function bindApiDebugPopupEvents() {
+        var closeBtn = document.getElementById("apiDebugClose");
+        var mask = document.getElementById("apiDebugMask");
+        if (closeBtn) {
+          closeBtn.addEventListener("click", hideApiDebugPopup);
+        }
+        if (mask) {
+          mask.addEventListener("click", function (e) {
+            if (e.target === mask) hideApiDebugPopup();
+          });
+        }
+      }
+
+      function normalizeConversationRole(raw) {
+        var role = String(raw || "").trim().toLowerCase();
+        if (
+          role === "user" ||
+          role === "human" ||
+          role === "customer" ||
+          role === "question" ||
+          role === "1" ||
+          role === "我"
+        ) {
+          return "user";
+        }
+        if (
+          role === "ai" ||
+          role === "assistant" ||
+          role === "bot" ||
+          role === "ubao" ||
+          role === "answer" ||
+          role === "2" ||
+          role === "system"
+        ) {
+          return "ai";
+        }
+        return "";
+      }
+
+      function normalizeConversationApiPayload(res) {
+        if (!res || typeof res !== "object") return null;
+        if (res.code != null) {
+          var code = Number(res.code);
+          if (code !== 200 && code !== 0 && res.success !== true) {
+            throw new Error(res.msg || res.message || "对话接口返回 code " + code);
+          }
+        }
+
+        var root = res.data != null && typeof res.data === "object" ? res.data : res;
+        var rawList =
+          (Array.isArray(root) && root) ||
+          (Array.isArray(root.messages) && root.messages) ||
+          (Array.isArray(root.messageList) && root.messageList) ||
+          (Array.isArray(root.conversation) && root.conversation) ||
+          (Array.isArray(root.conversations) && root.conversations) ||
+          (Array.isArray(root.records) && root.records) ||
+          (Array.isArray(root.list) && root.list) ||
+          null;
+
+        if (!rawList) return null;
+
+        var messages = [];
+        for (var i = 0; i < rawList.length; i++) {
+          var item = rawList[i];
+          if (!item || typeof item !== "object") continue;
+
+          var msgId = item.id != null ? item.id : item.message_id;
+          var role = normalizeConversationRole(
+            item.role || item.sender || item.messageRole || item.type || item.messageType || item.senderType
+          );
+          var content = String(
+            item.content != null
+              ? item.content
+              : item.message != null
+                ? item.message
+                : item.text != null
+                  ? item.text
+                  : ""
+          ).trim();
+
+          if (!role && item.question) {
+            role = "user";
+            content = String(item.question).trim();
+          } else if (!role && item.answer) {
+            role = "ai";
+            content = String(item.answer).trim();
+          } else if (!role && item.userMessage) {
+            role = "user";
+            content = String(item.userMessage).trim();
+          } else if (!role && (item.aiMessage || item.assistantMessage)) {
+            role = "ai";
+            content = String(item.aiMessage || item.assistantMessage).trim();
+          }
+
+          var imageUrls = normalizeHistoryRowImageUrls(item);
+          if (imageUrls.length) {
+            messages.push({
+              id: msgId,
+              role: role || "user",
+              isImage: true,
+              imageUrl: imageUrls[0],
+              content: content,
+            });
+            continue;
+          }
+
+          if (!content) continue;
+
+          var imageUrl = item.imageUrl || item.image || item.imgUrl || item.url;
+          if (imageUrl && /^(https?:)?\/\//i.test(String(imageUrl))) {
+            messages.push({
+              id: msgId,
+              role: role || "user",
+              isImage: true,
+              imageUrl: String(imageUrl),
+            });
+            continue;
+          }
+
+          messages.push({
+            id: msgId,
+            role: role || (messages.length % 2 === 0 ? "user" : "ai"),
+            content: content,
+          });
+        }
+
+        if (!messages.length) return null;
+
+        return {
+          messages: messages,
+          shareTime:
+            root.shareTime ||
+            root.createdAt ||
+            root.createTime ||
+            root.updateTime ||
+            root.timestamp ||
+            res.timestamp,
+          firstQuestion: root.firstQuestion || root.title || root.topic || "",
+          sessionId: root.sessionId || root.session_id || "",
+          userId: root.userId || root.user_id || "",
+        };
+      }
+
+      function fetchConversationHistory(sessionId, userId, clientType) {
+        var requestUrl = buildConversationApiUrl(sessionId, userId, clientType);
+        var requestParams = buildConversationRequestParams(sessionId, userId, clientType);
+        console.log("[kf-conversation-api] GET", requestUrl);
+        return fetch(requestUrl, {
+          method: "GET",
+          mode: "cors",
+          credentials: "omit",
+          headers: { Accept: "application/json" },
+        })
+          .then(function (r) {
+            if (r.ok) {
+              return r.json().then(function (json) {
+                return { ok: true, json: json };
+              });
+            }
+            return r
+              .text()
+              .catch(function () {
+                return "";
+              })
+              .then(function (text) {
+                var hint = "";
+                try {
+                  var j = JSON.parse(text);
+                  hint = j.msg || j.message || "";
+                } catch (eP) {
+                  if (text) hint = text.slice(0, 120);
+                }
+                throw new Error("对话接口 HTTP " + r.status + (hint ? ":" + hint : ""));
+              });
+          })
+          .then(function (result) {
+            showApiDebugPopup({
+              url: requestUrl,
+              params: requestParams,
+              response: result.json,
+            });
+            var data = normalizeConversationApiPayload(result.json);
+            if (!data) {
+              throw new Error("对话接口返回数据为空或格式无法解析");
+            }
+            return data;
+          })
+          .catch(function (err) {
+            showApiDebugPopup({
+              url: requestUrl,
+              params: requestParams,
+              response: { error: err && err.message ? err.message : String(err || "请求失败") },
+            });
+            throw err;
+          });
+      }
+
+      function loadPageData() {
+        var main = document.getElementById("main");
+        var params = getConversationQueryParams();
+        if (!params) {
+          main.innerHTML = '<div class="empty">缺少 session_id 或 user_id 参数</div>';
+          return;
+        }
+
+        var filterIds = parseMessageIdsFromQuery();
+        main.innerHTML = '<div class="empty">对话内容加载中…</div>';
+        fetchConversationHistory(params.sessionId, params.userId, params.clientType)
+          .then(function (data) {
+            if (filterIds && filterIds.length) {
+              var filtered = filterConversationMessagesByIds(data.messages, filterIds);
+              if (!filtered.length) {
+                throw new Error("未找到所选对话内容");
+              }
+              data = Object.assign({}, data, { messages: filtered });
+            }
+            render(data);
+          })
+          .catch(function (e) {
+            var tip = e && e.message ? e.message : "对话加载失败,请稍后重试";
+            console.warn("[kf-conversation-api]", tip, e);
+            main.innerHTML = '<div class="empty">' + escHtml(tip) + "</div>";
+            refreshWxLaunchTagAttrs();
+          });
+      }
+
+      function getFirstUserQuestion(messages) {
+        var list = Array.isArray(messages) ? messages : [];
+        for (var i = 0; i < list.length; i++) {
+          var m = list[i];
+          if (!m || m.role !== "user") continue;
+          if (m.isImage) return "[图片]";
+          var t = String(m.content || "").trim();
+          if (t) return t;
+        }
+        return "";
+      }
+
+      function formatDiscussionTitle(question) {
+        var qText = String(question || "").trim();
+        if (!qText) return "与AI客服对话";
+        if (qText.slice(-3) === "的讨论") return qText;
+        return qText + "的讨论";
+      }
+
+      function normalizeShareTimestamp(ts) {
+        if (ts == null || ts === "") return null;
+        var n = Number(ts);
+        if (!isFinite(n) || n <= 0) return null;
+        if (n < 1e12) n = n * 1000;
+        var d = new Date(n);
+        if (isNaN(d.getTime()) || d.getFullYear() < 2020) return null;
+        return n;
+      }
+
+      function resolveDisplayShareTime(data) {
+        var fromUrl = q("shareTime") || q("share_time");
+        var urlTs = normalizeShareTimestamp(fromUrl);
+        if (urlTs != null) return urlTs;
+        var dataTs = normalizeShareTimestamp(data && data.shareTime);
+        if (dataTs != null) return dataTs;
+        return Date.now();
+      }
+
+      function formatDate(ts) {
+        var normalized = normalizeShareTimestamp(ts);
+        var d = normalized != null ? new Date(normalized) : new Date();
+        return d.getFullYear() + "年" + (d.getMonth() + 1) + "月" + d.getDate() + "日";
+      }
+
+      function renderMessages(messages) {
+        var html = "";
+        var list = Array.isArray(messages) ? messages : [];
+        for (var i = 0; i < list.length; i++) {
+          var msg = list[i];
+          if (!msg) continue;
+          if (msg.role === "user") {
+            if (msg.isImage && msg.imageUrl) {
+              html +=
+                '<div class="row row--user"><div class="user-bubble"><img class="user-bubble__image" src="' +
+                escHtml(msg.imageUrl) +
+                '" alt="图片" loading="lazy" decoding="async" /></div></div>';
+              var imageUserText = String(msg.content || "").trim();
+              if (imageUserText) {
+                html +=
+                  '<div class="row row--user"><div class="user-bubble">' +
+                  escHtml(imageUserText) +
+                  "</div></div>";
+              }
+              continue;
+            }
+            var userText = String(msg.content || "").trim();
+            if (!userText) continue;
+            html +=
+              '<div class="row row--user"><div class="user-bubble">' +
+              escHtml(userText) +
+              "</div></div>";
+            continue;
+          }
+          if (msg.role === "ai" || msg.role === "assistant") {
+            var aiText = String(msg.content || "").trim();
+            if (!aiText) continue;
+            html +=
+              '<div class="row row--ai"><div class="ai-card"><div class="ai-card__text">' +
+              renderAiContentHtml(aiText) +
+              "</div></div></div>";
+          }
+        }
+        return html;
+      }
+
+      function applyWeixinShareMeta() {
+        var siteName = "U店在哪";
+        var iconUrl =
+          "https://alien-volume.oss-cn-beijing.aliyuncs.com/icon/ubao.png";
+        var setMeta = function (key, content) {
+          var el =
+            document.querySelector('meta[property="' + key + '"]') ||
+            document.querySelector('meta[name="' + key + '"]');
+          if (!el) {
+            el = document.createElement("meta");
+            if (key.indexOf("og:") === 0) {
+              el.setAttribute("property", key);
+            } else {
+              el.setAttribute("name", key);
+            }
+            document.head.appendChild(el);
+          }
+          el.setAttribute("content", content);
+        };
+        setMeta("og:site_name", siteName);
+        setMeta("application-name", siteName);
+        setMeta("og:title", "和AI客服的对话");
+        setMeta("og:description", "点击查看对话内容");
+        var links = document.querySelectorAll('link[rel="icon"], link[rel="apple-touch-icon"]');
+        for (var i = 0; i < links.length; i++) {
+          links[i].setAttribute("href", iconUrl);
+        }
+      }
+
+      function countDisplayableMessages(messages) {
+        var list = Array.isArray(messages) ? messages : [];
+        var count = 0;
+        for (var i = 0; i < list.length; i++) {
+          var msg = list[i];
+          if (!msg) continue;
+          if (msg.role === "user") {
+            if (msg.isImage && msg.imageUrl) {
+              count += 1;
+              continue;
+            }
+            if (String(msg.content || "").trim()) count += 1;
+            continue;
+          }
+          if (msg.role === "ai" || msg.role === "assistant") {
+            if (String(msg.content || "").trim()) count += 1;
+          }
+        }
+        return count;
+      }
+
+      function parseMessagesFromContent(text) {
+        var raw = String(text || "").trim();
+        if (!raw) return [];
+        var list = [];
+        var blocks = raw.split(/\n\n+/);
+        for (var i = 0; i < blocks.length; i++) {
+          var block = String(blocks[i] || "").trim();
+          if (!block) continue;
+          var userMatch = block.match(/^我[::]\s*([\s\S]*)$/);
+          if (userMatch) {
+            var userText = String(userMatch[1] || "").trim();
+            if (userText) list.push({ role: "user", content: userText });
+            continue;
+          }
+          var aiMatch = block.match(/^UBAO[::]\s*([\s\S]*)$/i);
+          if (aiMatch) {
+            var aiText = String(aiMatch[1] || "").trim();
+            if (aiText) list.push({ role: "ai", content: aiText });
+          }
+        }
+        if (list.length) return list;
+        var current = null;
+        var lines = raw.split(/\n/);
+        for (var j = 0; j < lines.length; j++) {
+          var line = String(lines[j] || "");
+          var userLine = line.match(/^我[::]\s*(.*)$/);
+          var aiLine = line.match(/^UBAO[::]\s*(.*)$/i);
+          if (userLine) {
+            if (current) list.push(current);
+            current = { role: "user", content: String(userLine[1] || "").trim() };
+            continue;
+          }
+          if (aiLine) {
+            if (current) list.push(current);
+            current = { role: "ai", content: String(aiLine[1] || "").trim() };
+            continue;
+          }
+          if (current && line.trim()) {
+            current.content = (current.content ? current.content + "\n" : "") + line.trim();
+          }
+        }
+        if (current && String(current.content || "").trim()) list.push(current);
+        return list;
+      }
+
+      function resolveShareMessagesForDisplay(data) {
+        var fromArray = Array.isArray(data && data.messages) ? data.messages : [];
+        var fromContent = parseMessagesFromContent((data && data.content) || "");
+        var arrayCount = countDisplayableMessages(fromArray);
+        var contentCount = countDisplayableMessages(fromContent);
+        // 分享链接超长时 messages 会被截断,但 content 仍保留完整对话文本
+        if (contentCount > arrayCount) return fromContent;
+        if (arrayCount) return fromArray;
+        return fromContent;
+      }
+
+      function render(data) {
+        applyWeixinShareMeta();
+        sharePayloadCache = data || null;
+        var main = document.getElementById("main");
+        if (!data) {
+          main.innerHTML = '<div class="empty">对话内容不存在或链接已失效</div>';
+          refreshWxLaunchTagAttrs();
+          return;
+        }
+
+        var messages = resolveShareMessagesForDisplay(data);
+        var firstQuestion =
+          String(data.firstQuestion || "").trim() ||
+          getFirstUserQuestion(messages) ||
+          (function () {
+            var text = String(data.content || "").trim();
+            var m = text.match(/^我[::]([\s\S]+?)(?:\n\n|$)/);
+            return m ? String(m[1] || "").trim() : "";
+          })();
+        var pageTitle = formatDiscussionTitle(firstQuestion);
+        var dateText = formatDate(resolveDisplayShareTime(data));
+
+        document.title = pageTitle;
+
+        var bodyHtml =
+          '<section class="hero">' +
+          '<h1 class="hero__title">' +
+          escHtml(pageTitle) +
+          "</h1>" +
+          '<p class="hero__meta">' +
+          escHtml(dateText) +
+          " · 内容由AI生成,不能完全保障真实</p>" +
+          '<div class="hero__divider"></div>' +
+          "</section>";
+
+        var convHtml = renderMessages(messages);
+        if (convHtml) {
+          bodyHtml +=
+            '<section class="conversation">' +
+            convHtml +
+            '</section><div class="scroll-spacer" aria-hidden="true"></div>';
+        } else {
+          bodyHtml += '<div class="empty">暂无对话内容</div>';
+        }
+
+        main.innerHTML = bodyHtml;
+        refreshWxLaunchTagAttrs();
+      }
+
+      function buildAiConsultOpenParams() {
+        var params = new URLSearchParams();
+        params.set("fromShareAiKfChat", "1");
+        return params;
+      }
+
+      function buildAppDeepLink() {
+        var path = APP_UNI_AI_PATH;
+        var qs = buildAiConsultOpenParams().toString();
+        var root = APP_IOS_URL_SCHEME.replace(/\/$/, "");
+        return root + "/" + path + (qs ? "?" + qs : "");
+      }
+
+      function buildWeChatLaunchExtinfo(useBarePathOnly) {
+        var path = APP_UNI_AI_PATH.replace(/^\//, "");
+        if (useBarePathOnly) return path;
+        var qs = buildAiConsultOpenParams().toString();
+        var uniPage = qs ? path + "?" + qs : path;
+        if (uniPage.length <= 1024) return uniPage;
+        return path + "?fromShareAiKfChat=1";
+      }
+
+      function isWeChatInAppBrowser() {
+        return /MicroMessenger/i.test(navigator.userAgent || "");
+      }
+
+      function getWxShareEntryFrom() {
+        var from = q("from");
+        if (from) return String(from).trim().toLowerCase();
+        try {
+          var h = location.hash || "";
+          var qi = h.indexOf("?");
+          if (qi >= 0) {
+            var hf = new URLSearchParams(h.slice(qi + 1)).get("from");
+            if (hf) return String(hf).trim().toLowerCase();
+          }
+        } catch (eH) {}
+        return "";
+      }
+
+      function logWxEntryDiagnostics() {
+        if (!isWeChatInAppBrowser()) return;
+        console.log("[wx-entry]", {
+          entryFrom: getWxShareEntryFrom() || "(无)",
+          wxJssdkReady: weChatJssdkConfigured,
+          signUrl: getWxConfigSignUrl(),
+        });
+      }
+
+      function isIOSWeChatBrowser() {
+        var ua = navigator.userAgent || "";
+        return /MicroMessenger/i.test(ua) && /iPhone|iPad|iPod/i.test(ua);
+      }
+
+      function isWxDebugOn() {
+        return q("wxDebug") === "1";
+      }
+
+      function isWxForceDebug() {
+        return q("wxForce") === "1";
+      }
+
+      function isWxConfigOnClickDebug() {
+        return q("wxConfigOnClick") === "1";
+      }
+
+      function isWxPcAutoDebugHost() {
+        var h = (location.hostname || "").toLowerCase();
+        if (h === "localhost" || h === "127.0.0.1") return true;
+        for (var i = 0; i < WECHAT_JS_SAFE_HOSTS.length; i++) {
+          if (WECHAT_JS_SAFE_HOSTS[i] === h) return true;
+        }
+        return false;
+      }
+
+      function isWxPcBrowser() {
+        return !isWeChatInAppBrowser();
+      }
+
+      function shouldInitWeChatJssdkOnLoad() {
+        if (isWeChatInAppBrowser()) return true;
+        return isWxForceDebug() || isWxPcAutoDebugHost();
+      }
+
+      function shouldFetchWxConfig(fromUserClick) {
+        if (isWeChatInAppBrowser()) return true;
+        if (fromUserClick) return true;
+        return isWxForceDebug() || isWxPcAutoDebugHost();
+      }
+
+      function getWxHtmlUrl() {
+        var forced = String(q("wxSignUrl") || "").trim();
+        if (forced) return forced.split("#")[0];
+        return String(location.href || "").split("#")[0];
+      }
+
+      function getWxSignPageUrlForApi() {
+        var htmlUrl = getWxHtmlUrl();
+        if (htmlUrl && /^https?:\/\//i.test(htmlUrl)) return htmlUrl;
+        return WX_GET_CONFIG_SIGN_URL;
+      }
+
+      function getWxHtmlUrlBase() {
+        var htmlUrl = getWxSignPageUrlForApi();
+        try {
+          var u = new URL(htmlUrl);
+          return u.origin + u.pathname;
+        } catch (eU) {
+          return WX_GET_CONFIG_SIGN_URL;
+        }
+      }
+
+      /** 与 secondShareGoods 一致:默认用当前页完整 URL 验签(须与微信地址栏一致,含 query) */
+      function getWxConfigSignUrl() {
+        if (String(q("wxSignBaseOnly") || "") === "1") return getWxHtmlUrlBase();
+        return getWxSignPageUrlForApi();
+      }
+
+      function getWxGetConfigApiUrl() {
+        return API_BASE.replace(/\/$/, "") + WECHAT_GET_WX_CONFIG_PATH;
+      }
+
+      function buildWxGetConfigRequestBody(htmlUrl) {
+        return {
+          url: String(htmlUrl || "").split("#")[0].trim(),
+        };
+      }
+
+      function resolveWxConfigAppIdFromSignData(d) {
+        if (!d || typeof d !== "object") return "";
+        var mp =
+          d.mpAppId ||
+          d.mpAppid ||
+          d.officialAppId ||
+          d.gzhAppId ||
+          d.serviceAppId;
+        if (mp != null && String(mp).trim() !== "") return String(mp).trim();
+        var fromQuery = String(q("wxMpAppId") || WECHAT_MP_APP_ID || "").trim();
+        if (fromQuery) return fromQuery;
+        var raw = d.appId || d.appid || d.wxAppId;
+        return raw != null && String(raw).trim() !== "" ? String(raw).trim() : "";
+      }
+
+      function normalizeWxJssdkSignPayload(res, signUrlUsed) {
+        if (!res || typeof res !== "object") return null;
+        var d = res.data != null && typeof res.data === "object" ? res.data : res;
+        if (!d || typeof d !== "object") return null;
+        var appId = resolveWxConfigAppIdFromSignData(d);
+        var timestamp = d.timestamp != null ? d.timestamp : d.timeStamp;
+        var nonceStr =
+          d.nonceStr != null && String(d.nonceStr) !== ""
+            ? d.nonceStr
+            : d.noncestr != null && String(d.noncestr) !== ""
+              ? d.noncestr
+              : d.nonce;
+        var signature = d.signature || d.sign;
+        if (!appId || timestamp == null || nonceStr == null || nonceStr === "" || !signature) {
+          return null;
+        }
+        return {
+          appId: String(appId),
+          timestamp: Number(timestamp),
+          nonceStr: String(nonceStr),
+          signature: String(signature),
+          signUrl: String(signUrlUsed || "")
+            .split("#")[0]
+            .trim(),
+        };
+      }
+
+      function getWxErrMsg(err) {
+        if (!err) return "";
+        if (err.errMsg) return String(err.errMsg);
+        if (typeof err === "string") return err;
+        try {
+          return JSON.stringify(err);
+        } catch (e) {
+          return String(err);
+        }
+      }
+
+      function formatWxConfigErrorTip(err, signPageUrl) {
+        var errMsg = getWxErrMsg(err);
+        var tip = "微信 JSSDK 配置失败";
+        if (/invalid signature/i.test(errMsg)) {
+          return (
+            tip +
+            ":签名无效。请核对:①后端用与前端相同的 url 签名;②url=" +
+            (signPageUrl || getWxHtmlUrl()) +
+            ";③nonceStr/timestamp 与接口返回一致;④appId=" +
+            WECHAT_MP_APP_ID
+          );
+        }
+        if (/require\s*subscribe/i.test(errMsg)) {
+          return tip + ":" + errMsg + "(服务号需用户已关注)";
+        }
+        return errMsg ? tip + ":" + errMsg : tip;
+      }
+
+      function setWxInitError(msg) {
+        wxInitLastError = String(msg || "").trim();
+        if (wxInitLastError) console.warn("[wx]", wxInitLastError);
+      }
+
+      function requestWeChatJssdkSignAndConfig(htmlUrlOptional) {
+        var htmlUrl = String(htmlUrlOptional != null ? htmlUrlOptional : getWxConfigSignUrl())
+          .split("#")[0]
+          .trim();
+        if (!htmlUrl || !/^https?:\/\//i.test(htmlUrl)) {
+          htmlUrl = WX_GET_CONFIG_SIGN_URL;
+        }
+
+        if (isWxDebugOn()) {
+          try {
+            window.alert("htmlUrl(签名用,应与地址栏一致):\n" + htmlUrl);
+          } catch (eDbg) {}
+        }
+
+        var requestUrl = getWxGetConfigApiUrl();
+        var requestBody = buildWxGetConfigRequestBody(htmlUrl);
+        console.log("[wx] htmlUrl=", htmlUrl);
+        console.log("[wx] POST getWxConfig →", requestUrl, requestBody);
+
+        return fetch(requestUrl, {
+          method: "POST",
+          mode: "cors",
+          credentials: "omit",
+          headers: {
+            Accept: "application/json",
+            "Content-Type": "application/json;charset=UTF-8",
+          },
+          body: JSON.stringify(requestBody),
+        })
+          .then(function (r) {
+            if (r.ok) return r.json();
+            return r
+              .text()
+              .catch(function () {
+                return "";
+              })
+              .then(function (text) {
+                var hint = "";
+                try {
+                  var j = JSON.parse(text);
+                  hint = j.msg || j.message || "";
+                } catch (eP) {
+                  if (text) hint = text.slice(0, 120);
+                }
+                throw new Error("getWxConfig HTTP " + r.status + (hint ? ":" + hint : ""));
+              });
+          })
+          .then(function (res) {
+            if (res && res.code != null) {
+              var c = Number(res.code);
+              if (c !== 200 && c !== 0 && res.success !== true) {
+                throw new Error(res.msg || res.message || "getWxConfig code " + c);
+              }
+            }
+            var sign = normalizeWxJssdkSignPayload(res, htmlUrl);
+            if (!sign) {
+              console.warn("[wx] getWxConfig 响应字段不全", res, "htmlUrl=", htmlUrl);
+              throw new Error("getWxConfig 缺少 appId/timestamp/nonceStr/signature(见控制台)");
+            }
+            if (sign.appId !== WECHAT_MP_APP_ID) {
+              console.warn(
+                "[wx] 后端 appId=" + sign.appId + ",期望服务号 " + WECHAT_MP_APP_ID
+              );
+            }
+            if (typeof wx === "undefined") {
+              if (isWxPcBrowser()) {
+                console.log("[wx] PC getWxConfig 成功(无 jweixin)", sign);
+                return true;
+              }
+              setWxInitError("jweixin.js 未加载");
+              return false;
+            }
+            return applyWxConfigFromSign(sign, htmlUrl);
+          });
+      }
+
+      function applyWxConfigFromSign(sign, htmlUrl) {
+        var wxConfigParams = {
+          debug: isWxDebugOn(),
+          appId: String(sign.appId),
+          timestamp: sign.timestamp,
+          nonceStr: String(sign.nonceStr),
+          signature: String(sign.signature),
+          jsApiList: [],
+          openTagList: ["wx-open-launch-app"],
+        };
+        return new Promise(function (resolve) {
+          wx.config(wxConfigParams);
+          wx.ready(function () {
+            weChatJssdkConfigured = true;
+            document.body.classList.add("wx-jssdk-ready");
+            refreshWxLaunchTagAttrs();
+            console.log("[wx.config] ready, htmlUrl=", htmlUrl);
+            resolve(true);
+          });
+          wx.error(function (err) {
+            weChatJssdkConfigured = false;
+            document.body.classList.remove("wx-jssdk-ready");
+            wxJssdkInitPromise = null;
+            var errMsg = getWxErrMsg(err);
+            setWxInitError(formatWxConfigErrorTip(err, htmlUrl));
+            if (isWxDebugOn()) window.alert(wxInitLastError);
+            console.warn("[wx.config]", errMsg, "htmlUrl=", htmlUrl);
+            var baseUrl = getWxHtmlUrlBase();
+            var fullUrl = getWxSignPageUrlForApi();
+            if (
+              !/invalid signature/i.test(errMsg) ||
+              wxConfigSignRetriedBaseUrl ||
+              baseUrl === fullUrl ||
+              htmlUrl === baseUrl
+            ) {
+              resolve(false);
+              return;
+            }
+            wxConfigSignRetriedBaseUrl = true;
+            requestWeChatJssdkSignAndConfig(baseUrl).then(resolve);
+          });
+        });
+      }
+
+      function refreshWxLaunchTagAttrs(useBarePathOnly) {
+        var tag = document.getElementById("launch-btn");
+        if (!tag) return;
+        try {
+          tag.setAttribute("appid", WECHAT_OPEN_APP_ID);
+          tag.setAttribute("extinfo", buildWeChatLaunchExtinfo(!!useBarePathOnly));
+          console.log("[wx-open-launch-app] extinfo=", tag.getAttribute("extinfo"));
+        } catch (eA) {}
+      }
+
+      function bindWeChatLaunchTagEvents() {
+        var tag = document.getElementById("launch-btn");
+        if (!tag || tag._wxLaunchBound) return;
+        tag._wxLaunchBound = true;
+        refreshWxLaunchTagAttrs();
+        tag.addEventListener("launch", function () {
+          console.log("[wx-open-launch-app] launch ok");
+        });
+        tag.addEventListener("error", function (e) {
+          var detail = e && e.detail;
+          var errMsg =
+            detail && detail.errMsg
+              ? String(detail.errMsg)
+              : detail && detail.errmsg
+                ? String(detail.errmsg)
+                : "";
+          console.warn(
+            "[wx-open-launch-app]",
+            detail,
+            "extinfo=",
+            tag.getAttribute("extinfo")
+          );
+
+          if (/launch:fail_check/i.test(errMsg)) {
+            showAppOpenFailTip(
+              "请用微信分享卡片进入,或确认已安装最新版「U店在哪」"
+            );
+            return;
+          }
+
+          // if (
+          //   /launch:fail/i.test(errMsg) &&
+          //   !tag._wxLaunchBareRetried &&
+          //   tag.getAttribute("extinfo") !== buildWeChatLaunchExtinfo(true)
+          // ) {
+          //   tag._wxLaunchBareRetried = true;
+          //   refreshWxLaunchTagAttrs(true);
+          //   showFabToast("请再点一次「和U宝继续聊」");
+          //   return;
+          // }
+
+          if (/launch:fail/i.test(errMsg) && !getWxShareEntryFrom()) {
+            showAppOpenFailTip("请前往应用商店下载U店在哪app");
+            return;
+          }
+
+          showAppOpenFailTip(
+            errMsg
+              ? "未能打开 App:" + errMsg
+              : "未能打开 App,请确认已安装最新版「U店在哪」"
+          );
+        });
+      }
+
+      function initWeChatOpenLaunchApp(fromUserClick) {
+        if (!shouldFetchWxConfig(!!fromUserClick)) {
+          return Promise.resolve(false);
+        }
+        if (wxJssdkInitPromise && !fromUserClick) return wxJssdkInitPromise;
+
+        wxConfigSignRetriedBaseUrl = false;
+        wxInitLastError = "";
+        var htmlUrl = getWxConfigSignUrl();
+
+        bindWeChatLaunchTagEvents();
+        wxJssdkInitPromise = requestWeChatJssdkSignAndConfig(htmlUrl)
+          .then(function (ok) {
+            if (ok === true) return true;
+            if (!wxInitLastError) {
+              setWxInitError("wx.config 失败,可加 ?wxDebug=1 查看 htmlUrl");
+            }
+            return false;
+          })
+          .catch(function (e) {
+            var msg = e && e.message ? e.message : "getWxConfig 请求失败";
+            setWxInitError(msg);
+            console.warn("[wx] requestWeChatJssdkSignAndConfig failed", msg, "htmlUrl=", htmlUrl);
+            if (isWeChatInAppBrowser() && isWxDebugOn()) window.alert(msg);
+            return false;
+          })
+          .finally(function () {
+            if (!weChatJssdkConfigured) wxJssdkInitPromise = null;
+          });
+
+        return wxJssdkInitPromise;
+      }
+
+      function scheduleWeChatJssdkBootstrap() {
+        if (!shouldInitWeChatJssdkOnLoad()) return;
+        var attempts = 0;
+        function tick() {
+          attempts += 1;
+          if (weChatJssdkConfigured) return;
+          initWeChatOpenLaunchApp();
+          if (!weChatJssdkConfigured && attempts < 8 && typeof wx === "undefined") {
+            setTimeout(tick, 400);
+          }
+        }
+        if (isIOSWeChatBrowser()) {
+          setTimeout(tick, 350);
+        } else {
+          tick();
+        }
+      }
+
+      function showFabToast(msg, ms) {
+        var tip = String(msg || "").trim();
+        if (!tip) return;
+        var el = document.getElementById("openAppToast");
+        if (el) {
+          el.textContent = tip;
+          el.style.display = "block";
+          if (showFabToast._t) clearTimeout(showFabToast._t);
+          showFabToast._t = setTimeout(function () {
+            el.style.display = "none";
+          }, ms || 2800);
+        }
+        console.log("[openApp]", tip);
+      }
+
+      function showDownloadTip() {
+        var msg = "请到应用商店下载「U店在哪」";
+        if (typeof uni !== "undefined" && typeof uni.showToast === "function") {
+          uni.showToast({ title: msg, icon: "none", duration: 2500 });
+        } else {
+          window.alert(msg);
+        }
+      }
+
+      function showAppOpenFailTip(msg) {
+        var tip = msg || "未能打开 App,请确认已安装最新版「U店在哪」。";
+        if (typeof uni !== "undefined" && typeof uni.showToast === "function") {
+          uni.showToast({ title: msg, icon: "none", duration: 2800 });
+        } else if (isWeChatInAppBrowser()) {
+          window.alert(tip);
+        } else {
+          showFabToast(tip);
+        }
+      }
+
+      function launchAppDeepLink(deepLink) {
+        try {
+          var a = document.createElement("a");
+          a.href = deepLink;
+          a.setAttribute("target", "_self");
+          document.body.appendChild(a);
+          a.click();
+          document.body.removeChild(a);
+        } catch (e1) {}
+        try {
+          window.location.href = deepLink;
+        } catch (e2) {}
+      }
+
+      function tryOpenHBuilderAppViaScheme() {
+        var deepLink = buildAppDeepLink();
+
+        if (typeof plus !== "undefined" && plus.runtime) {
+          var installed = null;
+          try {
+            if (typeof plus.runtime.isApplicationExist === "function") {
+              installed = plus.runtime.isApplicationExist({
+                pname: APP_ANDROID_PACKAGE,
+                action: APP_IOS_URL_SCHEME,
+              });
+            }
+          } catch (e) {
+            console.warn(e);
+          }
+          if (installed === false) {
+            showDownloadTip();
+            return;
+          }
+          try {
+            plus.runtime.openURL(deepLink);
+          } catch (e2) {
+            console.warn(e2);
+            showDownloadTip();
+          }
+          return;
+        }
+
+        var done = false;
+        function finish() {
+          if (done) return;
+          done = true;
+          document.removeEventListener("visibilitychange", onVis);
+          window.removeEventListener("pagehide", onHide);
+        }
+        function onVis() {
+          if (document.visibilityState === "hidden") finish();
+        }
+        function onHide() {
+          finish();
+        }
+        document.addEventListener("visibilitychange", onVis);
+        window.addEventListener("pagehide", onHide);
+
+        try {
+          launchAppDeepLink(deepLink);
+        } catch (e3) {
+          finish();
+          showDownloadTip();
+          return;
+        }
+
+        window.setTimeout(function () {
+          finish();
+        }, 3200);
+      }
+
+      function tryFetchWxConfigOnPcClick() {
+        if (!isWxPcBrowser()) return Promise.resolve(false);
+        showFabToast("正在请求 getWxConfig…");
+        wxJssdkInitPromise = null;
+        return initWeChatOpenLaunchApp(true).then(function (ok) {
+          if (ok) {
+            showFabToast(
+              weChatJssdkConfigured
+                ? "getWxConfig 成功,wx.config 已就绪"
+                : "getWxConfig 成功"
+            );
+          } else {
+            showFabToast(wxInitLastError || "getWxConfig 失败");
+          }
+          return ok;
+        });
+      }
+
+      function tryOpenHBuilderApp() {
+        if (isWeChatInAppBrowser()) return;
+        if (!isWxPcBrowser()) {
+          tryOpenHBuilderAppViaScheme();
+          return;
+        }
+        tryFetchWxConfigOnPcClick().then(function () {
+          if (isWxConfigOnClickDebug() && !isWxForceDebug() && !isWxPcAutoDebugHost()) {
+            return;
+          }
+          tryOpenHBuilderAppViaScheme();
+        });
+      }
+
+      function boot() {
+        var launchTag = document.getElementById("launch-btn");
+        if (launchTag) launchTag.setAttribute("appid", WECHAT_OPEN_APP_ID);
+        bindWeChatLaunchTagEvents();
+        bindApiDebugPopupEvents();
+
+        if (isWeChatInAppBrowser()) {
+          document.body.classList.add("is-wechat");
+          logWxEntryDiagnostics();
+        }
+
+        if (shouldInitWeChatJssdkOnLoad()) {
+          if (isWxPcBrowser() && (isWxForceDebug() || isWxPcAutoDebugHost())) {
+            document.body.classList.add("wx-pc-debug");
+          }
+          scheduleWeChatJssdkBootstrap();
+        }
+
+        document.addEventListener("WeixinOpenTagsError", function (e) {
+          console.warn("[WeixinOpenTagsError]", e && e.detail);
+        });
+
+        if (isWeChatInAppBrowser()) {
+          var openBtnWx = document.getElementById("openApp");
+          if (openBtnWx) {
+            openBtnWx.addEventListener("click", function () {
+              if (!weChatJssdkConfigured) {
+                showFabToast(
+                  wxInitLastError || "微信 SDK 初始化中,请稍候再点底部按钮"
+                );
+              }
+            });
+          }
+        } else {
+          var openAppBtn = document.getElementById("openApp");
+          if (openAppBtn) {
+            openAppBtn.addEventListener("click", tryOpenHBuilderApp);
+          }
+        }
+
+        loadPageData();
+      }
+
+      if (document.readyState === "complete") {
+        boot();
+      } else {
+        window.addEventListener("load", boot);
+      }
+    })();
+  </script>
+</body>
+</html>