<script setup>
// 导入
import { ref, computed, onMounted, watch, nextTick, onUnmounted, h } from "vue";
import { setHeight } from "../utils/setHeight";
import {
  getUserCountAPI,
  showExchangeAPI,
  godExchangeAPI,
  exchangeAPI,
  getGoldCoinAPI,
} from "../api/AIxiaocaishen";
import { ElMessage } from "element-plus";
import AIchat from "./AIchat.vue";
import AIfind from "./AIfind.vue";
import AiEmotion from "./AiEmotion.vue";
import deepNine from "./deepNine.vue";
import Feedback from "./Feedback.vue";
import Announcement from "./Announcement.vue";

import { useAppBridge } from "../assets/js/useAppBridge.js";
import { useDataStore } from "@/store/dataList.js";
import { useChatStore } from "../store/chat";
import { useEmotionAudioStore } from "../store/emotionAudio";
import { useAudioStore } from "../store/audio";
import { useDeepNineStore } from "../store/deepNine";
import _ from "lodash";

import logo from "../assets/img/homePage/logo.png";
import madeInHL from "../assets/img/homePage/madeInHL.png";
import getCountAll from "../assets/img/homePage/get-count-all.png";
import announcementBtn from "../assets/img/homePage/announcement.png";
import thinkActive from "../assets/img/homePage/tail/think-active.png";
import thinkNoActive from "../assets/img/homePage/tail/think-no-active.png";
import languageBtn from "../assets/img/homePage/tail/language.png";
import dbqbButton01 from "../assets/img/AiEmotion/dbqb-button01.png";
import dbqbButton02 from "../assets/img/AiEmotion/dbqb-button02.png";
import emotionButton01 from "../assets/img/AiEmotion/emotion-button01.png";
import emotionButton02 from "../assets/img/AiEmotion/emotion-button02.png";
import voice from "../assets/img/homePage/tail/voice.png";
import voiceNoActive from "../assets/img/homePage/tail/voice-no-active.png";
import sendBtn from "../assets/img/homePage/tail/send.png";
import msgBtn from "../assets/img/homePage/tail/msg.png";
import feedbackBtn from "../assets/img/Feedback/feedbackBtn.png";
import back from "../assets/img/Feedback/back.png";

import HistoryRecord from "./components/HistoryRecord.vue";

// import VConsole from "vconsole";

// const vConsole = new VConsole();

const isMobile = ref(null);

// 获取 AiEmotion 组件的 ref
const aiEmotionRef = ref(null);
// 获取深度九大模型组件的 ref
const deepNineRef = ref(null);
// 获取历史记录组件的 ref
const historyRecordRef = ref(null);
// import { useUserStore } from "../store/userPessionCode.js";
const { getQueryVariable, setActiveTabIndex, getUserInfo } = useDataStore();
const dataStore = useDataStore();
const chatStore = useChatStore();
const deepNineStore = useDeepNineStore();
// 变量
// 音频管理
const emotionAudioStore = useEmotionAudioStore();
const audioStore = useAudioStore();
// 根据当前页面类型获取对应的音频store
const getCurrentAudioStore = () => {
  return activeTab.value === "AiEmotion" ? emotionAudioStore : audioStore;
};

const isVoice = computed(() => {
  const currentStore = getCurrentAudioStore();
  return currentStore.isVoiceEnabled;
});

const toggleVoice = () => {
  const currentStore = getCurrentAudioStore();

  if (!currentStore.isVoiceEnabled) {
    // 如果语音功能关闭，先开启语音功能
    currentStore.toggleVoice();
  } else {
    // 如果语音功能开启，则切换播放/暂停状态
    if (currentStore.currentAudioUrl || currentStore.ttsUrl) {
      // 有音频时切换播放/暂停
      currentStore.togglePlayPause();
    } else {
      // 没有音频时关闭语音功能
      currentStore.toggleVoice();
    }
  }
};
// 将默认值改为从 sessionStorage 中获取，如果没有则使用默认值 'aifindCow'为第一个默认tab
const activeTab = ref(sessionStorage.getItem("activeTabAI") || "AIchat");
const activeIndex = ref(
  parseInt(sessionStorage.getItem("activeIndexAI") || "0")
);

// 手机端选择器的值，与activeTab保持同步
const activeTabMobile = ref(activeTab.value);
// 下拉菜单开关状态
const isDropdownOpen = ref(false);

// 模型选项数据
const modelOptions = [
  {
    label: "夺宝奇兵大模型",
    value: "AIchat",
    image:
      "https://d31zlh4on95l9h.cloudfront.net/images/0389f08c458c20b715be7acebf7a8eb2.png",
  },
  {
    label: "AI情绪大模型",
    value: "AiEmotion",
    image:
      "https://d31zlh4on95l9h.cloudfront.net/images/aed3597ea187c5af6c88d5a5c67fc9c1.png",
  },
  {
    label: "深度九大模型",
    value: "deepNine",
    image:
      "https://d31zlh4on95l9h.cloudfront.net/images/35bf808538183be0062e4647570a9abd.png",
  },
];

// 监听activeTab变化，同步到activeTabMobile
watch(activeTab, (newVal) => {
  activeTabMobile.value = newVal;
});

// 切换下拉菜单显示状态
const toggleDropdown = () => {
  isDropdownOpen.value = !isDropdownOpen.value;
};

// 选择选项
const selectOption = (value) => {
  activeTabMobile.value = value;
  isDropdownOpen.value = false;

  const tabIndexMap = {
    AIchat: 0,
    AiEmotion: 1,
    deepNine: 2,
  };
  setActiveTab(value, tabIndexMap[value]);
};

// 获取当前选中选项的标签
const getSelectedOptionLabel = () => {
  const option = modelOptions.find(
    (opt) => opt.value === activeTabMobile.value
  );
  return option ? option.label : "请选择模型";
};

// 获取当前选中选项的图片
const getSelectedOptionImage = () => {
  const option = modelOptions.find(
    (opt) => opt.value === activeTabMobile.value
  );
  return option ? option.image : "";
};

// 点击外部关闭下拉菜单
onMounted(() => {
  document.addEventListener("click", (e) => {
    const container = document.querySelector(".custom-select-container");
    if (container && !container.contains(e.target) && isDropdownOpen.value) {
      isDropdownOpen.value = false;
    }
  });
});

// 手机端选择器变化处理（保留原函数以兼容其他地方可能的调用）
const handleMobileTabChange = (value) => {
  const tabIndexMap = {
    AIchat: 0,
    AiEmotion: 1,
    deepNine: 2,
  };
  setActiveTab(value, tabIndexMap[value]);
};

const tabs = computed(() => [
  {
    name: "AIchat",
    label: "夺宝奇兵大模型",
  },
  // {
  //   name: "AIfind",
  //   label: "发现",
  // },
  {
    name: "AiEmotion",
    label: "AI情绪大模型",
  },
  {
    name: "deepNine",
    label: "深度九大模型",
  },
]);

// 修改 setActiveTab 方法，添加一个可选参数 forceAIchat
const setActiveTab = (tab, index, forceAIchat = false) => {
  isScrolling.value = false; //回复滚动到底部方法
  isAnnouncementVisible.value = false;
  // 重置输入框禁用状态，防止页面切换时状态残留

  console.log("tab", tab, "index", index);
  if (tab == "AIchat") {
    isInputDisabled.value = chatStore.chatInput;
    console.log("切换到AIchat页面，输入框状态为", isInputDisabled.value);
  } else if (tab == "AiEmotion") {
    isInputDisabled.value = chatStore.emotionInput;
    console.log("切换到AiEmotion页面，输入框状态为", isInputDisabled.value);
  } else if (tab == "deepNine") {
    isInputDisabled.value = chatStore.deepNineInput;
    console.log("切换到deepNine页面，输入框状态为", isInputDisabled.value);
  } else {
    isInputDisabled.value = false;
  }

  if (forceAIchat && activeTab.value !== "AIchat") {
    activeTab.value = "AIchat";
    activeIndex.value = 0;
    sessionStorage.setItem("activeTabAI", "AIchat");
    sessionStorage.setItem("activeIndexAI", "0");
  } else {
    activeTab.value = tab;
    activeIndex.value = index;
    sessionStorage.setItem("activeTabAI", tab);
    sessionStorage.setItem("activeIndexAI", index.toString());
  }
  setActiveTabIndex(index);
  console.log(tab, index, "tab, index");
  setHeight(document.getElementById("testId")); // 给父组件发送窗口高度

  // 在页面切换时获取最新的次数
  chatStore.getUserCount();
};

// 修改 activeComponent 的计算逻辑
const activeComponent = computed(() => {
  if (activeTab.value === "AIchat") {
    return AIchat;
  } else if (activeTab.value === "AIfind") {
    return AIfind;
  } else if (activeTab.value === "AiEmotion") {
    return AiEmotion; // 新增逻辑
  } else if (activeTab.value === "deepNine") {
    return deepNine;
  }
});

const activeTwoTab = computed(() => {
  if (isAnnouncementVisible.value) {
    return Announcement;
  } else {
    return Feedback;
  }
});

// 新增一个方法，调用时先判断是否处于 AIchat，若不在则跳转到 AIchat
const ensureAIchat = () => {
  setActiveTab("AIchat", 0, true);
};

// 获取次数
const UserCount = computed(() => chatStore.UserCount);

const getCount = () => {
  console.log("点击了获取次数的按钮");
};

// 深度思考
const isThinking = ref(true);
const toggleThink = () => {
  isThinking.value = !isThinking.value;
};

// 发送消息
const message = ref("");
// 传输对象
const messages = ref([]);
// 信息加载状态
const isLoading = computed(() => {
  chatStore.isLoading;
});
// 输入框禁用状态
const isInputDisabled = ref(false);

// 添加用户消息
const updateMessage = (title) => {
  message.value = title;
  console.log("updateMessage 的值:", title);
};

watch(
  () => chatStore.announcementMsg,
  (newVal) => {
    console.log("监听到公告改变", chatStore.announcementMsg);
    if (chatStore.announcementMsg && !isInputDisabled.value) {
      message.value = chatStore.announcementMsg;
      chatStore.announcementMsg = null;
    }
  }
);

watch(
  () => dataStore.isFeedback,
  async (newVal) => {
    if (!dataStore.isFeedback) {
      // 重置公告页面显示状态
      isAnnouncementVisible.value = false;
      await nextTick();
      // 监听页面高度
      throttledHeightListener();
    }
  }
);

watch(
  () => chatStore.chatInput,
  async (newVal) => {
    if (activeTab.value == "AIchat") {
      isInputDisabled.value = chatStore.chatInput;
    }
  }
);

watch(
  () => chatStore.emotionInput,
  async (newVal) => {
    if (activeTab.value == "AiEmotion") {
      isInputDisabled.value = chatStore.emotionInput;
    }
  }
);

watch(
  () => chatStore.deepNineInput,
  async (newVal) => {
    console.log("deepNineInput", chatStore.deepNineInput);
    if (activeTab.value == "deepNine") {
      isInputDisabled.value = chatStore.deepNineInput;
    }
  }
);

const sendMessage = async () => {
  if (
    localStorage.getItem("localToken") == null ||
    localStorage.getItem("localToken") == ""
  ) {
    ElMessage.error("请先登录");
    return;
  }

  // 检查输入内容是否为空
  if (!message.value || !message.value.trim()) {
    ElMessage.warning("输入内容不能为空");
    return;
  }
  isScrolling.value = false;

  // 注意：历史记录会在消息发送后自动更新，无需手动添加

  // 取消历史记录选中状态
  if (historyRecordRef) {
    historyRecordRef.value.selectedRecordId = null;
  }
  // 判断当前是否为 AiEmotion 组件
  if (activeTab.value === "AiEmotion") {
    // 禁用输入框
    isInputDisabled.value = true;
    chatStore.emotionInput = true;

    // 调用 AiEmotion 组件的 handleSendMessage 方法
    aiEmotionRef.value?.handleSendMessage(message.value, () => {
      // 打字机效果完成后的回调，重新启用输入框
      isInputDisabled.value = false;
      chatStore.emotionInput = false;
    });
    message.value = ""; // 清空输入框
    return;
  }

  // 判断当前是否为深度九大模型
  if (activeTab.value === "deepNine") {
    // 禁用输入框
    isInputDisabled.value = true;
    chatStore.deepNineInput = true;
    // 获取深度九大模型的 store
    const deepNineStore = useDeepNineStore();

    // 添加消息到深度九大模型的 store 中
    const messageContent = message.value;
    message.value = ""; // 清空输入框

    setTimeout(() => {
      console.log("深度九大模型：添加消息", messageContent);
      messages.value = [
        ...messages.value,
        {
          sender: "user",
          content: messageContent,
          audioArray: [],
          audioStatus: false,
        },
      ];
    }, 200);

    return;
  }

  // 调用 ensureAIchat 确保跳转到 AIchat 页面
  ensureAIchat();

  if (isInputDisabled.value) return;
  isInputDisabled.value = true;
  chatStore.chatInput = true;

  const messageContent = message.value;
  // 重置消息输入框
  message.value = "";

  setTimeout(() => {
    console.log("延时后添加消息", messageContent);
    // 发送消息时，设置 isLoading 为 true
    messages.value = [
      ...messages.value,
      {
        sender: "user",
        content: messageContent,
        audioArray: [],
        audioStatus: false,
      },
    ];
    console.log(messages.value, "messages.value");
  }, 200);
};

// 重新启用输入框的方法
const enableInput = () => {
  console.log("解除禁用");
  isInputDisabled.value = false;
};

// 处理历史记录选择
const handleHistorySelect = (stockData) => {
  console.log("接收到历史记录数据:", stockData);

  // 只在情绪大模型中处理历史记录选择
  if (activeTab.value === 'AiEmotion') {
    // 等待组件渲染完成后调用addStock方法
    nextTick(() => {
      if (aiEmotionRef.value && aiEmotionRef.value.addStock) {
        aiEmotionRef.value.addStock(stockData);
      } else {
        console.error("AiEmotion组件或addStock方法不可用");
      }
    });
  } else {
    console.log("历史记录选择仅在情绪大模型中有效");
  }
};

// 公告

// 新增一个变量来控制是否显示公告页面
const isAnnouncementVisible = ref(false);

// Token规则提示框相关
const tokenRuleDialogVisible = ref(false);
const hasShownTokenRule = ref({
  AIchat: sessionStorage.getItem("hasShownTokenRule_AIchat") === "true",
  AiEmotion: sessionStorage.getItem("hasShownTokenRule_AiEmotion") === "true",
  deepNine: sessionStorage.getItem("hasShownTokenRule_deepNine") === "true",
});

// 关闭Token规则提示框
const closeTokenRuleDialog = () => {
  tokenRuleDialogVisible.value = false;
};
// 打开Token规则提示框
const openTokenRuleDialog = () => {
  tokenRuleDialogVisible.value = true;
};

// 添加全局点击事件监听器，使任何点击动作都能关闭提示框
// 定义处理函数，以便正确移除事件监听器
const handleGlobalClick = (event) => {
  // 检查点击事件是否来自"兑换规则"按钮
  const changeRuleElement = document.querySelector(".changeRule");
  if (
    changeRuleElement &&
    (changeRuleElement === event.target ||
      changeRuleElement.contains(event.target))
  ) {
    // 如果点击的是"兑换规则"按钮，不关闭提示框
    return;
  }

  if (tokenRuleDialogVisible.value) {
    tokenRuleDialogVisible.value = false;
  }
};

onMounted(() => {
  document.addEventListener("click", handleGlobalClick);
});

// 在组件卸载时移除事件监听器
onUnmounted(() => {
  document.removeEventListener("click", handleGlobalClick);
});

// 检查是否需要显示Token规则提示框（从其他页面跳转过来时）
const checkTokenRuleOnPageLoad = () => {
  const activeTab = sessionStorage.getItem("activeTabAI");
  const fromExternalPage = sessionStorage.getItem("fromExternalPage");

  if (
    fromExternalPage === "true" &&
    activeTab &&
    !hasShownTokenRule.value[activeTab]
  ) {
    tokenRuleDialogVisible.value = true;
    hasShownTokenRule.value[activeTab] = true;
    sessionStorage.setItem(`hasShownTokenRule_${activeTab}`, "true");
    // 清除标记，避免重复显示
    sessionStorage.removeItem("fromExternalPage");
  }
};

const showAnnouncement = async () => {
  console.log("打开公告");
  dataStore.isFeedback = true; // 显示用户反馈页面
  isScrolling.value = false; //回复滚动到底部方法
  isAnnouncementVisible.value = true; // 显示公告页面
  if (isMobile.value) {
    if (historyRecordRef) {
      historyRecordRef.value.isCollapsed = true;
    }
  }
};

// 跳转用户反馈
const showFeedback = () => {
  console.log("打开用户反馈");
  dataStore.isFeedback = true; // 显示用户反馈页面
  isAnnouncementVisible.value = false; // 显示反馈页面
  if (isMobile.value) {
    if (historyRecordRef) {
      historyRecordRef.value.isCollapsed = true;
    }
  }
};

// 保证发送消息时，滚动屏在底部

const tabContentAIchat = ref(null);
const tabContentAiEmotion = ref(null);
const tabContentDeepNine = ref(null);

const isScrolling = ref(false); //判断用户是否在滚动

// AiEmotion页面高度监听器相关变量
const aiEmotionHeightObserver = ref(null);
const isAiEmotionAutoScrollEnabled = ref(false);
const isAiEmotionUserScrolling = ref(false); // 用户是否正在手动滚动
const aiEmotionScrollTimer = ref(null); // 滚动检测定时器
const isChartInteracting = ref(false); // 图表是否正在交互
const chartInteractionTimer = ref(null); // 图表交互检测定时器

// 获取当前活动页面的滚动容器
const getCurrentScrollContainer = () => {
  if (activeTab.value === "AIchat") {
    return tabContentAIchat.value;
  } else if (activeTab.value === "AiEmotion") {
    return tabContentAiEmotion.value;
  } else if (activeTab.value === "deepNine") {
    return tabContentDeepNine.value;
  }
  return null;
};

const smoothScrollToBottom = async () => {
  const container = getCurrentScrollContainer();
  if (!container) return;

  await nextTick(); // 确保在DOM更新后执行

  if (!isScrolling.value) {
    container.scrollTop = container.scrollHeight - container.offsetHeight;
  }
};

const throttledSmoothScrollToBottom = _.throttle(smoothScrollToBottom, 300, {
  trailing: false,
});

// AiEmotion页面自动滚动到底部的防抖函数
const debouncedAiEmotionScrollToBottom = _.debounce(() => {
  if (
    activeTab.value === "AiEmotion" &&
    isAiEmotionAutoScrollEnabled.value &&
    !isAiEmotionUserScrolling.value &&
    !isChartInteracting.value
  ) {
    const container = tabContentAiEmotion.value;
    if (container) {
      container.scrollTop = container.scrollHeight - container.offsetHeight;
    }
  }
}, 150);

// 启动AiEmotion页面高度监听器
const startAiEmotionHeightObserver = () => {
  // 先停止之前的监听器
  stopAiEmotionHeightObserver();

  isAiEmotionAutoScrollEnabled.value = true;

  // 创建ResizeObserver监听页面内容变化
  aiEmotionHeightObserver.value = new ResizeObserver((entries) => {
    if (
      isAiEmotionAutoScrollEnabled.value &&
      activeTab.value === "AiEmotion" &&
      !isChartInteracting.value
    ) {
      debouncedAiEmotionScrollToBottom();
    }
  });

  // 监听document.body的尺寸变化
  if (document.body) {
    aiEmotionHeightObserver.value.observe(document.body);
  }

  // 创建MutationObserver监听DOM结构变化
  const mutationObserver = new MutationObserver((mutations) => {
    let shouldScroll = false;
    mutations.forEach((mutation) => {
      if (mutation.type === "childList" && mutation.addedNodes.length > 0) {
        // 检查新增的节点是否包含实际内容
        const hasContent = Array.from(mutation.addedNodes).some((node) => {
          if (node.nodeType === Node.ELEMENT_NODE) {
            return node.offsetHeight > 0 || node.scrollHeight > 0;
          }
          return (
            node.nodeType === Node.TEXT_NODE &&
            node.textContent.trim().length > 0
          );
        });
        if (hasContent) {
          shouldScroll = true;
        }
      }
    });

    if (
      shouldScroll &&
      isAiEmotionAutoScrollEnabled.value &&
      activeTab.value === "AiEmotion" &&
      !isChartInteracting.value
    ) {
      debouncedAiEmotionScrollToBottom();
    }
  });

  // 监听AiEmotion页面的主要内容区域的DOM变化
  const aiEmotionContainer = tabContentAiEmotion.value;
  if (aiEmotionContainer) {
    mutationObserver.observe(aiEmotionContainer, {
      childList: true,
      subtree: true,
      attributes: false,
      characterData: true,
    });
  }

  // 保存mutationObserver引用以便清理
  aiEmotionHeightObserver.value.mutationObserver = mutationObserver;

  // 为AiEmotion页面的滚动容器添加滚动事件监听器
  if (aiEmotionContainer) {
    aiEmotionContainer.addEventListener("scroll", handleAiEmotionUserScroll, {
      passive: true,
    });
    // 保存滚动事件监听器引用以便清理
    aiEmotionHeightObserver.value.scrollListener = handleAiEmotionUserScroll;
  }

  console.log("AiEmotion页面高度监听器已启动");
};

// AiEmotion页面用户滚动检测
const handleAiEmotionUserScroll = () => {
  // 标记用户正在滚动
  isAiEmotionUserScrolling.value = true;

  // 清除之前的定时器
  if (aiEmotionScrollTimer.value) {
    clearTimeout(aiEmotionScrollTimer.value);
  }

  // 设置定时器，2秒后恢复自动滚动
  // aiEmotionScrollTimer.value = setTimeout(() => {
  //   isAiEmotionUserScrolling.value = false;
  //   console.log("AiEmotion页面用户滚动检测：恢复自动滚动");
  // }, 2000);
};

// 图表交互状态管理
const handleChartInteractionStart = () => {
  console.log("图表交互开始，临时禁用自动滚动");
  isChartInteracting.value = true;

  // 清除之前的定时器
  if (chartInteractionTimer.value) {
    clearTimeout(chartInteractionTimer.value);
  }
};

const handleChartInteractionEnd = () => {
  // 清除之前的定时器
  if (chartInteractionTimer.value) {
    clearTimeout(chartInteractionTimer.value);
  }

  // 设置定时器，1秒后恢复自动滚动
  chartInteractionTimer.value = setTimeout(() => {
    isChartInteracting.value = false;
    console.log("图表交互结束，恢复自动滚动");
  }, 1000);
};

// 暴露图表交互管理函数给全局使用
window.handleChartInteractionStart = handleChartInteractionStart;
window.handleChartInteractionEnd = handleChartInteractionEnd;

// 处理AiEmotion页面的滚动请求
const handleAiEmotionScrollToBottom = () => {
  if (activeTab.value === "AiEmotion") {
    const container = tabContentAiEmotion.value;
    if (container) {
      // 使用nextTick确保DOM已更新
      nextTick(() => {
        container.scrollTop = container.scrollHeight - container.offsetHeight;
        console.log("AiEmotion页面：执行容器滚动到底部");
      });
    }
  }
};

// 停止AiEmotion页面高度监听器
const stopAiEmotionHeightObserver = () => {
  isAiEmotionAutoScrollEnabled.value = false;
  isAiEmotionUserScrolling.value = false;

  // 清理滚动检测定时器
  if (aiEmotionScrollTimer.value) {
    clearTimeout(aiEmotionScrollTimer.value);
    aiEmotionScrollTimer.value = null;
  }

  if (aiEmotionHeightObserver.value) {
    // 清理ResizeObserver
    aiEmotionHeightObserver.value.disconnect();

    // 清理MutationObserver
    if (aiEmotionHeightObserver.value.mutationObserver) {
      aiEmotionHeightObserver.value.mutationObserver.disconnect();
      aiEmotionHeightObserver.value.mutationObserver = null;
    }

    // 清理滚动事件监听器
    if (
      aiEmotionHeightObserver.value.scrollListener &&
      tabContentAiEmotion.value
    ) {
      tabContentAiEmotion.value.removeEventListener(
        "scroll",
        aiEmotionHeightObserver.value.scrollListener
      );
      aiEmotionHeightObserver.value.scrollListener = null;
    }

    aiEmotionHeightObserver.value = null;
  }

  console.log("AiEmotion页面高度监听器已停止");
};

watch(
  () => chatStore.messages.length,
  () => {
    // console.log('messages变化了')
    // 只有在AIchat页面时才执行自动滚动
    if (activeTab.value === "AIchat" || activeTab.value === "deepNine") {
      throttledSmoothScrollToBottom();
    }
  },
  { deep: false, immediate: true }
);

watch(
  () => deepNineStore.messages.length,
  () => {
    // console.log('messages变化了')
    // 只有在AIchat页面时才执行自动滚动
    if (activeTab.value === "AIchat" || activeTab.value === "deepNine") {
      throttledSmoothScrollToBottom();
    }
  },
  { deep: false, immediate: true }
);
// 监听-当点击夺宝奇兵大模型的历史记录时，滚动到顶部
watch(
  () => chatStore.dbqbClickRecord,
  async (newValue, oldValue) => {
    const container = getCurrentScrollContainer();
    if (!container) return;

    await nextTick(); // 确保在DOM更新后执行
    container.scrollTop = 0;
  }
);
// 监听-当点击深度九大模型的历史记录时，滚动到顶部
watch(
  () => deepNineStore.dbqbClickRecord,
  async (newValue, oldValue) => {
    const container = getCurrentScrollContainer();
    if (!container) return;

    await nextTick(); // 确保在DOM更新后执行
    container.scrollTop = 0;
  }
);

watch(
  () => chatStore.dbqbScrollToTop,
  async (newValue, oldValue) => {
    const container = getCurrentScrollContainer();
    if (!container) return;

    await nextTick(); // 确保在DOM更新后执行
    container.scrollTop = 0;
  }
);

watch(
  activeTab,
  async () => {
    console.log("activeTab变化了", activeTab.value);
    if (
      activeTab.value == "AIchat" ||
      activeTab.value == "AiEmotion" ||
      activeTab.value == "deepNine"
    ) {
      if (historyRecordRef.value && historyRecordRef.value.getHistoryList) {
        let model =
          activeTab.value == "AIchat"
            ? 1
            : activeTab.value == "AiEmotion"
            ? 2
            : 3;
        const result = historyRecordRef.value.getHistoryList({
          model: model,
          token: localStorage.getItem("localToken"),
        });
      }
    }

    if (activeTab.value === "AIchat" || activeTab.value === "deepNine") {
      isScrolling.value = false; //回复滚动到底部方法
      // 停止AiEmotion页面的高度监听器
      stopAiEmotionHeightObserver();
      setTimeout(() => {
        // throttledSmoothScrollToBottom();
      }, 100);
    } else if (activeTab.value === "AiEmotion") {
      // 启动AiEmotion页面的高度监听器
      await nextTick(); // 确保DOM更新后启动监听器
      startAiEmotionHeightObserver();
    } else {
      // 其他页面时停止AiEmotion页面的高度监听器
      stopAiEmotionHeightObserver();
    }
  },
  { deep: true, immediate: true }
);

// 获取token的核心函数
// const fnGetToken = () => {
//   // console.log('进入fnGetToken')
//   window.JWready = (ress) => {
//     // console.log('进入JWready')
//     try {
//       ress = JSON.parse(ress);
//       // console.log(ress, 'ress')
//     } catch (error) {
//       console.log(error, "fnGetToken error");
//     } //platform为5是app端
//     // platform.value = ress.data.platform
//     // 处理平台判断
//     console.log(ress.data.platform, "ress.data.platform");
//     if (!ress.data.platform) {
//       // 非App环境通过URL参数获取
//       localStorage.setItem(
//         "localToken",
//         decodeURIComponent(String(getQueryVariable("token")))
//       );
//       // localStorage.setItem('localToken', "+SsksARQgUHIbIG3rRnnbZi0+fEeMx8pywnIlrmTxo5EOPR/wjWDV7w7+ZUseiBtf9kFa/atmNx6QfSpv5w")
//     } else {
//       // App环境通过桥接获取
//       useAppBridge().packageFun(
//         "JWgetStorage",
//         (response) => {
//           const res = JSON.parse(response); // 解析返回的结果
//           localStorage.setItem("localToken", res.data);
//           // localStorage.setItem('localToken', "+SsksARQgUHIbIG3rRnnbZi0+fEeMx8pywnIlrmTxo5EOPR/wjWDV7w7+ZUseiBtf9kFa/atmNx6QfSpv5w")
//         },
//         5,
//         {
//           key: "token",
//         }
//       );
//     }
//   };
//   // console.log('出来了')
//   // 触发App桥接
//   useAppBridge().packageFun("JWwebReady", () => {}, 5, {});
// };

// 在setTimeout中延迟执行
// setTimeout(() => {
//   fnGetToken();
// }, 800);

const heightListener = () => {
  const tabContainer = getCurrentScrollContainer();
  if (!tabContainer) return;

  let befortop = 0;

  const scrollHandler = () => {
    const aftertop = tabContainer.scrollTop;

    // 新增底部判断逻辑
    const isBottom =
      aftertop + tabContainer.offsetHeight + 70 >= tabContainer.scrollHeight;

    if (activeTab.value === "AIchat") {
      if (aftertop - befortop > 0) {
        // console.log("向下滚动");
        isScrolling.value = true;
      } else {
        // console.log("向上滚动");
        isScrolling.value = true;
      }

      // 添加底部状态检测
      if (isBottom) {
        // console.log("滚动到底部");
        isScrolling.value = false;
      }
    }
    befortop = aftertop;
  };

  // console.log(isScrolling.value, 'isScrolling.value')

  tabContainer.addEventListener("scroll", scrollHandler);
};

const throttledHeightListener = _.throttle(heightListener, 500, {
  trailing: false,
});

// const goToRecharge = () => {
//   console.log("点击充值");
//   // http://39.101.133.168:8919/payment/recharge/index?
//   // url=http%3A%2F%2Flocalhost%3A8080%2FLiveActivity%2Fpck
//   // &platform=1
//   // &token=+S4h5QEE1hTIb4CxphrnbZi0+fEeMx8pywnIlrmTmo4QO6IolWnVWu5r+J4rKXMwK41UPfKqyIp+RvWmtM8

//   const userAgent = navigator.userAgent.toLowerCase();
//   const mobileKeywords = ["mobile", "android", "iphone", "ipad", "ipod"];
//   const isMobile = mobileKeywords.some((keyword) =>
//     userAgent.includes(keyword)
//   );

//   console.log(isMobile ? "手机" : "电脑");

//   const url = encodeURI("http://39.101.133.168:8857/aixiaocaishen/homePage");
//   console.log(url, "url");
//   const platform = isMobile ? 2 : 1;
//   const token = encodeURIComponent(localStorage.getItem("localToken"));
//   console.log(token, "token");
//   const rechargeUrl =
//     "http://39.101.133.168:8919/payment/recharge/index?" +
//     "url=" +
//     url +
//     "&platform=" +
//     platform +
//     "&token=" +
//     token;
//   console.log(rechargeUrl, "rechargeUrl");
//   window.location.href = rechargeUrl;
//   // window.open(rechargeUrl)
// };

const adjustFooterPosition = (height) => {
  const html = document.querySelector("html");
  const body = document.querySelector("body");

  const isAndroid = /Android/i.test(navigator.userAgent);
  if (isAndroid) {
    console.log("是安卓设备");
    console.log("window.visualViewport", window.visualViewport.height);
    const homePage = document.querySelector(".homepage");

    homePage.style.height = `${height}px`;
    // homePage.style.height = `460px`;

    html.scrollTop = 0;
  } else {
    console.log("非安卓设备");
    console.log("调整底部位置", height);
    const homePage = document.querySelector(".homepage");
    homePage.style.height = `${height}px`;

    html.scrollTop = 0;
  }
  setTimeout(() => {
    // 隐藏滚动条
    html.style.overflow = "hidden";
    body.style.overflow = "hidden";
  }, 200);
};

// 是否正在输入法组合
const inputing = ref(false);

const onFocus = function () {
  const visualViewport = window.visualViewport;
  // 获取可视区域高度
  setTimeout(() => {
    console.log("输入框聚焦");

    console.log(visualViewport.height, "visualViewport.height");
    const keyboardHeight = window.innerHeight - visualViewport.height;
    console.log(window.innerHeight, "window.innerHeight");
    console.log(keyboardHeight, "keyboardHeight");

    adjustFooterPosition(visualViewport.height);
  }, 200);
};

const onBlur = function () {
  inputing.value = false;
  const visualViewport = window.visualViewport;
  setTimeout(() => {
    console.log("输入框失焦");

    const keyboardHeight = window.innerHeight - visualViewport.height;
    console.log(window.innerHeight, "window.innerHeight");
    console.log(visualViewport.height, "visualViewport.height");
    console.log(keyboardHeight, "keyboardHeight");
    adjustFooterPosition(visualViewport.height);
  }, 200);
};

// window.addEventListener("resize", () => {
//   // 检测是否为iOS设备
//   const isIOS = /iPhone|iPad|iPod|ios/i.test(navigator.userAgent);
//   console.log("是否为iOS设备:", isIOS);
//   if (!isIOS) {
//     console.log("窗口大小变化");
//     const homePage = document.querySelector(".homepage");
//     homePage.style.height = `${window.innerHeight}px`;
//   }
// });

let touchmoveHandlerRef = null;
const touchmoveHandler = (e) => {
  if (!dataStore.isFeedback) {
    if (historyRecordRef) {
      if (!historyRecordRef.value.isCollapsed) {
        return;
      }
    }
    // 判断触摸目标是否在当前活动页面的可滚动区域内
    const currentContainer = getCurrentScrollContainer();
    const isScrollableArea =
      currentContainer && currentContainer.contains(e.target);

    // 如果不在可滚动区域，则阻止滚动
    if (!isScrollableArea) {
      e.preventDefault();
    }
  }
};

const judgeDevice = async () => {
  // 延时300ms
  await new Promise((resolve) => setTimeout(resolve, 200));
  const userAgent = navigator.userAgent;
  isMobile.value =
    /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(
      userAgent
    );
  console.log("当前设备为：", isMobile.value ? "移动端" : "PC端");
};

const throttledJudgeDevice = _.throttle(judgeDevice, 300, {
  trailing: false,
});

const expandHistory = () => {
  if (
    historyRecordRef.value &&
    historyRecordRef.value.isCollapsed !== undefined
  ) {
    console.log("存在");
    historyRecordRef.value.isCollapsed = !historyRecordRef.value.isCollapsed;
    if (activeTab.value == "AIchat") {
      chatStore.aiChatCall = true;
    } else if (activeTab.value == "AiEmotion") {
      chatStore.aiEmotionCall = true;
    } else if (activeTab.value == "deepNine") {
      chatStore.deepNineCall = true;
    }
  }
};

const feedbackBack = () => {
  dataStore.isFeedback = false;
};

const backToHome = () => {
  if (isMobile.value) {
    console.log("用户是移动端");
    // 调用原生方法跳转到首页
    uni.postMessage({
      data: {
        val: {
          name: "JWopenView",
          extra: {
            data: {
              type: 3,
            },
          },
        },
      },
    });
  } else {
    console.log("用户是pc端");
    const env = import.meta.env.VITE_ENV;
    console.log("当前的环境为：", env);
    if (env == "development" || env == "test") {
      window.parent.location.href =
        "http://121.89.234.155:8807/hljw/homepage?menu=999999991";
    } else {
      window.parent.postMessage(
        {
          type: "NAVIGATE_TO_HOMEPAGE",
          menu: "999999991",
        },
        "*"
      );
    }
    // window.parent.location.href = window.parent.document.referrer
  }
};

// 8.18金币兑换Token start
const userInfo = ref({
  nickname: "",
  img: "",
  jwcode: "",
});
const changeRule = ref({
  gold: 1,
  token: 1,
});
const changeLevelList = ref([
  { position: 10, calculatedPosition: 10 },
  { position: 20, calculatedPosition: 20 },
  { position: 50, calculatedPosition: 50 },
  { position: 100, calculatedPosition: 100 },
  { position: 200, calculatedPosition: 200 },
  { position: 500, calculatedPosition: 500 },
  { position: 1000, calculatedPosition: 1000 },
]);
const activeLevel = ref(
  changeLevelList.value[0] || { position: 10, calculatedPosition: 10 }
);
const gold = ref(90);
// 点击剩余次数会弹出的弹窗
// 新增一个 ref 来控制弹窗的显示与隐藏
const dialogVisible = ref(false);
const rechargeDialogVisible = ref(false);
const confirmDialogVisible = ref(false);
const changeSuccessDialogVisible = ref(false);

// 图片加载错误处理
const handleImageError = (event) => {
  console.error("图片加载失败:", event.target.src);
  // 可以设置默认图片或重试逻辑
  event.target.src =
    "https://cdn.legu168.com/jtzy/Product/pcjingwang/images/userimg.png";
};

// 获取次数
const showCount = async () => {
  try {
    if (activeTab.value == "deepNine") {
      return;
    }
    if (
      !dataStore.userInfo.img ||
      !dataStore.userInfo.nickname ||
      !dataStore.userInfo.jwcode
    ) {
      console.log("缺少用户信息，调用方法");
      await getUserInfo();
    }

    userInfo.value.nickname = dataStore.userInfo.nickname;
    userInfo.value.img = dataStore.userInfo.img;
    userInfo.value.jwcode = dataStore.userInfo.jwcode;
    console.log("userInfo", userInfo.value);
    const [res, res2] = await Promise.all([
      showExchangeAPI(),
      getGoldCoinAPI({
        token: String(localStorage.getItem("localToken")),
      }),
    ]);
    changeLevelList.value = res.data;

    activeLevel.value = changeLevelList.value[0];

    changeRule.value.token = res.data[0].ratio;
    gold.value = res2.data.total;

    // 显示弹窗
    dialogVisible.value = true;
    console.log("dialogVisible 的值:", dialogVisible.value); // 添加日志确认
  } catch (e) {
    console.error("获取兑换列表出错", e);
  }
};

const chooseLevel = (item) => {
  activeLevel.value = item;
};

const changeToken = () => {
  if (gold.value < activeLevel.value.position) {
    rechargeDialogVisible.value = true;
    return;
  } else {
    confirmDialogVisible.value = true;
  }
};

const goRecharge = () => {
  console.log("执行前往充值方法");
  sessionStorage.setItem("rechargeFlag", "1");
  sessionStorage.setItem("activeLevel", JSON.stringify(activeLevel.value));

  if (isMobile.value) {
    console.log("用户是移动端");

    uni.postMessage({
      data: {
        val: {
          name: "JWopenView",
          extra: {
            data: {
              type: 4,
            },
          },
        },
      },
    });
  } else {
    console.log("用户是pc端");
    const env = import.meta.env.VITE_ENV;
    console.log("当前的环境为：", env);
    if (env == "development" || env == "test") {
      window.parent.location.href =
        "http://121.89.234.155:8807/user/myGold?token=" +
        encodeURIComponent(localStorage.getItem("localToken")) +
        "&where=xiaocaishen&successUrl=https://hwjb.homilychart.com/aixiaocaishen/homePage";
      // "&where=xiaocaishen&successUrl=http://192.168.1.5:3000/aixiaocaishen/homePage";
    } else {
      window.parent.location.href =
        "https://web.homilychart.com/user/myGold?token=" +
        encodeURIComponent(localStorage.getItem("localToken")) +
        "&where=xiaocaishen&successUrl=https://mp.homilychart.com/aixiaocaishen/homePage";
    }
    // window.parent.location.href = window.parent.document.referrer
  }
};

const goChange = async () => {
  try {
    await exchangeAPI({
      token: String(localStorage.getItem("localToken")),
      num: activeLevel.value.position,
    });

    confirmDialogVisible.value = false;
    dialogVisible.value = false;
    changeSuccessDialogVisible.value = true;
    // setTimeout(() => {
    //   changeSuccessDialogVisible.value = false;
    // }, 2000);

    // 刷新次数
    await chatStore.getUserCount();
  } catch (e) {
    console.error("兑换失败", e);
  }
};
// 8.18金币兑换Token end

onMounted(async () => {
  // 检查是否需要显示Token规则提示框
  checkTokenRuleOnPageLoad();

  throttledJudgeDevice();
  // 禁用全局触摸滚动
  touchmoveHandlerRef = touchmoveHandler;
  document.addEventListener("touchmove", touchmoveHandlerRef, {
    passive: false,
  });

  setHeight(document.getElementById("testId")); // 给父组件发送窗口高度
  // 获取次数
  await chatStore.getUserCount();

  // 滚动到底部
  throttledSmoothScrollToBottom();
  // 监听页面高度
  throttledHeightListener();

  // 添加输入框焦点处理
  // handleInputFocus();

  // 初始化视口高度变量
  // updateAppHeight();

  // 添加原生事件监听器
  window.showCountHandler = showCount;

  window.addEventListener("resize", throttledJudgeDevice);

  window.receiveUniAppMessage = async function (messageData) {
    console.log("收到 uni-app 消息:", messageData);

    // 根据消息类型进行不同处理
    switch (messageData.type) {
      case "paymentSuccess":
        // 处理支付成功消息
        const [res1, res2] = await Promise.all([
          godExchangeAPI({ state: 1 }),
          getGoldCoinAPI({ token: String(localStorage.getItem("localToken")) }),
        ]);
        gold.value = res2.data.total;
        rechargeDialogVisible.value = false;

        break;
      default:
        console.log("未知消息类型:", messageData.type);
    }
  };

  if (
    sessionStorage.getItem("rechargeFlag") == "1" &&
    getQueryVariable("successType") == "success"
  ) {
    await godExchangeAPI({ state: 1 });
    await showCount();
    activeLevel.value =
      JSON.parse(sessionStorage.getItem("activeLevel")) ||
      changeLevelList.value[0];
    console.log("activeLevel", activeLevel.value);

    sessionStorage.removeItem("activeLevel");
    sessionStorage.setItem("rechargeFlag", "0");
  }
});

onUnmounted(() => {
  window.removeEventListener("resize", throttledJudgeDevice);
  if (touchmoveHandlerRef) {
    console.log("卸载touchmoveHandlerRef组件");
    document.removeEventListener("touchmove", touchmoveHandlerRef);
  }
  // 清理AiEmotion页面的高度监听器
  stopAiEmotionHeightObserver();

  delete window.showCountHandler;

  delete window.receiveUniAppMessage;

  // 清理图表交互相关的定时器和全局函数
  if (chartInteractionTimer.value) {
    clearTimeout(chartInteractionTimer.value);
  }
  if (window.handleChartInteractionStart) {
    delete window.handleChartInteractionStart;
  }
  if (window.handleChartInteractionEnd) {
    delete window.handleChartInteractionEnd;
  }
});
</script>

<template>
  <div class="homepage" id="testId">
    <!-- 历史记录组件 -->
    <HistoryRecord
      ref="historyRecordRef"
      :current-type="activeTab"
      @selectRecord="handleHistorySelect"
      :isMobile="isMobile"
      @showAnnouncement="showAnnouncement"
      @showFeedback="showFeedback"
    />

    <div
      v-if="isMobile && !historyRecordRef?.isCollapsed"
      class="zhezhao"
      @click="expandHistory"
    ></div>

    <el-container
      v-if="!dataStore.isFeedback"
      class="main-container"
      :class="{
        collapsed: !isMobile && historyRecordRef?.isCollapsed,
        unCollapsed: !isMobile && !historyRecordRef?.isCollapsed,
      }"
    >
      <!-- AI小财神头部： logo  次数  公告 -->
      <el-header class="homepage-head">
        <!-- logo -->
        <div class="homepage-logo" v-if="isMobile">
          <img
            class="expand"
            @click="expandHistory"
            src="https://d31zlh4on95l9h.cloudfront.net/images/37fe3d79a8a700f6c674c9f0e7af066b.png"
            alt="icon"
          />
          <img :src="logo" alt="图片加载失败" class="logo1" />
          <!-- <img :src="madeInHL" alt="图片加载失败" class="logo2" /> -->
        </div>

        <div class="homepage-right-group" v-if="isMobile">
          <div
            class="count-badge"
            @click="showCount"
            :class="{ 'deepnine-model': activeTab === 'deepNine' }"
          >
            <img
              v-if="activeTab !== 'deepNine'"
              src="https://d31zlh4on95l9h.cloudfront.net/images/74e20c65c9ef2526477c63ad68698a50.png"
              class="action-btn"
            />
            <img
              v-else
              src="https://d31zlh4on95l9h.cloudfront.net/images/4621e0d1463a13c6654fe39215ee64c2.png"
              class="action-btn"
            />
            <div class="count-number">{{ UserCount }}</div>
            <div class="clickGetCount">
              {{
                activeTab === "deepNine" ? "深度九专属Token" : "点击获取Token"
              }}
            </div>
          </div>
          <div class="backToHomeBtn" @click="backToHome()">
            <img
              src="https://d31zlh4on95l9h.cloudfront.net/images/9272c00f21a2724c3a76e375949ee1de.png"
              alt="返回首页"
              class="backImg"
            />
            <div class="backContent">返回首页</div>
          </div>
          <!-- <img
            :src="announcementBtn"
            class="announcement-btn action-btn"
            @click="showAnnouncement"
          />
          <img
            :src="feedbackBtn"
            class="announcement-btn action-btn"
            @click="showFeedback"
          /> -->
        </div>
      </el-header>

      <!-- 主体部分：小人  问题轮询图  对话内容 -->
      <el-main class="homepage-body">
        <div class="main-wrapper">
          <section class="tab-section">
            <div
              class="tab-container"
              :class="{
                pcTabContainer: !isMobile,
              }"
            >
              <div class="tab-items-container">
                <div
                  v-for="(tab, index) in tabs"
                  :key="tab.name"
                  @click="setActiveTab(tab.name, index)"
                  :class="[
                    'tab-item',
                    { active: activeIndex === index && !isAnnouncementVisible },
                  ]"
                >
                  <span>{{ tab.label }}</span>
                </div>
              </div>
              <div v-if="!isMobile" class="pc-count-badge">
                <div class="pc-countBtn" @click="showCount">
                  <div
                    class="pc-action-btn"
                    :class="{
                      'dbqb-model': activeTab === 'dbqb',
                      'emotion-model': activeTab === 'emotion',
                      'deepnine-model': activeTab === 'deepNine',
                    }"
                  >
                    <div class="pc-count-number">{{ UserCount }}</div>
                  </div>
                  <div class="pc-clickGetCount">
                    {{
                      activeTab === "deepNine"
                        ? "深度九专属Token"
                        : "点击获取Token"
                    }}
                  </div>
                </div>
                <div class="pc-backToHomeBtn" @click="backToHome()">
                  <img
                    src="https://d31zlh4on95l9h.cloudfront.net/images/9272c00f21a2724c3a76e375949ee1de.png"
                    alt="返回首页"
                    class="pc-backImg"
                  />
                  <div class="pc-backContent">返回首页</div>
                </div>
              </div>
            </div>
          </section>
          <!-- AIchat页面的独立滚动容器 -->
          <div
            v-show="activeTab === 'AIchat'"
            class="tab-content"
            :class="{
              pcTabContent: !isMobile,
            }"
            ref="tabContentAIchat"
          >
            <component
              v-if="activeTab === 'AIchat'"
              :is="activeComponent"
              :messages="messages"
              @updateMessage="updateMessage"
              @sendMessage="sendMessage"
              @ensureAIchat="ensureAIchat"
              @enableInput="enableInput"
            />
          </div>

          <!-- AiEmotion页面的独立滚动容器 -->
          <div
            v-show="activeTab === 'AiEmotion'"
            class="tab-content"
            :class="{
              pcTabContent: !isMobile,
            }"
            ref="tabContentAiEmotion"
          >
            <component
              v-if="activeTab === 'AiEmotion'"
              :is="activeComponent"
              :messages="messages"
              @updateMessage="updateMessage"
              @sendMessage="sendMessage"
              @ensureAIchat="ensureAIchat"
              @enableInput="enableInput"
              @scrollToBottom="handleAiEmotionScrollToBottom"
              @showCount="showCount"
              ref="aiEmotionRef"
            />
          </div>
          <!-- deepNine页面的独立滚动容器 -->
          <div
            v-show="activeTab === 'deepNine'"
            class="tab-content"
            :class="{
              pcTabContent: !isMobile,
            }"
            ref="tabContentDeepNine"
          >
            <component
              v-if="activeTab === 'deepNine'"
              :is="activeComponent"
              :messages="messages"
              @updateMessage="updateMessage"
              @sendMessage="sendMessage"
              @ensureAIchat="ensureAIchat"
              @enableInput="enableInput"
              @scrollToBottom="handleDeepNineScrollToBottom"
              @showCount="showCount"
              ref="deepNineRef"
            />
          </div>
        </div>
      </el-main>
      <!-- 尾部： 问题输入框 深度思考 多语言 语音播报 -->
      <el-footer
        class="homepage-footer"
        :class="{
          pcFooter: !isMobile,
        }"
        id="input"
      >
        <!-- 第一行按钮 -->
        <div class="footer-first-line">
          <div class="left-group">
            <!-- <img v-if="isThinking" :src="thinkActive" @click="toggleThink" class="action-btn" />
            <img v-else :src="thinkNoActive" @click="toggleThink" class="action-btn" />
            <img :src="languageBtn" @click="changeLanguage" class="action-btn" /> -->
            <!-- PC端按钮 -->
            <template v-if="!isMobile">
              <!-- 夺宝奇兵大模型按钮 -->
              <img
                :src="activeTab === 'AIchat' ? dbqbButton01 : dbqbButton02"
                @click="setActiveTab('AIchat', 0)"
                class="action-btn model-btn"
                alt="夺宝奇兵大模型"
              />
              <!-- AI情绪大模型按钮 -->
              <img
                :src="
                  activeTab === 'AiEmotion' ? emotionButton01 : emotionButton02
                "
                @click="setActiveTab('AiEmotion', 1)"
                class="action-btn model-btn"
                alt="AI情绪大模型"
              />
              <!-- 深度九大模型按钮 -->
              <img
                :src="
                  activeTab === 'deepNine'
                    ? 'https://d31zlh4on95l9h.cloudfront.net/images/07349ebc846a6772b1ab8a47b54635ff.png'
                    : 'https://d31zlh4on95l9h.cloudfront.net/images/29f0ad8e4e47f58952cc4a957ce9db10.png'
                "
                @click="setActiveTab('deepNine', 2)"
                class="action-btn model-btn"
                alt="深度九大模型"
              />
            </template>

            <!-- 手机端下拉选择 - 自定义组件 -->
            <template v-else>
              <div class="custom-select-container">
                <div class="custom-select-header" @click="toggleDropdown">
                  <div class="select-option-with-image">
                    <img :src="getSelectedOptionImage()" class="option-image" />
                    <span>{{ getSelectedOptionLabel() }}</span>
                  </div>
                  <div
                    class="dropdown-arrow"
                    :class="{ 'arrow-up': isDropdownOpen }"
                  >
                    <img
                      src="https://d31zlh4on95l9h.cloudfront.net/images/5f96dfcbff643cbbcf0f2790dbb4e54a.png"
                      style="width: 24px; height: 24px; object-fit: contain"
                      alt="箭头"
                    />
                  </div>
                </div>
                <div class="custom-select-dropdown" v-if="isDropdownOpen">
                  <div
                    v-for="option in modelOptions"
                    :key="option.value"
                    class="custom-select-option"
                    :class="{
                      'option-selected': activeTabMobile === option.value,
                    }"
                    @click="selectOption(option.value)"
                  >
                    <div class="select-option-with-image">
                      <img :src="option.image" class="option-image" />
                      <span>{{ option.label }}</span>
                    </div>
                  </div>
                </div>
              </div>
            </template>
            <!-- <img v-if="
              getCurrentAudioStore().isVoiceEnabled &&
              getCurrentAudioStore().isPlaying
            " :src="voice" @click="toggleVoice" class="action-btn" style="animation: pulse 1.5s infinite" />
            <img v-else-if="
              getCurrentAudioStore().isVoiceEnabled &&
              !getCurrentAudioStore().isPlaying
            " :src="voiceNoActive" @click="toggleVoice" class="action-btn" />
            <img v-else :src="voiceNoActive" @click="toggleVoice" class="action-btn" /> -->
          </div>
        </div>

        <!-- 第二行输入框 -->
        <div class="footer-second-line">
          <!-- <img :src="msgBtn" class="msg-icon" /> -->
          <div class="input-container">
            <el-input
              type="textarea"
              v-model="message"
              @focus="onFocus"
              @blur="onBlur"
              :autosize="{ minRows: 1, maxRows: 4 }"
              class="msg-input"
              @keydown.enter.exact.prevent="
                isLoading || isInputDisabled ? null : sendMessage()
              "
              :disabled="isInputDisabled"
              resize="none"
              :class="{ input: !message && !inputing }"
              @compositionstart="inputing = true"
              @compositionend="inputing = false"
            >
            </el-input>
            <img
              :src="
                isInputDisabled
                  ? 'https://d31zlh4on95l9h.cloudfront.net/images/aa192bcbc1682c97e1bc6fb422f2afff.png'
                  : 'https://d31zlh4on95l9h.cloudfront.net/images/e6ec2ae238ced85b74e0912e988f243e.png'
              "
              @click="sendMessage"
              class="action-btn send-btn-inner"
              :style="{
                opacity: isInputDisabled ? 0.5 : 1,
                cursor: isInputDisabled ? 'not-allowed' : 'pointer',
              }"
            />
          </div>
        </div>
      </el-footer>
    </el-container>
    <el-container
      v-else
      class="main-container"
      :class="{
        collapsed: historyRecordRef?.isCollapsed && !isMobile,
        unCollapsed: !historyRecordRef?.isCollapsed && !isMobile,
      }"
    >
      <el-header class="homepage-head">
        <!-- logo -->
        <div class="homepage-logo">
          <img
            src="https://d31zlh4on95l9h.cloudfront.net/images/4c91fce359a1c184772857594c38e3b4.png"
            alt="返回按钮"
            class="backToHomeImg"
            @click="feedbackBack"
          />
          <!-- <img :src="madeInHL" alt="图片加载失败" class="logo2" /> -->
        </div>

        <div class="homepage-right-group">
          <div class="count-badge" @click="showCount">
            <img
              v-if="activeTab !== 'deepNine'"
              src="https://d31zlh4on95l9h.cloudfront.net/images/74e20c65c9ef2526477c63ad68698a50.png"
              class="action-btn"
            />
            <img
              v-else
              src="https://d31zlh4on95l9h.cloudfront.net/images/4621e0d1463a13c6654fe39215ee64c2.png"
              class="action-btn"
            />
            <div class="count-number">{{ UserCount }}</div>
            <div class="clickGetCount">点击获取Token</div>
          </div>
          <div class="backToHomeBtn" @click="backToHome()">
            <img
              src="https://d31zlh4on95l9h.cloudfront.net/images/9272c00f21a2724c3a76e375949ee1de.png"
              alt="返回首页"
              class="backImg"
            />
            <div class="backContent">返回首页</div>
          </div>
          <!-- <img
            :src="announcementBtn"
            class="announcement-btn action-btn"
            @click="showAnnouncement"
          />
          <img
            :src="feedbackBtn"
            class="announcement-btn action-btn"
            @click="showFeedback"
          /> -->
        </div>
      </el-header>

      <!-- 主体部分：小人  问题轮询图  对话内容 -->
      <el-main class="homepage-body">
        <component :is="activeTwoTab" />
      </el-main>
    </el-container>
    <!-- 弹窗 -->
    <!-- 新增弹窗组件 -->
    <el-dialog v-if="!isMobile" v-model="dialogVisible" width="48%">
      <!-- 中间内容部分 -->
      <div class="changeMsg">
        <div class="changeInfo">
          <div class="changeImg">
            <img
              :src="userInfo.img"
              alt="头像"
              class="changeImgClass"
              @error="handleImageError"
            />
          </div>
          <div class="changeContent">
            <div class="changeUsername">{{ userInfo.nickname }}</div>
            <div class="changeJwcode">精网号：{{ userInfo.jwcode }}</div>
          </div>
        </div>
        <div class="changeRule" @click="openTokenRuleDialog">
          兑换规则：{{ changeRule.gold }}金币={{ changeRule.token }}Token
          <div>点击查看详情</div>
        </div>
      </div>
      <div class="changeLevel">
        <div class="changeLevelTitle">兑换Token</div>
        <div class="changeLevelContent">
          <div
            class="changeLevelItems"
            v-for="item in changeLevelList"
            :key="item"
            :class="{
              changeLevelItemsActive: item.position == activeLevel.position,
            }"
            @click="chooseLevel(item)"
          >
            <div class="changeLevelItem">
              <div class="changeLevelItemToken">
                <img
                  src="https://d31zlh4on95l9h.cloudfront.net/images/403ef762dd2f335df3b0c9e3fe488375.png"
                  alt="token"
                  class="changeLevelItemTokenImg"
                />
                {{ item.calculatedPosition }}
              </div>
              <div class="changeLevelItemToken">{{ item.position }} 金币</div>
            </div>
          </div>
        </div>
      </div>
      <div class="changeNow">
        应付金额
        <div class="changePay">{{ activeLevel.position }}</div>

        (金币余额：{{ gold }})
      </div>
      <div class="changeBtn" @click="changeToken">立即兑换</div>
    </el-dialog>

    <el-dialog v-else v-model="dialogVisible" width="80%">
      <!-- 中间内容部分 -->
      <div class="changeMsg">
        <div class="changeInfo">
          <div class="changeImg">
            <img
              :src="userInfo.img"
              alt="头像"
              class="changeImgClass"
              @error="handleImageError"
            />
          </div>
          <div class="changeContent">
            <div class="changeJwcode">精网号：{{ userInfo.jwcode }}</div>
          </div>
        </div>
      </div>
      <div class="changeLevel">
        <div class="changeLevelTitle">
          兑换Token
          <div class="changeRule" @click="openTokenRuleDialog">
            (兑换规则：{{ changeRule.gold }}金币={{ changeRule.token }}Token)
            <div>点击查看详情</div>
          </div>
        </div>

        <div class="changeLevelContent">
          <div
            class="changeLevelItems"
            v-for="item in changeLevelList"
            :key="item"
            :class="{
              changeLevelItemsActive: item.position == activeLevel.position,
            }"
            @click="chooseLevel(item)"
          >
            <div class="changeLevelItem">
              <div class="changeLevelItemToken">
                <img
                  src="https://d31zlh4on95l9h.cloudfront.net/images/403ef762dd2f335df3b0c9e3fe488375.png"
                  alt="token"
                  class="changeLevelItemTokenImg"
                />
                {{ item.calculatedPosition }}
              </div>
              <div class="changeLevelItemToken">{{ item.position }} 金币</div>
            </div>
          </div>
        </div>
      </div>
      <div class="changeNow">
        应付金额
        <div class="changePay">{{ activeLevel.position }}</div>

        (金币余额：{{ gold }})
      </div>
      <div class="changeBtn" @click="changeToken">立即兑换</div>
    </el-dialog>

    <el-dialog
      v-model="rechargeDialogVisible"
      :width="isMobile ? '60%' : '30%'"
      :show-close="false"
    >
      <div class="rechargeDialogTitle">温馨提示</div>
      <div class="rechargeDialogContent">
        尊敬的用户您好！您当前的金币余额不足，无法进行兑换，可充值金币后进行兑换。点击下方的“前往充值”可进行充值。
      </div>
      <div class="rechargeDialogBtnGroup">
        <div class="recharge" @click="goRecharge">前往充值</div>

        <div
          class="rechargeDialogCancel"
          @click="rechargeDialogVisible = false"
        >
          取消
        </div>
      </div>
    </el-dialog>

    <el-dialog
      v-model="confirmDialogVisible"
      :width="isMobile ? '60%' : '30%'"
      :show-close="false"
      align-center="true"
    >
      <div class="confirmDialogTitle">兑换</div>
      <div class="confirmDialogContent">
        尊敬的用户您好！您确认要花费{{ activeLevel.position }}金币兑换{{
          activeLevel.calculatedPosition
        }}Token吗？
      </div>
      <div class="confirmDialogBtnGroup">
        <div class="confirmDialogConfirm" @click="goChange()">确认</div>
        <div class="confirmDialogCancel" @click="confirmDialogVisible = false">
          取消
        </div>
      </div>
    </el-dialog>

    <el-dialog
      v-model="changeSuccessDialogVisible"
      :width="isMobile ? '60%' : '30%'"
      :show-close="false"
      class="changeSuccessDialog"
      align-center
      center
    >
      <div class="changeSuccessDialogTitle">
        <img
          v-if="!isMobile"
          src="https://d31zlh4on95l9h.cloudfront.net/images/84edd341b2ddec464fc4475254f7a309.png"
          style="scale: 0.7"
          alt="token图标"
        />
        兑换成功
      </div>
      <div class="changeSuccessDialogContent">
        尊敬的用户，恭喜您成功兑换：{{ activeLevel.calculatedPosition }} Token
      </div>
      <div class="changeSuccessDialogFooter">
        <button
          class="confirmButton"
          @click="changeSuccessDialogVisible = false"
        >
          确定
        </button>
      </div>
    </el-dialog>

    <!-- Token规则提示框 -->
    <div
      v-if="tokenRuleDialogVisible"
      class="tokenRuleDialog"
      @click="closeTokenRuleDialog"
    >
      <div class="tokenRuleDialogContent" @click.stop>
        <div class="tokenRuleDialogClose" @click="closeTokenRuleDialog">
          <el-icon>
            <Close />
          </el-icon>
        </div>
        <div class="tokenRuleDialogTitle">Token规则</div>

        <div class="tokenRuleSection">
          <div class="tokenRuleSectionTitle">Token消耗规则</div>
          <div class="tokenRuleItem">
            •
            "夺宝奇兵大模型"和"AI情绪大模型"中搜索股票消耗普通Token，"深度九大模型"中搜索股票消耗专属Token
          </div>
          <div class="tokenRuleItem">
            •
            在"夺宝奇兵大模型"、"AI情绪大模型"、"深度九大模型"中搜索股票，若搜索成功，内容正常生成，则会消耗1Token
          </div>
          <div class="tokenRuleItem">
            •
            在"夺宝奇兵大模型"、"AI情绪大模型"、"深度九大模型"中搜索股票，若搜索有误，无法生成内容，则不会消耗Token
          </div>
          <div class="tokenRuleItem">
            • 搜索同一只股票，产出内容相同时，只扣除1Token
          </div>
          <div class="tokenRuleItem">
            • "夺宝奇兵"中的Token和"AI小财神"中的普通Token是互通的
          </div>
        </div>

        <div class="tokenRuleSection">
          <div class="tokenRuleSectionTitle">Token兑换规则</div>
          <div class="tokenRuleItem">
            •
            点击右上角"获取Token"，即可进入Token兑换页进行金币兑换Token（只能兑换普通Token）
          </div>
          <div class="tokenRuleItem">
            • 金币兑换Token的比例为：1金币=1Token；一经兑换，不予退还
          </div>
        </div>

        <div class="tokenRuleNote">
          注意：报告生成过程中，请耐心等待，在此期间请勿进行页面刷新操作，以免导致报告生成进程中断
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
/* 标签栏 */
.tab-container {
  display: flex;
  margin-bottom: 10px;
  height: 100%;
  position: relative;
  align-items: center;
  width: 100%;
  /* 使用三段式布局 */
  justify-content: space-between;
}

.tab-items-container {
  display: flex;
  justify-content: center;
  flex: 1;
  gap: 200px;
}

.pcTabContainer {
  padding: 0 20px;
  /* 添加内边距，避免内容贴边 */
}

.tab-item {
  cursor: pointer;
  padding: 8px 12px;
  font-size: clamp(18px, 3vw, 20px);
  color: #fff;
  transition: all 0.3s;
  border-bottom: 2px solid transparent;
  font-weight: bold;
  /* 确保tab项目不会被挤压 */
  flex-shrink: 0;
}

.tab-item.active {
  /* color: #000;
  border-color: #000; */
  background: linear-gradient(0deg, #ffffff, #fec13e);
  -webkit-background-clip: text;
  background-clip: text;
  -webkit-text-fill-color: transparent;
  color: transparent;
  border-color: #fec13e;
}

.tab-item:not(.active):hover {
  color: #999999;
}

.tab-content {
  overflow-y: auto;
  overflow-x: hidden;
  scroll-behavior: smooth;
  height: 100%;
  /* 添加平滑滚动效果 */
}

.pcTabContent {
  padding: 0 6%;
}

.backToHomeImg {
  width: 40px;
  height: 40px;
  margin-left: 10px;
}

@media (max-width: 768px) {
  .tab-container {
    justify-content: center;
  }

  .tab-items-container {
    justify-content: center;
    gap: 0px;
    /* 移动端使用更小的间距 */
  }

  .tab-item {
    font-size: clamp(14px, 3vw, 16px);
    padding: 6px 10px;
  }
}
</style>

<style scoped>
html {
  height: 100dvh;
  overflow: hidden !important;
  position: fixed;
  margin: 0;
  padding: 0;
  -webkit-overflow-scrolling: auto;
  /* 禁用 iOS 弹性滚动 */
}

body {
  height: 100dvh;
  overflow: clip;
  margin: 0;
  padding: 0;
  -webkit-overflow-scrolling: auto;
  /* 禁用 iOS 弹性滚动 */
  position: fixed;
}

#app {
  overflow: hidden;
  height: 100%;
  margin: 0;
  padding: 0;
}

.homepage {
  /* height: var(--app-height, 100vh); */
  height: var(--app-height, 100vh);
  margin: 0 auto;
  background-image: url("https://d31zlh4on95l9h.cloudfront.net/images/98c8230d386012c9f1e70bf05a30de5e.png");
  background-size: 100% 100%;
  background-repeat: no-repeat;
  background-position: center;
  display: flex;
  flex-direction: row;
  /* 改为水平布局 */
  overflow: hidden;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  width: 100%;
  /* -webkit-overflow-scrolling: touch; */
}

.zhezhao {
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 100;
  position: fixed;
}

@media (min-width: 769px) {
  .main-container {
    flex: 1;
    transition: margin-left 0.3s ease;
    display: flex;
    flex-direction: column;
    overflow: hidden;
  }

  .main-container.unCollapsed {
    margin-left: 300px;
    /* 为历史记录组件留出空间 */
  }

  /* 当历史记录组件折叠时调整主容器边距 */
  .main-container.collapsed {
    margin-left: 40px;
  }
}

/* 移动端适配 */
@media (max-width: 768px) {
  .homepage {
    background-image: url("https://d31zlh4on95l9h.cloudfront.net/images/90d31d7052e729c63acb9e2cb94d1307.png");
  }
}

.homepage .el-container {
  height: 100%;
  flex-direction: column;
  display: flex;
  width: 100%;
  overflow: hidden;
  /* 防止容器滚动 */
}

.el-container .el-header {
  flex-shrink: 0;
  /* 防止头部压缩 */
  height: auto;
  min-height: 60px;
  padding: 5px 0;
  position: sticky;
  top: 0;
  z-index: 10;
  /* background-color: rgba(255, 255, 255, 0.9); */
}

.el-container .el-main {
  flex: 1;
  /* 自动占据剩余空间 */
  overflow: hidden;
  /* 主容器不滚动 */
  display: flex;
  flex-direction: column;
  min-height: 0;
  /* 允许内容区域缩小 */
  position: relative;
  height: auto;
}

.el-container .el-footer {
  flex-shrink: 0;
  height: auto;
  min-height: 70px;
  position: sticky;
  bottom: 0;
  z-index: 20;
  background-color: rgba(211, 24, 24, 0);
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
  -webkit-transform: translateZ(0);
  transform: translateZ(0);
  padding-bottom: env(safe-area-inset-bottom, 0);
  /* 适配iPhone X及以上的底部安全区域 */
}

.homepage-head {
  padding: 0px;
  display: flex;
  position: relative;
  justify-content: space-between;
  width: 100%;
}

.homepage-right-group {
  display: flex;
  /* gap: 8px; */
  align-items: center;
  margin-left: auto;
  margin-right: 5px;
}

.homepage-right-group .action-btn {
  height: 40px;
}

.count-badge {
  position: relative;
  cursor: pointer;
}

.count-badge:hover {
  transform: scale(1.05);
}

.count-number {
  position: absolute;
  top: 16px;
  right: 0px;
  width: 68%;
  text-align: center;
  color: #6a00ff;
}

.deepnine-model .count-number {
  color: blue;
  font-size: 12px;
  font-weight: bold;
}

.clickGetCount {
  width: 100%;
  text-align: center;
  color: white;
  font-size: 12px;
}

.backToHomeBtn {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  cursor: pointer;
}

.backToHomeBtn:hover {
  transform: scale(1.05);
}

.backImg {
  width: 60%;
  height: auto;
}

.backContent {
  width: 100%;
  text-align: center;
  color: white;
  font-size: 12px;
  white-space: nowrap;
}

.pc-count-badge {
  display: flex;
  height: 100%;
  gap: 10px;
  align-items: center;
  /* 移除绝对定位，使用flex布局自然定位 */
  flex-shrink: 0;
}

.pc-countBtn {
  height: 60px;
  width: 115px;
  position: relative;
  cursor: pointer;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.pc-countBtn:hover {
  transform: scale(1.05);
}

.pc-action-btn {
  width: 100%;
  height: 70%;
  background-repeat: no-repeat;
  background-size: 100% 100%;
  background-image: url("https://d31zlh4on95l9h.cloudfront.net/images/74e20c65c9ef2526477c63ad68698a50.png");
}

.pc-action-btn.deepnine-model {
  background-image: url("https://d31zlh4on95l9h.cloudfront.net/images/4621e0d1463a13c6654fe39215ee64c2.png");
}

.pc-count-number {
  position: absolute;
  top: 15px;
  right: 4px;
  width: 68%;
  text-align: center;
  color: #6a00ff;
}

.deepnine-model .pc-count-number {
  color: blue;
  font-size: 15px;
  font-weight: bold;
}

.pc-clickGetCount {
  width: 100%;
  text-align: center;
  color: white;
  font-size: 12px;
}

.pc-backToHomeBtn {
  width: 30%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  cursor: pointer;
}

.pc-backImg {
  width: 100%;
  height: auto;
}

.pc-backContent {
  width: 100%;
  text-align: center;
  color: white;
  font-size: 12px;
}

.pc-backToHomeBtn:hover {
  transform: scale(1.05);
}

.homepage-right-group .announcement-btn {
  cursor: pointer;
  transition: transform 0.3s;
}

.homepage-right-group .announcement-btn:hover {
  transform: scale(1.3);
}

.homepage-body {
  padding: 0px;
  display: flex;
  flex-direction: column;
  flex: 1;
  min-height: 0;
  /* 允许内容区域缩小 */
  overflow: hidden;
}

.main-wrapper {
  height: 100%;
  display: flex;
  flex-direction: column;
  flex: 1;
  min-height: 0;
  /* 允许内容区域缩小 */
}

.tab-section {
  flex-shrink: 0;
  /* 禁止伸缩 */
}

.tab-content {
  flex: 1;
  overflow-y: auto;
  min-height: 0;
  /* 关键：允许内容收缩 */
}

.homepage-logo {
  height: 100%;
  width: fit-content;
  display: flex;
  /* flex-direction: column; */
  align-items: center;
  justify-content: center;
  margin-left: 20px;
  margin-right: auto;
  position: relative;
  gap: 10px;
}

.expand {
  font-size: 2.5rem;
  cursor: pointer;
  color: white;
}

.logo1 {
  width: 110px;
  height: auto;
  margin-bottom: 8px;
}

.logo2 {
  width: 80px;
  height: auto;
}

/* 尾部 */
.homepage-footer {
  display: flex;
  flex-direction: column;
  gap: 5px;
  flex-shrink: 0;
  /* width: 100%; */
  background-color: #fff;
}

.pcFooter {
  margin: 0 6% 4%;
}

.footer-first-line {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 5px 15px;
  flex-shrink: 0;
}

.left-group {
  display: flex;
  gap: 15px;
}

.action-btn {
  cursor: pointer;
  transition: transform 0.2s;
  height: 28px;
}

.model-btn {
  height: 32px;
  transition: all 0.3s ease;
}

.model-btn:hover {
  transform: scale(1.1);
}

/* 手机端模型选择器样式 */
.mobile-model-select {
  width: 180px;
  --el-select-border-color-hover: var(--el-border-color-hover);
  --el-select-disabled-border: var(--el-disabled-border-color);
  --el-select-font-size: var(--el-font-size-base);
  --el-select-close-hover-color: var(--el-text-color-secondary);
  --el-select-input-focus-border-color: var(--el-color-primary);
  --el-select-input-font-size: 14px;
}

.send-btn {
  margin-left: 10px;
  height: 33px !important;
  width: auto;
  /* margin-right: 5px; */
}

.input-container {
  position: relative;
  width: 100%;
}

.send-btn-inner {
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  height: 28px !important;
  width: auto;
  z-index: 10;
  transition: all 0.3s ease;
}

.send-btn-inner:hover {
  transform: translateY(-50%) scale(1.1);
}

/* 音频播放动画 */
@keyframes pulse {
  0% {
    transform: scale(1);
  }

  50% {
    transform: scale(1.1);
  }

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

.footer-second-line {
  position: relative;
  display: flex;
  align-items: center;
  padding: 5px 15px 10px;
  flex-shrink: 0;
}

.msg-icon {
  position: absolute;
  left: 25px;
  top: 50%;
  transform: translateY(-50%);
  width: 24px;
  z-index: 999;
}

.msg-input:deep(.el-textarea__inner) {
  border: none !important;
  box-shadow: none !important;
  overflow-y: auto !important;
  transition: all 0.2s ease-out;
  resize: none !important;
  line-height: 1.5 !important;
  max-height: 100px !important;
  padding-right: 45px !important;
}

.msg-input {
  min-height: 34px;
  width: 100%;
  border-radius: 5px;
  font-size: 16px;
  transition: all 0.3s ease-out;
  overflow-y: hidden;
  box-shadow: 0 4px 12px rgba(89, 24, 241, 0.3);
  background: #fff;
  z-index: 5;
  /* 添加iOS设备特殊处理 */
  -webkit-appearance: none;
  appearance: none;
}

.msg-input:focus {
  outline: none;
}

.input::before {
  content: "请输入股票名称或股票代码...";
  position: absolute;
  left: 11px;
  top: 5px;
  color: var(--el-text-color-secondary);
  pointer-events: none;
  white-space: nowrap;
  overflow-x: hidden;
  text-overflow: ellipsis;
  width: 80%;
  z-index: 6;
}

.changeMsg {
  display: flex;
  width: 100%;
  margin-bottom: 30px;
  flex-wrap: wrap;
  gap: 20px;
}

.changeInfo {
  display: flex;
  background-color: #f8f8f8;
  border-radius: 5px;
  padding: 10px 20px;
  width: 40%;
  white-space: nowrap;
  align-items: center;
  justify-content: center;
}

.changeImg {
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-right: 10px;
}

.changeImgClass {
  width: 50px;
  height: auto;
}

.changeContent {
  display: flex;
  flex-direction: column;
  justify-content: center;
  font-weight: bold;
}

.changeRule {
  display: flex;
  flex-direction: column;
  background-color: #f8f8f8;
  border-radius: 5px;
  text-align: center;
  align-items: center;
  justify-content: center;
  color: #4e86fe;
  white-space: nowrap;
  padding: 5px 20px;
  min-width: 40%;
  transition: all 0.3s ease;
  cursor: pointer;
}

.changeRule:hover {
  background-color: #e8f0ff;
  box-shadow: 0 2px 8px rgba(78, 134, 254, 0.2);
  transform: translateY(-2px);
}

.changeLevel {
  display: flex;
  flex-direction: column;
}

.changeLevelTitle {
  font-weight: bold;
  margin-bottom: 10px;
}

.changeLevelContent {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  margin-bottom: 10px;
}

.changeLevelItems {
  display: flex;
  background-color: #f8f8f8;
  width: calc(20% - 12px);
  min-width: 70px;
  max-width: 150px;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  border-radius: 10px;
  padding: 5px;
  cursor: pointer;
}

.changeLevelItems:hover {
  background-color: #ecf2ff;
}

.changeLevelItemsActive {
  border: 1px solid #4e86fe;
  background-color: #ecf2ff;
}

.changeLevelItem {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.changeLevelItemToken {
  display: flex;
  justify-content: center;
  align-items: center;
}

.changeLevelItemTokenImg {
  width: 40px;
  height: 40px;
}

.changeNow {
  display: flex;
  white-space: nowrap;
  /* font-weight: bold; */
  margin-bottom: 15px;
  align-items: center;
}

.changePay {
  color: #4e86fe;
  margin: 0px 5px;
  font-size: 1.1rem;
}

.changeBtn {
  width: 40%;
  max-width: 350px;
  background-color: #4e86fe;
  color: white;
  display: flex;
  justify-content: center;
  align-content: center;
  padding: 10px;
  border-radius: 5px;
  cursor: pointer;
  margin: 0 auto;
}

.changeBtn:hover {
  background-color: #3a73e6;
}

.rechargeDialogTitle {
  font-size: 1.7rem;
  /* font-weight: bold; */
  color: #4e86fe;
  display: flex;
  justify-content: center;
  align-items: center;
  letter-spacing: 10px;
}

.rechargeDialogContent {
  padding: 20px;
  font-size: 1.2rem;
}

.rechargeDialogBtnGroup {
  display: flex;
  font-size: 1.2rem;
  padding: 0px 20px;
  justify-content: space-between;
}

.recharge {
  color: white;
  background-color: #4e86fe;
  padding: 10px 20px;
  border-radius: 13px;
  cursor: pointer;
  min-width: 20%;
  text-align: center;
  white-space: nowrap;
}

.recharge:hover {
  background-color: #3a73e6;
}

.rechargeDialogCancel {
  border: 1px solid rgb(202, 202, 202);
  padding: 10px 20px;
  border-radius: 13px;
  cursor: pointer;
  min-width: 20%;
  text-align: center;
}

.rechargeDialogCancel:hover {
  background-color: #ecf2ff;
}

.confirmDialogTitle {
  font-size: 1.7rem;
  /* font-weight: bold; */
  color: #4e86fe;
  display: flex;
  justify-content: center;
  align-items: center;
  letter-spacing: 10px;
}

.confirmDialogContent {
  padding: 20px;
  font-size: 1.2rem;
}

.confirmDialogBtnGroup {
  display: flex;
  font-size: 1.2rem;
  padding: 0px 20px;
  justify-content: space-between;
}

.confirmDialogConfirm {
  color: white;
  background-color: #4e86fe;
  padding: 10px 20px;
  border-radius: 13px;
  cursor: pointer;
  min-width: 20%;
  text-align: center;
}

.confirmDialogConfirm:hover {
  background-color: #3a73e6;
}

.confirmDialogCancel {
  border: 1px solid rgb(202, 202, 202);
  padding: 10px 20px;
  border-radius: 13px;
  cursor: pointer;
  min-width: 20%;
  text-align: center;
}

.confirmDialogCancel:hover {
  background-color: #ecf2ff;
}

.changeSuccessDialogTitle {
  font-size: 1.7rem;
  font-weight: bold;
  color: #7849de;
  display: flex;
  justify-content: center;
  align-items: center;
  letter-spacing: 10px;
}

.changeSuccessDialogTitle image {
  font-size: 1.7rem;
  font-weight: bold;
  color: #7849de;
  display: flex;
  justify-content: center;
  align-items: center;
  letter-spacing: 10px;
}

.changeSuccessDialogContent {
  padding: 20px;
  color: white;
  font-size: 1.2rem;
  font-weight: bold;
  text-align: center;
}

/* Token规则提示框样式 - 与DBQBmodel无权限弹出框一致 */
.tokenRuleDialog {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  position: fixed;
  bottom: 20%;
  color: white;
  z-index: 9999;
}

.tokenRuleDialogContent {
  position: relative;
  border-radius: 5px;
  border: 1px solid white;
  padding: 20px 30px;
  background-color: #261176;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: flex-start;
  max-width: 500px;
  width: 70vw;
  max-height: 70vh;
  /* overflow-y: auto; */
  box-sizing: border-box;
}

.tokenRuleDialogClose {
  border-radius: 5px;
  border: 1px solid white;
  background-color: #8621d9;
  padding: 2px;
  display: flex;
  justify-content: center;
  align-items: center;
  position: absolute;
  top: 0px;
  right: 0px;
  width: 24px;
  height: 24px;
  cursor: pointer;
  color: white;
}

.tokenRuleDialogTitle {
  color: #fec13e;
  font-size: 20px;
  font-weight: bold;
  text-align: center;
  width: 100%;
}

.tokenRuleSection {
  width: 100%;
}

.tokenRuleSectionTitle {
  color: #fec13e;
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 8px;
}

.tokenRuleItem {
  color: white;
  font-size: 16px;
  line-height: 1.5;
}

.tokenRuleNote {
  background: rgba(134, 33, 217, 0.3);
  border: 1px solid #fec13e;
  border-radius: 5px;
  padding: 12px;
  color: white;
  font-size: 14px;
  line-height: 1.5;
  text-align: center;
  word-wrap: break-word;
  overflow-wrap: break-word;
}

@media (max-width: 768px) {
  .tokenRuleDialog {
    bottom: 20%;
  }

  .tokenRuleDialogContent {
    width: 80vw;
    padding: 15px 20px;
    max-height: 85vh;
  }

  .tokenRuleDialogTitle {
    font-size: 18px;
  }

  .tokenRuleSectionTitle {
    font-size: 14px;
    margin-bottom: 6px;
  }

  .tokenRuleItem {
    font-size: 13px;
    line-height: 1.4;
    word-wrap: break-word;
    overflow-wrap: break-word;
  }

  .tokenRuleNote {
    font-size: 12px;
    padding: 10px;
    line-height: 1.4;
  }

  .tokenRuleDialogClose {
    width: 20px;
    height: 20px;
  }
}

@media (max-width: 768px) {
  .logo1 {
    max-width: 110px;
    width: 25vw;
  }

  .homepage-right-group {
    gap: 10px;
  }

  .homepage-right-group .action-btn {
    height: 30px;
  }

  .count-number {
    top: 10px;
    font-size: 12px;
  }

  .backImg {
    width: 35px;
    height: auto;
  }

  .action-btn {
    height: 21px;
  }

  .footer-second-line {
    padding: 5px 10px 10px;
  }

  .msg-input {
    /* min-height: 44px; */
    /* height: 44px; */
    font-size: 16px;
  }

  /* .changeImg {
    width: 30px;
    height: 30px;
  } */

  .changeLevel {
    flex-direction: horizontal;
  }

  .changeLevelContent {
    display: flex;
    /* justify-content: center; */
  }

  .changeLevelItems {
    flex: 0 0 calc(33% - 20px);
    /* margin-right: auto; */
  }

  .changeLevelTitle {
    align-items: center;
    display: flex;
    flex-direction: column;
  }

  .changeRule {
    margin-left: 10px;
    width: 0%;
    background-color: white;
  }

  .changeMsg {
    gap: 10px 20px;
    margin-bottom: 10px;
  }

  .changeImgClass {
    width: 30px;
    height: 30px;
  }

  /* .changeContent {
    font-size: 0.5rem;
  } */

  .changeLevelItems {
    font-size: 0.7rem;
    min-width: 0px;
  }

  .changeLevelItemToken {
    white-space: nowrap;
  }

  .changeLevelItemTokenImg {
    width: 20px;
    height: 20px;
  }

  .changeInfo {
    margin: 0px auto;
  }

  .changeBtn {
    margin: 0px auto;
  }

  .rechargeDialogTitle {
    font-size: 1.3rem;
  }

  .rechargeDialogContent {
    padding: 10px 0px;
    font-size: 0.8rem;
  }

  .rechargeDialogBtnGroup {
    font-size: 1rem;
  }

  .recharge {
    padding: 5px 10px;
  }

  .rechargeDialogCancel {
    padding: 5px 10px;
  }

  .confirmDialogTitle {
    font-size: 1.3rem;
  }

  .confirmDialogContent {
    padding: 10px 0px;
    font-size: 0.8rem;
  }

  .confirmDialogBtnGroup {
    font-size: 1rem;
  }

  .confirmDialogConfirm {
    padding: 5px 10px;
  }

  .confirmDialogCancel {
    padding: 5px 10px;
  }

  .changeSuccessDialogTitle {
    font-size: 1.3rem;
  }

  .changeSuccessDialogContent {
    font-size: 1rem;
  }
}

@media (min-width: 320px) and (max-width: 375px) {
    .tokenRuleDialog {
        bottom: 10%;
    }

}
</style>

<style>
.changeSuccessDialog {
  background: linear-gradient(180deg, #80d3f8, #8080ff);
}

.changeSuccessDialogFooter {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.confirmButton {
  background: #8a52df;
  color: white;
  border: none;
  border-radius: 5px;
  padding: 8px 30px;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.confirmButton:hover {
  background: #3a75e6;
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(78, 134, 254, 0.3);
}

/* 自定义下拉选择框样式 */
.custom-select-container {
  position: relative;
  width: 100%;
  margin-bottom: 10px;
  font-size: 14px;
  user-select: none;
}

.custom-select-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px 12px;
  background: #3549b9;
  color: white;
  border-radius: 4px;
  cursor: pointer;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
  gap: 10px;
}

.dropdown-arrow {
  transition: transform 0.3s ease;
  display: flex;
}

.arrow-up {
  transform: rotate(180deg);
}

.custom-select-dropdown {
  position: absolute;
  bottom: 100%;
  left: 0;
  width: 100%;
  max-height: 200px;
  overflow-y: auto;
  background: #3549b9;
  border-radius: 4px;
  box-shadow: 0 -4px 12px rgba(0, 0, 0, 0.15);
  z-index: 100;
  margin-bottom: 4px;
  color: white;
}

.custom-select-option {
  padding: 8px 12px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.custom-select-option:hover {
  background-color: #f5f7fa;
}

.option-selected {
  background-color: #6a00ff;
  color: white;
  font-weight: 500;
}

.select-option-with-image {
  display: flex;
  align-items: center;
  gap: 10px;
}

.option-image {
  width: 24px;
  height: 24px;
  object-fit: contain;
}
</style>
