<template>
  <view class="deepMate-page">
    <!-- 顶部导航栏 -->
    <view class="header" :style="{ paddingTop: safeAreaInsets?.top + 'px' }">
      <view class="header-left">
        <image
          src="https://d31zlh4on95l9h.cloudfront.net/images/f91e09b5987802185e7679055dafd272.svg"
          class="icon"
          @click="goToCustomerService"
        >
        </image>
      </view>
      <view class="header-center">
        <text class="title" :style="{ paddingTop: safeAreaInsets?.top + 'px' }"
          >DeepMate</text
        >
      </view>
      <view class="header-right">
        <image
          src="https://d31zlh4on95l9h.cloudfront.net/images/d7c4e74201213a25dd9574e908233928.svg"
          class="icon"
          @click="goToNotice"
          @tap="goToNotice"
        >
        </image>
        <image
          style="margin-left: 10px"
          src="https://d31zlh4on95l9h.cloudfront.net/images/099903c4aabf5713488b5cb60815e3f7.svg"
          class="icon"
          @click="openHistoryDrawer"
        ></image>
        <!-- 新增新会话按钮
        <button class="new-chat-button" @click="newChat">
          <text class="new-chat-text">新会话</text>
        </button> -->
      </view>
    </view>

    <!-- 主要内容区域 -->
    <view class="main-content">
      <view class="banner-panel" v-if="messages.length === 0">
        <image
          src="https://d31zlh4on95l9h.cloudfront.net/images/42e18bd7fe97d4f4f37aa70439a0990b.svg"
          class="pray-banner"
        ></image>
        <view class="contain">
          <!-- 机器人头像和欢迎语 -->
          <view class="robot-container" v-if="messages.length === 0">
            <image src="/static/icons/机器人.svg" class="robot-avatar"></image>
            <view class="welcome-message">
              <text class="greeting">Hi, 我是您的股市随身顾问~</text>
              <text class="description"
                >个股诊断、市场情绪解读，都可以找我。</text
              >
            </view>
          </view>

          <!-- 功能标签栏 -->
          <!-- <view class="function-tabs" v-if="messages.length === 0">
         <view ref="tabsTrack" class="tabs-track" :style="{ transform: 'translate3d(-' + marqueeOffset + 'px,0,0)' }">
           <view class="tab-item" v-for="(tab, idx) in marqueeList" :key="idx">{{ tab }}</view>
         </view>
         </view> -->

          <!-- 特斯拉推荐卡片 -->
          <view
            class="recommend-card"
            v-if="messages.length === 0"
            @click="goinstitutionalTrendsBriefing"
          >
            <view class="arrow" v-if="messages.length === 0"></view>
            <view class="card-content">
              <image
                src="../../static/images/tesla-logo.png"
                class="logo"
              ></image>
              <view class="card-text">
                <text class="main-question">当前特斯拉该如何布局？</text>
                <text class="stock-code">TSLA</text>
              </view>
              <image
                src="https://d31zlh4on95l9h.cloudfront.net/images/40d94054644f6e3f1c366751f07f0010.svg"
                class="arrow-icon"
                @click="goinstitutionalTrendsBriefing"
              ></image>
            </view>
          </view>
        </view>
      </view>

      <!-- 可能感兴趣的话题 -->
      <!-- <view v-if="messages.length === 0" class="interest-section">
        <text class="section-title">- 您可能感兴趣 -</text>
        <view class="topics-list">
          <view class="topic-item" v-for="topic in hotTopics" :key="topic.id">
            <image :src="topic.icon" class="tag-icon"></image>
            <text class="topic-text" @click="sendMessageList(topic.text)">{{
              topic.text
            }}</text>
          </view>
        </view>
      </view> -->
      <view v-if="messages.length === 0" class="welcome-section"> </view>

      <!-- 聊天区域 -->
      <!-- 顶部粘性欢迎块：始终保留在聊天上方 -->
      <view class="chat-header" v-if="messages.length > 0">
        <view class="robot-container">
          <image src="/static/icons/机器人.svg" class="robot-avatar"></image>
          <view class="welcome-message">
            <text class="greeting">Hi, 我是您的股市随身顾问~</text>
          </view>
        </view>
      </view>
      <scroll-view
        class="chat-container"
        scroll-y="true"
        :scroll-top="chatScrollTop"
        :scroll-with-animation="!isSending"
        @scroll="onChatScroll"
        v-if="messages.length > 0"
      >
        <view class="message-list" id="messageList">
          <view
            v-for="(message, index) in messages"
            :key="index"
            :class="
              message.isUser ? 'message user-message' : 'message bot-message'
            "
          >
            <!-- 会话图标 -->
            <text
              :class="
                message.isUser
                  ? 'fa-solid fa-user message-icon'
                  : 'fa-solid fa-robot message-icon'
              "
            ></text>
            <!-- 会话内容 -->
            <view class="message-content">
              <!-- <text class="message-text">{{ message.content }}</text> -->
              <!-- loading -->
              <view
                class="loading-dots"
                v-if="message.isThinking || !message.isUser"
              >
                <view class="thinking-process">
                  <view class="thinking-header">
                    <view class="thinking-icon">∞</view>
                    <view class="thinking-title">{{
                      message.isTyping ? "正在思考" : "思考完成"
                    }}</view>
                    <view class="thinking-count"> </view>
                    <view
                      class="thinking-toggle"
                      @click="message.isThinking = !message.isThinking"
                    >
                      <span v-if="message.isThinking">↑</span>
                      <span v-else>↓</span>
                    </view>
                  </view>
                  <view v-show="message.isThinking" class="thinking-content">
                    <view class="thinking-item">
                      <view class="item-status">
                        <span v-if="message.isFirst" class="checkmark">✓</span>
                      </view>
                      <view class="item-text">问题分析完成</view>
                    </view>
                    <view class="thinking-item">
                      <view class="item-status">
                        <span v-if="message.isSecond" class="checkmark">✓</span>
                      </view>
                      <view class="item-text">收集相关信息</view>
                    </view>
                  </view>
                </view>
              </view>
              <!-- 使用 rich-text 渲染 Markdown 内容 -->
              <rich-text
                v-if="!message.isUser"
                class="message-text"
                :nodes="renderMarkdown(message.content)"
              ></rich-text>
              <text v-else class="message-text">{{ message.content }}</text>
            </view>
          </view>
        </view>
      </scroll-view>
    </view>

    <!-- 输入框区域 -->
    <view class="input-area">
      <view class="input-wrapper">
        <input
          type="text"
          placeholder="请输入股票代码/名称，获取AI洞察"
          placeholder-style="color:#fff;opacity:1"
          class="input-field"
          v-model="inputMessage"
          @confirm="sendMessage"
        />
        <image class="send-button" @click="sendMessage" :disabled="isSending">
          <!-- <image
            src="https://d31zlh4on95l9h.cloudfront.net/images/95f1ea2262e9157db13c93c0dc1c5d96.svg"
            class="send-icon"
          ></image> -->
        </image>
      </view>
      <text class="disclaimer"
        >以上数据由AI生成，不作为最终投资建议，决策需独立！</text
      >
    </view>

    <image
      class="back-to-top"
      src="https://d31zlh4on95l9h.cloudfront.net/images/ba357635d2bb480241952bb1cabacd73.svg"
      :style="{
        transform: 'translate3d(' + backTopX + 'px,' + backTopY + 'px,0)',
      }"
      @touchstart="onBackTopTouchStart"
      @touchmove="onBackTopTouchMove"
      @touchend="onBackTopTouchEnd"
      @click="onBackTopClick"
    ></image>

    <!-- 搜索历史侧拉框 -->
    <view class="drawer-overlay" v-show="showHistoryDrawer"></view>
    <view
      class="drawer-panel"
      v-show="showHistoryDrawer"
      @click.stop
      @touchmove.stop.prevent
      :style="{ transform: 'translateY(' + drawerOffsetY + 'px)' }"
    >
      <view class="drawer-header">
        <text class="drawer-title">历史对话</text>
        <view class="drawer-actions">
          <view class="delete-all-container">
            <image
              class="delete-icon"
              src="/static/icons/Group_48095481.svg"
            ></image>
            <text class="delete-all" @click="clearAllHistory">删除全部</text>
          </view>
          <view class="drawer-close" @click="onDrawerBackClick"
            ><text class="drawer-close-icon"></text
          ></view>
        </view>
      </view>
      <scroll-view scroll-y="true" class="drawer-content">
        <view class="drawer-inner">
          <view v-if="groupedHistory.length === 0" class="empty-history">
            <text>暂无历史记录</text>
          </view>
          <view
            v-for="(section, sIdx) in groupedHistory"
            :key="sIdx"
            class="history-section"
          >
            <text class="section-title">{{ section.title }}</text>
            <view
              v-for="(item, idx) in section.items"
              :key="idx"
              class="history-item"
            >
              <view class="history-left">
                <view class="flag-circle"
                  ><text class="flag-emoji">🇺🇸</text></view
                >
              </view>
              <view class="history-main" @click="itemClick(item)">
                <text class="history-query">{{ item.stockName }}</text>
                <text class="history-query">（{{ item.stockCode }}）</text>
              </view>
              <text class="history-time">{{
                formatTimeForHistory(item.createdTime)
              }}</text>
            </view>
          </view>
        </view>
      </scroll-view>
    </view>
    <footerBar class="static-footer" :type="type"></footerBar>
  </view>
  <LoginPrompt ref="loginPrompt"></LoginPrompt>
</template>

<script setup>
const { safeAreaInsets } = uni.getSystemInfoSync();

import { ref, computed, onMounted, onUnmounted, watch, nextTick } from "vue";
import footerBar from "../../components/footerBar";
import marked from "marked"; // 引入 marked 库
import { onPageScroll } from "@dcloudio/uni-app";
import {
  postStock,
  postIntent,
  postHistory,
  postHistoryDetail,
} from "../../api/deepMate/deepMate";

const renderer = new marked.Renderer();
renderer.heading = function (text, level) {
  return `<p>${text}</p>`;
};
// 设置 marked 选项
marked.setOptions({
  renderer: new marked.Renderer(),
  highlight: null, // 如果需要代码高亮，可以设置适当的函数
  langPrefix: "language-",
  pedantic: false,
  gfm: true,
  breaks: false,
  sanitize: false,
  smartLists: true,
  smartypants: false,
  xhtml: false,
});
// 创建一个用于渲染 Markdown 的函数
const renderMarkdown = (content) => {
  if (!content) return "";
  return marked.parse(content);
};

const type = ref("deepMate");
const inputMessage = ref("");
const showThinking = ref(true);
const isSending = ref(false);
const chatScrollTop = ref(0);
const chatContainerHeight = ref(0);
const uuid = ref("");
const messages = ref([]);
const showHistoryDrawer = ref(false);
const drawerOffsetY = ref(0);
const searchHistory = ref([]);
const historyList = ref([]);

const hotTopics = ref([
  {
    id: 1,
    text: "英伟达(NVDA)股票情绪温度？",
    icon: "https://d31zlh4on95l9h.cloudfront.net/images/7ed58be0f4b81aeb398d9ba2534a624b.svg",
  },
  {
    id: 2,
    text: "博通(AVGO)明天还能涨吗？",
    icon: "https://d31zlh4on95l9h.cloudfront.net/images/7ed58be0f4b81aeb398d9ba2534a624b.svg",
  },
  {
    id: 3,
    text: "为什么Fluence Energy(FLNC)会暴涨？",
    icon: "https://d31zlh4on95l9h.cloudfront.net/images/7ed58be0f4b81aeb398d9ba2534a624b.svg",
  },
  {
    id: 4,
    text: "为什么Fluence Energy(FLNC)会暴涨？",
    icon: "https://d31zlh4on95l9h.cloudfront.net/images/7ed58be0f4b81aeb398d9ba2534a624b.svg",
  },
]);

// 初始化
onMounted(() => {
  const sys = uni.getSystemInfoSync();
  const iconSize = uni.upx2px(100); // 和样式保持一致
  const reserveBottom = uni.upx2px(260); // 预留底部输入区域空间
  const initX = Math.max(0, sys.windowWidth - iconSize - uni.upx2px(30));
  const initY = Math.max(0, Math.floor(sys.windowHeight * 0.65) - iconSize);
  backTopTargetX.value = initX;
  backTopTargetY.value = initY;
  backTopX.value = initX;
  backTopY.value = initY;

  initUUID();
  if (messages.value.length === 0) {
    // nextTick(startTabsMarquee);
  }
  if (messages.value.length > 0) {
    nextTick(() => {
      measureChatContainer();
      scrollToBottom();
    });
  }

  // 载入历史
  // const hist = uni.getStorageSync("search_history") || [];
  // searchHistory.value = Array.isArray(hist) ? hist : [];

  // 缓存今天日期（YYYY-MM-DD）
  const todayStr = new Date().toISOString().slice(0, 10);
  uni.setStorageSync("today_date", todayStr);
});

// 初始化 UUID
const initUUID = () => {
  let storedUUID = uni.getStorageSync("user_uuid");
  if (!storedUUID) {
    storedUUID = generateUUID();
    uni.setStorageSync("user_uuid", storedUUID);
  }
  uuid.value = storedUUID;
};

// 生成简单UUID
const generateUUID = () => {
  return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) {
    var r = (Math.random() * 16) | 0,
      v = c == "x" ? r : (r & 0x3) | 0x8;
    return v.toString(16);
  });
};

// 计算聊天容器可视高度
const measureChatContainer = () => {
  const q = uni.createSelectorQuery();
  q.select(".chat-container").boundingClientRect();
  q.exec((res) => {
    chatContainerHeight.value = res[0]?.height || 0;
  });
};

// 新会话
const newChat = () => {
  messages.value = [];
  uni.removeStorageSync("user_uuid");
  initUUID();
};

// 跳转到空白页
const goinstitutionalTrendsBriefing = () => {
  uni.navigateTo({
    url: "/pages/blank/institutionalTrendsBriefing",
  });
};

// 跳转到客户服务平台首页
const goToCustomerService = () => {
  uni.navigateTo({
    url: "/pages/customerServicePlatform/csPlatformIndex",
  });
};
// 跳转到通知页
function goToNotice() {
  try {
    console.log("goToNotice: navigating to /pages/blank/notice");
    uni.navigateTo({ url: "/pages/blank/notice" });
  } catch (e) {
    console.error("goToNotice navigateTo failed, fallback to redirect:", e);
    uni.redirectTo({ url: "/pages/blank/notice" });
  }
}

// 历史记录
const openHistoryDrawer = async () => {
  const res = await postHistory({
    model: 5,
  });

  if (res.code === 200) {
    historyList.value = res.data;
  }

  console.log("historyList.value", historyList.value);

  const hideDistance = uni.upx2px(900);
  drawerOffsetY.value = hideDistance;
  showHistoryDrawer.value = true;
  setTimeout(() => {
    drawerOffsetY.value = 0;
  }, 10);
};
const closeHistoryDrawer = () => {
  showHistoryDrawer.value = false;
};
const onDrawerBackClick = () => {
  const hideDistance = uni.upx2px(900);
  drawerOffsetY.value = hideDistance;
  setTimeout(() => {
    closeHistoryDrawer();
    drawerOffsetY.value = 0;
  }, 180);
};

// 时间格式化：YYYY-MM-DD HH:mm
const pad2 = (n) => (n < 10 ? "0" + n : "" + n);
const formatTime = (t) => {
  const d = new Date(t);
  const y = d.getFullYear();
  const m = pad2(d.getMonth() + 1);
  const day = pad2(d.getDate());
  const hh = pad2(d.getHours());
  const mm = pad2(d.getMinutes());
  return `${y}-${m}-${day} ${hh}:${mm}`;
};

// 为历史记录格式化时间：YYYY-MM-DD HH:mm
const formatTimeForHistory = (timeString) => {
  // 假设 timeString 格式为 "YYYY-MM-DD HH:mm:ss"
  const parts = timeString.split(" ");
  if (parts.length >= 2) {
    const datePart = parts[0];
    const timePart = parts[1];
    const timeParts = timePart.split(":");
    if (timeParts.length >= 2) {
      return `${datePart} ${timeParts[0]}:${timeParts[1]}`;
    }
  }
  return timeString;
};

// 历史分组（今天/昨天/近一周/按月）
const groupedHistory = computed(() => {
  const sections = [];

  // 从缓存获取今天日期，如果没有则使用当前日期
  const now = new Date();

  const startOfDay = (d) =>
    new Date(d.getFullYear(), d.getMonth(), d.getDate());
  const isSameDay = (a, b) =>
    startOfDay(a).getTime() === startOfDay(b).getTime();
  const isYesterday = (d) => {
    const y = new Date(now.getFullYear(), now.getMonth(), now.getDate() - 1);
    return isSameDay(d, y);
  };
  const isToday = (d) => isSameDay(d, now);
  const withinLast7Days = (d) => {
    const seven = new Date(
      now.getFullYear(),
      now.getMonth(),
      now.getDate() - 7
    );
    return d >= seven && !isToday(d) && !isYesterday(d);
  };
  const monthLabel = (d) => `${d.getMonth() + 1}月`;

  const today = [];
  const yesterday = [];
  const last7 = [];
  const byMonth = new Map();

  // 使用 historyList.value 替代 searchHistory.value
  historyList.value.forEach((item) => {
    // 根据你的数据结构，使用 createdTime 字段
    const dt = new Date(item.createdTime);
    if (isToday(dt)) {
      today.push(item);
    } else if (isYesterday(dt)) {
      yesterday.push(item);
    } else if (withinLast7Days(dt)) {
      last7.push(item);
    } else {
      const year = dt.getFullYear();
      const month = dt.getMonth() + 1;
      const key = `${year}-${month}`;
      if (!byMonth.has(key))
        byMonth.set(key, {
          title: `${year}年${month}月`,
          year,
          month,
          items: [],
        });
      byMonth.get(key).items.push(item);
    }
  });

  if (today.length) sections.push({ title: "今天", items: today });
  if (yesterday.length) sections.push({ title: "昨天", items: yesterday });
  if (last7.length) sections.push({ title: "近一周", items: last7 });

  const monthSections = Array.from(byMonth.values()).sort((a, b) => {
    if (a.year !== b.year) return b.year - a.year;
    return b.month - a.month; // 月份倒序，如 10月 在 9月 之前
  });
  sections.push(...monthSections);

  return sections;
});

const clearAllHistory = () => {
  searchHistory.value = [];
  // uni.setStorageSync("search_history", []);
};

// 发送消息
const sendMessage = () => {
  if (inputMessage.value.trim() === "" || isSending.value) return;

  const userMessage = {
    content: inputMessage.value,
    isUser: true,
    isThinking: false,
    isTyping: false,
  };

  messages.value.push(userMessage);
  inputMessage.value = "";

  // 记录搜索历史
  // const entry = { query: userMessage.content, time: Date.now() };
  // searchHistory.value.unshift(entry);
  // uni.setStorageSync("search_history", searchHistory.value);

  // 发送后强制恢复并滚到底部
  shouldAutoScroll.value = true;
  nextTick(() => {
    scrollToBottom();
  });

  // 模拟机器人回复
  simulateBotResponse(userMessage.content);
};

// 模拟机器人回复
const simulateBotResponse = async (userMessage) => {
  // 添加机器人加载消息
  const botMsg = {
    content: "",
    isUser: false,
    isTyping: true,
    isThinking: true,
    isFirst: false,
    isSecond: false,
  };

  messages.value.push(botMsg);

  isSending.value = true;

  // 首先进行意图识别
  let res;
  try {
    res = await postIntent({
      content: userMessage,
      language: "cn",
      marketList: "hk,cn,usa,my,sg,vi,in,gb",
      token:
        "pCtw6AYK0EHAaIexoFHsbZjtsfEAIhcmwkCFm6uKko8VPfMvyDiODL9v9c0veic9fIpQbvT8zN4sH/Si6Q",
    });
  } catch (error) {

  } finally {
    isSending.value = false;
  }

  console.log("res" + res);

  // 意图识别不通过
  if (res.code !== 200) {
    console.log("未通过意图识别");

    messages.value[messages.value.length - 1].isThinking = false;

    // 更新机器人的消息内容
    const errorMessage = res.message || "请求失败，请稍后重试";
    let responseText = `我已经收到您的消息: "${userMessage}"。错误信息: "${errorMessage}"`;

    // 开始打字机效果显示错误信息
    let index = 0;
    const botIndex = messages.value.length - 1;

    const typeWriter = () => {
      if (index < responseText.length) {
        const ch = responseText.charAt(index);
        const current = messages.value[botIndex];
        // 通过数组替换触发渲染，避免部分平台对子项属性变更不响应
        messages.value.splice(botIndex, 1, {
          ...current,
          content: current.content + ch,
          isTyping: true,
        });
        index++;
        scrollToBottom();

        // 字符间延迟，模拟打字效果
        const baseDelay = 5; // 普通字符基础延迟（毫秒）
        const slowPunct = /[。！？!?；;]/; // 句号、感叹号、分号等较长停顿
        const midPunct = /[，、,:：]/; // 逗号、顿号、冒号等中等停顿
        const delay = slowPunct.test(ch)
          ? 220
          : midPunct.test(ch)
          ? 120
          : baseDelay;
        setTimeout(typeWriter, delay);
      } else {
        // 打字完成，更新状态
        const current = messages.value[botIndex];
        messages.value.splice(botIndex, 1, { ...current, isTyping: false });
        isSending.value = false;
        nextTick(() => {
          scrollToBottom();
        });
      }
    };

    // 启动打字机效果
    setTimeout(typeWriter, 300);
    return;
  }

  console.log("通过意图识别");
  messages.value[messages.value.length - 1].isFirst = true;

  // 获取意图识别结果
  const recordId = res.data.recordId;
  const parentId = res.data.parentId;
  const stockId = res.data.stockId;

  // 获取股票信息
  const StockInfo = await postStock({
    language: "cn",
    token:
      "pCtw6AYK0EHAaIexoFHsbZjtsfEAIhcmwkCFm6uKko8VPfMvyDiODL9v9c0veic9fIpQbvT8zN4sH/Si6Q",
    recordId: Number(recordId),
    parentId: Number(parentId),
    stockId: Number(stockId),
  });
  console.log("postStock payload", {
    language: "cn",
    token: "790750702588f1ea79f24dc56ccd5d8a",
    recordId,
    parentId,
    stockId,
  });
  console.log("StockInfo", StockInfo);

  const cftl = StockInfo?.cftl || {};
  const date = StockInfo?.date || "";

  if (StockInfo && StockInfo.code !== 200) {
    const errMsg = `postStock失败(${StockInfo.code}): ${
      StockInfo.message || "未知错误"
    }`;
    console.warn(errMsg, StockInfo);
    messages.value[messages.value.length - 1].isThinking = false;
    messages.value[messages.value.length - 1].isTyping = false;
    messages.value[messages.value.length - 1].content = errMsg;
    isSending.value = false;
    return;
  }

  const markdown = StockInfo?.data?.markdown || "抱歉，未找到该股票";
  console.log("StockInfo", StockInfo);

  // 添加请求延迟
  // const toDataInfo = await getData();
  // console.log(toDataInfo);
  // dataInfo.value = toDataInfo.data;
  // console.log(dataInfo.value);

  messages.value[messages.value.length - 1].isSecond = true;

  messages.value[messages.value.length - 1].isThinking = false;

  // 滚动到底部
  nextTick(() => {
    scrollToBottom();
  });

  // 模拟流式响应
  let responseText = `我已经收到您的消息: "${userMessage}"。+"${markdown}"  `;
  let index = 0;

  const botIndex = messages.value.length - 1;
  const baseDelay = 5; // 普通字符基础延迟（毫秒）
  const slowPunct = /[。！？!?；;]/; // 句号、感叹号、分号等较长停顿
  const midPunct = /[，、,:：]/; // 逗号、顿号、冒号等中等停顿

  const typeWriter = () => {
    if (index < responseText.length) {
      const ch = responseText.charAt(index);
      const current = messages.value[botIndex];
      // 通过数组替换触发渲染，避免部分平台对子项属性变更不响应
      messages.value.splice(botIndex, 1, {
        ...current,
        content: current.content + ch,
        isTyping: true,
      });
      index++;
      scrollToBottom();

      const delay = slowPunct.test(ch)
        ? 220
        : midPunct.test(ch)
        ? 120
        : baseDelay;
      setTimeout(typeWriter, delay);
    } else {
      const current = messages.value[botIndex];
      messages.value.splice(botIndex, 1, { ...current, isTyping: false });
      isSending.value = false;
      nextTick(() => {
        scrollToBottom();
      });
    }
  };

  // 启动前稍作停顿，避免过快开始
  setTimeout(typeWriter, 500);

  console.log("messages", messages);
};

// 当消息出现或变化时，测量容器并滚到底部
watch(messages, (arr) => {
  if (arr.length > 0) {
    nextTick(() => {
      measureChatContainer();
      scrollToBottom();
    });
  }
});

// 滚动到底部（仅聊天区域滚动）
const scrollToBottom = () => {
  if (!shouldAutoScroll.value) return;
  const query = uni.createSelectorQuery();
  query.select("#messageList").boundingClientRect();
  query.exec((res) => {
    if (res[0]) {
      latestContentHeight.value = res[0].height;
      chatScrollTop.value = res[0].height; // scroll-view 会自动夹紧到最大位置
    }
  });
};
const scrollToTop = () => {
  chatScrollTop.value = 0;
};
// 自动滚动控制：用户向上滚动时暂停自动滚到底部
const shouldAutoScroll = ref(true);
const latestContentHeight = ref(0);
const lastScrollTop = ref(0);
const windowHeight = uni.getSystemInfoSync().windowHeight;
const AUTO_SCROLL_REENABLE_THRESHOLD = 40000; // px，接近底部时恢复自动滚动

const onChatScroll = (e) => {
  const st = e.detail?.scrollTop || 0;
  const delta = st - lastScrollTop.value;
  lastScrollTop.value = st;

  if (delta < 0) {
    shouldAutoScroll.value = false;
    return;
  }

  const distanceToBottom =
    latestContentHeight.value - st - chatContainerHeight.value;
  if (distanceToBottom <= AUTO_SCROLL_REENABLE_THRESHOLD) {
    shouldAutoScroll.value = true;
  }
};

// 回到顶部图标拖拽状态
const backTopX = ref(0);
const backTopY = ref(0);
const backTopDragging = ref(false);
const backTopDragOffset = ref({ x: 0, y: 0 });
const backTopTargetX = ref(0);
const backTopTargetY = ref(0);
let backTopRAF = 0;
const backTopSmoothing = 0.15; // 越大越跟手，越小越顺滑
const backTopEpsilon = 0.5; // 收敛阈值
const raf =
  typeof requestAnimationFrame === "function"
    ? requestAnimationFrame
    : (fn) => setTimeout(fn, 16);
const caf =
  typeof cancelAnimationFrame === "function"
    ? cancelAnimationFrame
    : (id) => clearTimeout(id);

function stepBackTop() {
  const dx = backTopTargetX.value - backTopX.value;
  const dy = backTopTargetY.value - backTopY.value;
  // 插值缓动，避免每帧重排
  backTopX.value += dx * backTopSmoothing;
  backTopY.value += dy * backTopSmoothing;
  if (Math.abs(dx) > backTopEpsilon || Math.abs(dy) > backTopEpsilon) {
    backTopRAF = raf(stepBackTop);
  } else {
    backTopX.value = backTopTargetX.value;
    backTopY.value = backTopTargetY.value;
    backTopRAF = 0;
  }
}
function ensureBackTopRAF() {
  if (!backTopRAF) {
    backTopRAF = raf(stepBackTop);
  }
}

const clamp = (val, min, max) => Math.max(min, Math.min(val, max));

const onBackTopTouchStart = (e) => {
  const t = e.touches && e.touches[0];
  if (!t) return;
  backTopDragging.value = false;
  backTopDragOffset.value = {
    x: t.pageX - backTopX.value,
    y: t.pageY - backTopY.value,
  };
};

const onBackTopTouchMove = (e) => {
  const t = e.touches && e.touches[0];
  if (!t) return;
  const sys = uni.getSystemInfoSync();
  const iconSize = uni.upx2px(100);
  const reserveBottom = uni.upx2px(260);
  const nx = t.pageX - backTopDragOffset.value.x;
  const ny = t.pageY - backTopDragOffset.value.y;
  const clampedX = clamp(nx, 0, sys.windowWidth - iconSize);
  const clampedY = clamp(ny, 0, sys.windowHeight - reserveBottom - iconSize);
  if (
    Math.abs(clampedX - backTopX.value) + Math.abs(clampedY - backTopY.value) >
    3
  ) {
    backTopDragging.value = true;
  }
  backTopTargetX.value = clampedX;
  backTopTargetY.value = clampedY;
  ensureBackTopRAF();
};

const onBackTopTouchEnd = () => {
  // 结束拖拽即可
};

const onBackTopClick = () => {
  if (backTopDragging.value) return; // 拖拽时不触发点击回到顶部
  scrollToTop();
};

// 历史记录详情
async function itemClick(item) {
  const res = await postHistoryDetail({
    recordId: item.id,
    parentId: item.parentId,
    model: 5,
  });

  if (res.code == 200) {
    const message = res.data.wokeFlowData.One.markdown;
    messages.value = [];
    const botMsg = {
      content: message,
      isUser: false,
      isTyping: false,
      isThinking: false,
    };

    onDrawerBackClick();
    messages.value.push(botMsg);
  }
}
</script>

<style scoped>
.deepMate-page {
  display: flex;
  flex-direction: column;
  position: fixed;
  /* 充满视口，彻底禁用页面滚动 */
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  height: 100vh;
  overflow: hidden;
  /* 锁定页面滚动 */
  background-color: #ffffff;
  padding: 20rpx 0rpx;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 30rpx;
  background-color: #ffffff;
  box-shadow: 0 2rpx rgba(0, 0, 0, 0.1);
}

.header-left,
.header-right {
  display: flex;
  align-items: center;
}

.header-left .icon,
.header-right .icon {
  width: 40rpx;
  height: 40rpx;
  /* margin-right: 20rpx; */
}

.header-center .title {
  position: fixed;
  top: 10rpx;
  left: 50%;
  transform: translateX(-50%);
  font-size: 36rpx;
  font-weight: bold;
  color: #333333;
}

.new-chat-button {
  background-color: #ff6600;
  border: none;
  border-radius: 8rpx;
  padding: 10rpx 20rpx;
}

.new-chat-text {
  color: white;
  font-size: 24rpx;
}

.main-content {
  background-color: #fff;
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  /* 内部滚动交给聊天容器 */
  padding: 20rpx;
  margin-top: 1rpx;
  margin-bottom: 280rpx;
}

/* 聊天顶部粘性欢迎块样式 */
.chat-header {
  position: sticky;
  top: 0;
  /* 在页面滚动时始终贴顶 */
  z-index: 50;
  background-color: #ffffff;
  padding: 3rpx 20rpx;
}

.robot-container {
  display: flex;
  align-items: center;
  margin-top: 30rpx;
}

.robot-avatar {
  width: 130rpx;
  height: 130rpx;
  border-radius: 50%;
  margin-left: 20rpx;
}

.welcome-message {
  flex: 1;
}

.greeting {
  font-size: 32rpx;
  margin-left: 50rpx;
  top: 40rpx;
  font-weight: bold;
  color: #333333;
  line-height: 48rpx;
}

.description {
  display: block;
  font-size: 24rpx;
  color: #666666;
  line-height: 36rpx;
  margin-top: 10rpx;
  margin-left: 45rpx;
}

.function-tabs {
  display: block;
  overflow: hidden;
  margin-bottom: 30rpx;
}

.tabs-track {
  display: inline-flex;
  white-space: nowrap;
  will-change: transform;
}

.tab-item {
  padding: 5rpx 20rpx;
  border-radius: 20rpx;
  font-size: 20rpx;
  font-weight: 700;
  color: #666666;
  background-color: #fffefe;
  margin-right: 20rpx;
  transition: all 0.3s;
}

.tab-item.active {
  color: #ff6600;
  background-color: #fff;
  border: 1rpx solid #ff6600;
}

.recommend-card {
  background: url("https://d31zlh4on95l9h.cloudfront.net/images/4da1d629a55c307c3605ca15bf15189a.svg");
  background-repeat: no-repeat;
  background-position: center bottom;
  background-size: contain;
  /* min-height: 20rpx; */
  /* border-radius: 20rpx; */
  padding: 40rpx;
  margin-top: 20rpx;
  margin-bottom: 10rpx;
  /* box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05); */
}

.welcome-section {
  /* 灰色卡片（recommend-card）之后展示背景图 */
  margin-top: 10rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background: url("https://d31zlh4on95l9h.cloudfront.net/images/eca84d9fb54712cb3bc6c6174773b83b.svg");
  background-repeat: no-repeat;
  background-position: center top;
  /* 放在容器顶部，正好在灰色卡片下方 */
  background-size: 80% auto;
  /* 缩放以适配宽度 */
  height: 460rpx;
  /* 提供可视高度，让背景图可见 */
}

.card-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-left: 40rpx;
}

.logo {
  width: 80rpx;
  height: 80rpx;
  background-color: #ff0000;
  border-radius: 10rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20rpx;
}

.card-text {
  flex: 1;
  margin-left: 20rpx;
}

.main-question {
  font-size: 32rpx;
  color: #333333;
  line-height: 48rpx;
}

.stock-code {
  display: block;
  font-size: 24rpx;
  color: #ff3b30;
  background-color: #ffffff;
  padding: 2rpx 15rpx;
  border-radius: 12rpx;
  margin-top: 8rpx;
  width: fit-content;
  border: 1rpx solid #ff3b30;
}

.arrow-icon {
  background: url("https://d31zlh4on95l9h.cloudfront.net/images/40d94054644f6e3f1c366751f07f0010.svg");
  background-repeat: no-repeat;
  left: 0.5rem;
  top: 1.8rem;
  background-size: 100% 100%;
  width: 60rpx;
  height: 60rpx;
}

.interest-section {
  margin-bottom: 30rpx;
}

.section-title {
  display: block;
  text-align: left;
  font-size: 26rpx;
  color: #666666;
  margin-bottom: 20rpx;
}

.topics-list {
  display: flex;
  flex-direction: column;
  gap: 15rpx;
}

.topic-item {
  display: flex;
  align-items: center;
  padding: 15rpx 20rpx;
  background-color: #f0f0f0;
  border-radius: 15rpx;
  width: fit-content;
}

.tag-icon {
  width: 24rpx;
  height: 24rpx;
  margin-right: 10rpx;
}

.topic-text {
  font-size: 28rpx;
  color: #333333;
  flex: 1;
}

/* 聊天区域样式 */
.chat-container {
  margin-top: 30rpx;
  border-radius: 10rpx;
  height: calc(100vh - 50rpx);
  /* 缩短滚动区域，避免被输入框覆盖 */
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
}

.message-list {
  background-color: #fff;
  margin-bottom: 400rpx;
  /* padding: 20rpx; */
}

.message {
  display: flex;
  align-items: flex-start;
  margin-bottom: 30rpx;
}

.user-message {
  flex-direction: row-reverse;
  justify-content: flex-start;
}

.message-icon {
  font-size: 24rpx;
  margin: 0 10rpx;
  padding: 10rpx;
  border-radius: 50%;
  background-color: #ddd;
  width: 40rpx;
  height: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.user-message .message-icon {
  background-color: #007aff;
  border-radius: 50%;
  color: #fff;
  /* box-shadow: 0 0 12rpx rgba(0, 122, 255, 0.4); */
}

.bot-message .message-icon {
  background: url("/static/images/机器人 (1).svg");

  color: white;
}

.message-content {
  max-width: 70%;
  position: relative;
  word-wrap: break-word;
  word-break: break-all;
  overflow-wrap: break-word;
}

.user-message .message-content {
  /* background-color: #007aff; */
  border: 2rpx solid #f3908f;
  border-radius: 20rpx;
  padding: 10rpx;
}

.bot-message .message-content {
  background-color: #f0f0f0;
  border-radius: 10rpx;
  padding: 15rpx;
}

.message-text {
  font-size: 28rpx;
  line-height: 40rpx;
}

.user-message .message-text {
  color: black;
}

.bot-message .message-text {
  color: #333;
}

.loading-dots {
  display: flex;
  align-items: center;
  /* padding-top: 10rpx; */
}

.dot {
  width: 10rpx;
  height: 10rpx;
  background-color: #666;
  border-radius: 50%;
  margin: 0 4rpx;
  animation: loading 1.4s infinite ease-in-out both;
}

.user-message .dot {
  background-color: white;
}

.dot:nth-child(1) {
  animation-delay: -0.32s;
}

.dot:nth-child(2) {
  animation-delay: -0.16s;
}

@keyframes loading {
  0%,
  80%,
  100% {
    transform: scale(0);
  }

  40% {
    transform: scale(1);
  }
}

.input-area {
  position: fixed;
  margin-top: 20rpx;
  bottom: 70rpx;
  left: 0;
  right: 0;
  padding: 0 40rpx 80rpx 40rpx;
  background-color: #ffffff;
}

.input-wrapper {
  position: relative;
  display: flex;
  align-items: center;
  padding: 15rpx 20rpx;
  background-color: rgb(220, 31, 29);
  border-radius: 100rpx;
  display: flex;
  align-items: center;
  justify-content: center;

  height: 50rpx;
}

.mic-icon {
  width: 36rpx;
  height: 36rpx;
  margin-right: 20rpx;
}

.input-field {
  flex: 1;
  font-size: 28rpx;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-left: 60rpx;
  background: none;
  border: none;
  outline: none;
}

.input-field::placeholder {
  color: #ffffff !important;
  opacity: 1;
}

/* .uni-scroll-view{
  height: 92%;
} */
.send-button {
  background: url("https://d31zlh4on95l9h.cloudfront.net/images/95f1ea2262e9157db13c93c0dc1c5d96.svg");
  background-repeat: no-repeat;
  background-size: 100% 100%;
  height: 50rpx;
  width: 50rpx;
  padding: 0;
  border: 1rpx solid transparent;
  margin-left: 20rpx;
}

.send-icon {
  width: 36rpx;
  height: 36rpx;
}

.disclaimer {
  font-size: 15rpx;
  color: #4d4c4c;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 15rpx;
}

.banner-panel {
  position: relative;
  height: 480rpx;
  /* 拉长容器，灰色背景跟随变高 */
  overflow: hidden;
  /* 让圆角和内部层剪裁一致 */
  border-radius: 15rpx;
}

.panelShow {
  height: 12%;
}

.pray-banner {
  position: absolute;
  /* background-size: 100% 100%; */
  inset: 0;
  /* 顶部、底部、左、右都贴合容器 */
  width: 100%;
  height: 81%;
  border-radius: 15rpx;
  z-index: 1;
  /* 在灰底之上、内容之下 */
}

.contain {
  margin: 0 20rpx;
  gap: 5rpx;
}

.banner-panel .robot-container,
.banner-panel .function-tabs,
.banner-panel .recommend-card {
  position: relative;
  z-index: 2;
}

.back-to-top {
  position: fixed;
  left: 0;
  top: 0;
  width: 100rpx;
  height: 100rpx;
  z-index: 1000;
}

.back-to-top:active {
  transform: scale(0.96);
}

.static-footer {
  position: fixed;
  bottom: 0;
}

/* 搜索历史侧拉框样式 */
.drawer-overlay {
  position: fixed;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.35);
  z-index: 900;
}

.drawer-panel {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  height: 75vh;
  max-height: 80vh;
  width: 100%;
  background: #ffffff;
  box-shadow: 0 -8rpx 20rpx rgba(0, 0, 0, 0.06);
  z-index: 1000;
  display: flex;
  flex-direction: column;
  border-top-left-radius: 20rpx;
  border-top-right-radius: 20rpx;
  transition: transform 0.22s ease;
}

.drawer-back {
  position: absolute;
  left: 50%;
  top: -14px;
  transform: translateX(-50%);
  width: 28px;
  height: 48px;
  border-radius: 12px;
  background: #fff;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.08);
  display: flex;
  align-items: center;
  justify-content: center;
}

.drawer-back-icon {
  font-size: 16px;
  color: #8a8a8a;
}

.drawer-actions {
  display: flex;
  align-items: center;
  gap: 40rpx;
}

.delete-all-container {
  display: flex;
  align-items: center;
  gap: 14rpx;
}

.delete-icon {
  width: 45rpx;
  height: 40rpx;
}

.delete-all {
  font-size: 28rpx;
}

.drawer-close {
  background: url("/static/icons/关闭2.svg");
  width: 48rpx;
  height: 48rpx;
  border-radius: 24rpx;
  /* background: #f5f5f5; */
  /* box-shadow: 0 2px 8px rgba(0,0,0,0.08); */
  display: flex;
  align-items: center;
  justify-content: center;
}

.drawer-close-icon {
  font-size: 24rpx;
  color: #8a8a8a;
}

.drawer-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 52rpx 28rpx 0rpx 28rpx;
  /* border-bottom: 2rpx solid #f0f0f0; */
}

.drawer-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333333;
}

/* .drawer-close {
  font-size: 42rpx;
  color: #999999;
} */

.drawer-content {
  flex: 1;
  min-height: 0;
  /* 让 flex 子元素可在容器内收缩以启用滚动 */
  height: 100%;
  overscroll-behavior-y: contain;
  /* 防止滚动串联到页面 */
  -webkit-overflow-scrolling: touch;
  /* iOS 惯性滚动 */
  touch-action: pan-y;
  /* 优化触控滚动，仅垂直 */
}

.drawer-inner {
  padding: 20rpx 24rpx 20rpx 24rpx;
}

.history-section {
  margin-bottom: 20rpx;
  /* margin: 0 24rpx; */
}

.section-title {
  font-size: 26rpx;
  color: #888;
  margin: 10rpx 6rpx 16rpx;
}

.history-item {
  display: flex;
  align-items: center;
  padding: 19rpx 18rpx;
  background-color: #f6f7f9;
  border-radius: 12rpx;
  margin-bottom: 12rpx;
}

.history-left {
  margin-right: 12rpx;
}

.flag-circle {
  width: 36rpx;
  height: 36rpx;
  border-radius: 50%;
  background: #fff;
  border: 2rpx solid #eee;
  display: flex;
  align-items: center;
  justify-content: center;
}

.flag-emoji {
  font-size: 24rpx;
}

.history-main {
  flex: 1;
}

.history-query {
  font-size: 28rpx;
  color: #333;
}

.history-time {
  font-size: 22rpx;
  color: #999;
}

.history-card {
  background-color: #fff;
  border: 2rpx solid #f2f2f2;
  border-left: 8rpx solid rgb(220, 31, 29);
  border-radius: 12rpx;
  padding: 18rpx 20rpx;
  margin-bottom: 16rpx;
  box-shadow: 0 4rpx 10rpx rgba(0, 0, 0, 0.03);
}

.history-query {
  font-size: 28rpx;
  color: #333333;
  font-weight: 500;
}

.history-time {
  margin-top: 8rpx;
  font-size: 22rpx;
  color: #888888;
}

.empty-history {
  padding: 40rpx;
  color: #999999;
  text-align: center;
}

.thinking-process {
  margin: 10rpx 0;
  border: 2rpx solid #e5e5e5;
  border-radius: 20rpx;
  background-color: #f9f9f9;
}

.thinking-header {
  display: flex;
  align-items: center;
  padding: 20rpx 30rpx;
  cursor: pointer;
  background-color: #fff;
  border-radius: 20rpx;
  border-bottom: 2rpx solid #e5e5e5;
}

.thinking-icon {
  font-size: 32rpx;
  margin-right: 16rpx;
  color: #d47c45;
}

.thinking-title {
  font-size: 28rpx;
  font-weight: 500;
  color: #d47c45;
  margin-right: 16rpx;
}

.thinking-count {
  font-size: 24rpx;
  color: #666;
  margin-right: 16rpx;
}

.thinking-toggle {
  font-size: 24rpx;
  color: #999;
}

.thinking-content {
  padding: 20rpx 30rpx;
}

.thinking-item {
  display: flex;
  align-items: center;
  margin-bottom: 16rpx;
  padding: 8rpx 0;
}

.item-status {
  width: 32rpx;
  height: 32rpx;
  border-radius: 50%;
  background-color: #f0f0f0;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-right: 16rpx;
}

.checkmark {
  font-size: 20rpx;
  color: #ff0000;
}

.item-text {
  font-size: 24rpx;
  color: #333;
}
</style>