"use strict";
const common_vendor = require("../../common/vendor.js");
require("../../common/libraries/request.js");
const common_store_useWeAppAuthStore = require("../../common/store/useWeAppAuthStore.js");
require("../../common/store/useWorkStore.js");
const common_libraries_upload = require("../../common/libraries/upload.js");
require("../../gen/Apis.js");
require("../../common/libraries/setTabBar.js");
require("../../common/libraries/apiLoading.js");
if (!Array) {
  const _easycom_uni_icons2 = common_vendor.resolveComponent("uni-icons");
  _easycom_uni_icons2();
}
const _easycom_uni_icons = () => "../../uni_modules/uni-icons/components/uni-icons/uni-icons.js";
if (!Math) {
  _easycom_uni_icons();
}
const _sfc_main = /* @__PURE__ */ common_vendor.defineComponent({
  __name: "chat",
  setup(__props) {
    common_vendor.dayjs.extend(common_vendor.relativeTime);
    common_vendor.dayjs.locale("zh-cn");
    const auth = common_store_useWeAppAuthStore.useWeAppAuthStore();
    const inputMessage = common_vendor.ref("");
    const selectedImages = common_vendor.ref([]);
    const isInputFocused = common_vendor.ref(false);
    const messages = common_vendor.ref([
      {
        role: "ai",
        content: "您好！我是物业客服，有什么可以帮助您的吗？",
        quickQuestions: []
      }
    ]);
    const loading = common_vendor.ref(false);
    const loadingText = common_vendor.ref("正在输入中...");
    let socketTask = null;
    let isConnected = common_vendor.ref(false);
    const API_BASE_URL = "https://kf-api-test.linyikj.com.cn";
    const WS_BASE_URL = "wss://kf-api-test.linyikj.com.cn";
    const currentPage = common_vendor.ref(1);
    const pageSize = common_vendor.ref(10);
    const hasMore = common_vendor.ref(true);
    const isLoadingHistory = common_vendor.ref(false);
    const conversationId = common_vendor.ref("");
    const currentOffset = common_vendor.ref(0);
    const quickQuestionsData = common_vendor.ref([]);
    const lastMessageContent = common_vendor.ref("");
    const getQuickQuestions = async () => {
      try {
        const response = await common_vendor.index.request({
          url: `${API_BASE_URL}/api/public/quick-questions`,
          method: "GET"
        });
        if (response.statusCode === 200) {
          const result = response.data;
          let quickQuestions = [];
          if (result.data && Array.isArray(result.data)) {
            quickQuestions = result.data.map(
              (item) => item.question || item.title || item.text || item
            );
          } else if (result.questions && Array.isArray(result.questions)) {
            quickQuestions = result.questions.map(
              (item) => item.question || item.title || item.text || item
            );
          } else if (Array.isArray(result)) {
            quickQuestions = result.map((item) => item.question || item.title || item.text || item);
          }
          console.log("获取到开场白按钮数据:", quickQuestions);
          return quickQuestions;
        } else {
          console.error("获取开场白数据失败，状态码:", response.statusCode);
          return [];
        }
      } catch (error) {
        console.error("获取开场白数据异常:", error);
        return [];
      }
    };
    const formatMessageContent = (content) => {
      if (!content || typeof content !== "string") {
        return [""];
      }
      return content.split("\n").filter((line) => line.trim() !== "");
    };
    const previewImage = (currentImage, images) => {
      common_vendor.index.previewImage({
        current: currentImage,
        urls: images
      });
    };
    const copyMessage = (content) => {
      if (!content) {
        common_vendor.index.showToast({
          title: "暂无内容可复制",
          icon: "none"
        });
        return;
      }
      common_vendor.index.setClipboardData({
        data: content,
        success: () => {
          common_vendor.index.showToast({
            title: "复制成功",
            icon: "success"
          });
        },
        fail: () => {
          common_vendor.index.showToast({
            title: "复制失败",
            icon: "none"
          });
        }
      });
    };
    const formatTime = (timeStr) => {
      if (!timeStr)
        return "";
      try {
        const date = common_vendor.dayjs(timeStr);
        if (!date.isValid()) {
          return "";
        }
        return date.fromNow();
      } catch (e) {
        console.error("时间格式化错误:", e);
        return "";
      }
    };
    const scrollToBottom = () => {
      common_vendor.nextTick$1(() => {
        common_vendor.index.pageScrollTo({
          scrollTop: 999999,
          duration: 300
        });
      });
    };
    const getHistoryMessages = async (page = 1) => {
      var _a, _b;
      const userPhone = (_b = (_a = auth.data) == null ? void 0 : _a.user) == null ? void 0 : _b.phone;
      if (!userPhone) {
        console.log("用户未登录，无法获取历史记录");
        return;
      }
      if (isLoadingHistory.value) {
        return;
      }
      try {
        isLoadingHistory.value = true;
        const offset = (page - 1) * pageSize.value;
        currentOffset.value = offset;
        console.log("分页信息 - 页码:", page, "每页数量:", pageSize.value, "计算出的offset:", offset);
        const response = await common_vendor.index.request({
          url: `${API_BASE_URL}/api/public/customer/init`,
          method: "POST",
          data: {
            platform: "property",
            platform_user_id: userPhone,
            //userPhone
            limit: pageSize.value,
            offset
          }
        });
        if (response.statusCode === 200) {
          const result = response.data;
          let historyMessages = [];
          if (result.conversation && result.conversation.id) {
            conversationId.value = result.conversation.id;
            console.log("获取到会话ID:", conversationId.value);
          } else if (result.conversation_id) {
            conversationId.value = result.conversation_id;
            console.log("获取到会话ID:", conversationId.value);
          } else if (result.conversations && result.conversations.id) {
            conversationId.value = result.conversations.id;
            console.log("获取到会话ID:", conversationId.value);
          }
          if (result.messages && Array.isArray(result.messages)) {
            historyMessages = result.messages.map((item) => {
              const message = {
                role: item.sender_type === "customer" ? "user" : "ai",
                content: item.message || item.content || "",
                created_at: item.created_at || item.timestamp || new Date().toISOString()
              };
              if (item.message_type) {
                message.message_type = item.message_type;
              }
              let imageUrlData = null;
              if (item.image_url && Array.isArray(item.image_url)) {
                imageUrlData = item.image_url;
              } else if (item.images && Array.isArray(item.images)) {
                imageUrlData = item.images;
              } else if (item.metadata && item.metadata.image_url && Array.isArray(item.metadata.image_url)) {
                imageUrlData = item.metadata.image_url;
              }
              if (imageUrlData) {
                message.image_url = imageUrlData;
                message.images = imageUrlData;
              }
              if (item.metadata) {
                message.metadata = item.metadata;
              }
              return message;
            });
            console.log("从messages字段获取到历史记录:", historyMessages.length);
          } else if (result.data && Array.isArray(result.data)) {
            historyMessages = result.data.map((item) => {
              const message = {
                role: item.sender_type === "customer" ? "user" : "ai",
                content: item.message || item.content || "",
                created_at: item.created_at || item.timestamp || new Date().toISOString()
              };
              if (item.message_type) {
                message.message_type = item.message_type;
              }
              let imageUrlData = null;
              if (item.image_url && Array.isArray(item.image_url)) {
                imageUrlData = item.image_url;
              } else if (item.images && Array.isArray(item.images)) {
                imageUrlData = item.images;
              } else if (item.metadata && item.metadata.image_url && Array.isArray(item.metadata.image_url)) {
                imageUrlData = item.metadata.image_url;
              }
              if (imageUrlData) {
                message.image_url = imageUrlData;
                message.images = imageUrlData;
              }
              if (item.metadata) {
                message.metadata = item.metadata;
              }
              return message;
            });
            console.log("从data字段获取到历史记录:", historyMessages.length);
          } else if (result.list && Array.isArray(result.list)) {
            historyMessages = result.list.map((item) => {
              const message = {
                role: item.sender_type === "customer" ? "user" : "ai",
                content: item.message || item.content || "",
                created_at: item.created_at || item.timestamp || new Date().toISOString()
              };
              if (item.message_type) {
                message.message_type = item.message_type;
              }
              let imageUrlData = null;
              if (item.image_url && Array.isArray(item.image_url)) {
                imageUrlData = item.image_url;
              } else if (item.images && Array.isArray(item.images)) {
                imageUrlData = item.images;
              } else if (item.metadata && item.metadata.image_url && Array.isArray(item.metadata.image_url)) {
                imageUrlData = item.metadata.image_url;
              }
              if (imageUrlData) {
                message.image_url = imageUrlData;
                message.images = imageUrlData;
              }
              if (item.metadata) {
                message.metadata = item.metadata;
              }
              return message;
            });
            console.log("从list字段获取到历史记录:", historyMessages.length);
          }
          if (page === 1) {
            if (historyMessages.length > 0) {
              messages.value = historyMessages;
              console.log("第一页历史记录已加载，总共", historyMessages.length, "条消息");
            } else {
              console.log("没有历史记录");
              messages.value = [];
            }
            const isFirstPageLastPage = !hasMore.value;
            if (checkShouldShowQuickQuestions(isFirstPageLastPage)) {
              addQuickQuestionsToFirstAIMessage(isFirstPageLastPage);
            }
          } else {
            if (historyMessages.length > 0) {
              setTimeout(() => {
                messages.value.unshift(...historyMessages);
                console.log(
                  "加载更多历史记录，新增",
                  historyMessages.length,
                  "条消息，总共",
                  messages.value.length,
                  "条"
                );
              }, 300);
            }
          }
          const totalItems = result.total || result.count || result.total_count || 0;
          hasMore.value = totalItems > messages.value.length;
          currentPage.value = page;
          if (page > 1 && !hasMore.value) {
            console.log("分页加载完成，当前页:", page, "hasMore:", hasMore.value, "展示开场白");
            setTimeout(() => {
              addQuickQuestionsToFirstAIMessage(true);
            }, 500);
          }
          console.log(
            "第",
            page,
            "页数据加载完成，offset:",
            offset,
            ", limit:",
            pageSize.value,
            ", 总数据:",
            totalItems,
            ", 当前已加载:",
            messages.value.length,
            ", 是否有更多:",
            hasMore.value
          );
          if (page === 1) {
            setTimeout(() => {
              scrollToBottom();
            }, 100);
            console.log("[Customer] 历史记录加载完成，开始建立WebSocket连接");
            initWebSocket();
          }
        } else {
          console.error("获取历史记录失败，状态码:", response.statusCode);
        }
      } catch (error) {
        console.error("获取历史记录异常:", error);
      } finally {
        isLoadingHistory.value = false;
      }
    };
    common_vendor.onPullDownRefresh(async () => {
      if (isLoadingHistory.value || !hasMore.value) {
        console.log("正在加载或没有更多数据");
        common_vendor.index.stopPullDownRefresh();
        return;
      }
      console.log("触发下拉分页，加载更多历史记录");
      const nextPage = currentPage.value + 1;
      try {
        await getHistoryMessages(nextPage);
        await new Promise((resolve) => setTimeout(resolve, 500));
      } catch (error) {
        console.error("加载历史记录失败:", error);
      } finally {
        common_vendor.index.stopPullDownRefresh();
      }
    });
    const initWebSocket = () => {
      if (socketTask) {
        return;
      }
      try {
        const wsUrl = `${WS_BASE_URL}/ws/socket.io/?EIO=4&transport=websocket`;
        console.log("正在建立Socket.IO连接");
        console.log("连接URL:", wsUrl);
        socketTask = common_vendor.index.connectSocket({
          url: wsUrl,
          header: {
            "content-type": "application/json"
          }
        });
        common_vendor.index.onSocketOpen((res) => {
          console.log("[Customer] WebSocket connected", res);
          isConnected.value = true;
          const connectPacket = '40/customer,{"jwt":""}';
          common_vendor.index.sendSocketMessage({
            data: connectPacket,
            success: () => {
              console.log("[Customer] Socket.IO连接包发送成功");
              if (conversationId.value) {
                setTimeout(() => {
                  const joinMessage = `42/customer,["join_conversation",{"conversation_id":"${conversationId.value}"}]`;
                  console.log("[Customer] 加入会话房间:", joinMessage);
                  common_vendor.index.sendSocketMessage({
                    data: joinMessage,
                    success: () => {
                      console.log("[Customer] 成功加入会话房间");
                    },
                    fail: (error) => {
                      console.error("[Customer] 加入会话房间失败:", error);
                    }
                  });
                }, 200);
              }
            },
            fail: (error) => {
              console.error("[Customer] Socket.IO连接包发送失败:", error);
            }
          });
        });
        common_vendor.index.onSocketError((error) => {
          console.error("[Customer] WebSocket error:", error);
          isConnected.value = false;
          socketTask = null;
        });
        common_vendor.index.onSocketClose((res) => {
          console.log("[Customer] WebSocket disconnected", res);
          isConnected.value = false;
          socketTask = null;
        });
        common_vendor.index.onSocketMessage((res) => {
          console.log("收到WebSocket原始消息:", res);
          console.log("消息数据类型:", typeof res.data);
          console.log("消息内容:", res.data);
          const data = res.data;
          if (typeof data === "string") {
            if (data.startsWith("42/customer,")) {
              const payload = data.substring("42/customer,".length);
              try {
                const parsedData = JSON.parse(payload);
                console.log("解析Socket.IO事件:", parsedData);
                handleSocketEvent(parsedData);
              } catch (e) {
                console.error("解析Socket.IO数据失败:", e, "原始数据:", payload);
              }
            } else if (data.startsWith("40/customer")) {
              console.log("Socket.IO连接确认");
            } else if (data.startsWith("2")) {
              common_vendor.index.sendSocketMessage({
                data: "3"
              });
            } else if (data.startsWith("0")) {
              console.log("Socket.IO握手成功");
            } else {
              try {
                const jsonData = JSON.parse(data);
                console.log("解析JSON消息:", jsonData);
                handleJsonMessage(jsonData);
              } catch (e) {
                console.log("非JSON格式的字符串消息:", data);
              }
            }
          } else if (typeof data === "object") {
            console.log("收到对象类型消息:", data);
            handleObjectMessage(data);
          } else {
            console.log("收到其他类型消息，类型:", typeof data);
          }
        });
      } catch (error) {
        console.error("初始化Socket.IO异常:", error);
        isConnected.value = false;
        socketTask = null;
      }
    };
    const handleSocketEvent = (parsedData) => {
      if (Array.isArray(parsedData) && parsedData.length >= 2) {
        const eventType = parsedData[0];
        const eventData = parsedData[1];
        console.log("[Customer] Socket.IO事件类型:", eventType, "事件数据:", eventData);
        if (eventType === "new_message") {
          processMessage(eventData);
        } else if (eventType === "join_conversation_response") {
          console.log("[Customer] Joined room:", eventData);
        } else if (eventType === "message") {
          processMessage(eventData);
        } else if (eventType === "typing") {
          processTypingIndicator(eventData);
        } else {
          console.log("[Customer] 未处理的Socket.IO事件类型:", eventType);
        }
      }
    };
    const handleJsonMessage = (jsonData) => {
      console.log("[Customer] 处理JSON消息:", jsonData);
      if (jsonData.type === "message" || jsonData.event === "new_message") {
        processMessage(jsonData.data || jsonData);
      } else if (jsonData.type === "typing" || jsonData.event === "typing") {
        processTypingIndicator(jsonData.data || jsonData);
      } else if (jsonData.message || jsonData.content) {
        processMessage(jsonData);
      } else {
        console.log("[Customer] 未识别的JSON消息结构:", jsonData);
      }
    };
    const handleObjectMessage = (objData) => {
      console.log("[Customer] 处理对象消息:", objData);
      if (objData.message || objData.content || objData.text) {
        processMessage(objData);
      } else if (objData.is_typing !== void 0) {
        processTypingIndicator(objData);
      } else {
        console.log("[Customer] 未识别的对象消息结构:", objData);
      }
    };
    const processTypingIndicator = (typingData) => {
      console.log("[Customer] 处理typing指示器:", typingData);
      if (typingData.is_typing && typingData.user_type === "staff") {
        loading.value = true;
        loadingText.value = "客服正在输入...";
      } else {
        loading.value = false;
      }
    };
    const checkShouldShowQuickQuestions = (isLastPage = false) => {
      if (quickQuestionsData.value.length === 0) {
        return false;
      }
      if (messages.value.length === 0) {
        return true;
      }
      if (isLastPage && messages.value.length > 0) {
        return true;
      }
      return false;
    };
    const addQuickQuestionsToFirstAIMessage = (isLastPage = false) => {
      if (quickQuestionsData.value.length === 0) {
        return;
      }
      if (!checkShouldShowQuickQuestions(isLastPage)) {
        return;
      }
      const existingWelcomeMessage = messages.value.find(
        (msg) => msg.role === "ai" && msg.quickQuestions && msg.quickQuestions.length > 0
      );
      if (existingWelcomeMessage) {
        console.log("[Customer] 开场白已存在，跳过添加");
        return;
      }
      const welcomeMessage = {
        role: "ai",
        content: "您好！我是物业客服，有什么可以帮助您的吗？",
        quickQuestions: quickQuestionsData.value,
        created_at: new Date().toISOString()
      };
      console.log("[Customer] 创建开场白消息，是否最后一页:", isLastPage);
      if (messages.value.length === 0) {
        messages.value = [welcomeMessage];
        console.log("[Customer] 设置开场白为第一条消息");
      } else if (isLastPage) {
        messages.value.unshift(welcomeMessage);
        console.log("[Customer] 已加载到最后一页，在第一条消息前面插入开场白");
      }
    };
    const processMessage = (messageData) => {
      console.log("[Customer] 处理消息数据:", messageData);
      if (messageData.sender_type === "customer" || messageData.role === "user") {
        console.log("[Customer] 过滤掉客户消息");
        return;
      }
      let messageContent = "";
      if (typeof messageData === "string") {
        messageContent = messageData;
      } else {
        messageContent = messageData.message || messageData.content || messageData.text || messageData.body || "收到回复";
      }
      if (typeof messageContent === "string") {
        messageContent = messageContent.replace(/↵/g, "\n").replace(/\\n/g, "\n");
      }
      console.log("[Customer] 收到新消息内容:", messageContent);
      if (messageContent === lastMessageContent.value) {
        console.log("[Customer] 消息与HTTP返回的消息相同，跳过显示");
        lastMessageContent.value = "";
        return;
      }
      loading.value = false;
      const newMessage = {
        role: "ai",
        content: messageContent,
        created_at: messageData.created_at || messageData.timestamp || messageData.time || new Date().toISOString()
      };
      if (messageData.suggested_questions && Array.isArray(messageData.suggested_questions) && messageData.suggested_questions.length > 0) {
        newMessage.quickQuestions = messageData.suggested_questions;
      } else if (messageData.quickQuestions && Array.isArray(messageData.quickQuestions) && messageData.quickQuestions.length > 0) {
        newMessage.quickQuestions = messageData.quickQuestions;
      }
      if (messageData.need_confirmation !== void 0) {
        newMessage.needConfirmation = messageData.need_confirmation;
      }
      if (messageData.confirmation_type !== void 0) {
        newMessage.confirmationType = messageData.confirmation_type;
      }
      messages.value.push(newMessage);
      scrollToBottom();
    };
    const handleQuickQuestion = (question) => {
      inputMessage.value = question;
      handleSendMessage();
    };
    const handleConfirmation = (message, confirmation) => {
      if (message.selectedConfirmation !== void 0) {
        return;
      }
      message.selectedConfirmation = confirmation;
      setTimeout(() => {
        inputMessage.value = confirmation;
        handleSendMessage();
      }, 300);
    };
    const chooseImage = async () => {
      const maxImages = 9;
      if (selectedImages.value.length >= maxImages) {
        common_vendor.index.showToast({
          title: "最多选择9张图片",
          icon: "none"
        });
        return;
      }
      try {
        const remainingCount = maxImages - selectedImages.value.length;
        const uploadResult = await common_libraries_upload.upload(remainingCount, 2, ["image"]);
        if (uploadResult && Array.isArray(uploadResult) && uploadResult.length > 0) {
          const imageUrls = uploadResult.map((item) => item.url);
          selectedImages.value.push(...imageUrls);
          common_vendor.index.showToast({
            title: "图片上传成功",
            icon: "success"
          });
        }
      } catch (error) {
        console.error("选择图片失败:", error);
        common_vendor.index.showToast({
          title: "选择图片失败",
          icon: "none"
        });
      }
    };
    const removeImage = (index) => {
      selectedImages.value.splice(index, 1);
    };
    const handleSendMessage = async () => {
      var _a, _b, _c, _d, _e, _f;
      const message = inputMessage.value.trim();
      const hasImages = selectedImages.value.length > 0;
      if (!message && !hasImages || loading.value)
        return;
      const userPhone = (_b = (_a = auth.data) == null ? void 0 : _a.user) == null ? void 0 : _b.phone;
      const projectId = (_d = (_c = auth.data) == null ? void 0 : _c.selected_house) == null ? void 0 : _d.asset_projects_id;
      const projectName = (_f = (_e = auth.data) == null ? void 0 : _e.selected_house) == null ? void 0 : _f.full_name;
      if (!userPhone || !projectId) {
        common_vendor.index.showToast({
          title: "请先登录并绑定房屋",
          icon: "none"
        });
        return;
      }
      if (!isConnected.value) {
        initWebSocket();
        await new Promise((resolve) => setTimeout(resolve, 1e3));
      }
      const uploadedImages = selectedImages.value;
      let messageType = "text";
      if (hasImages && message) {
        messageType = "mixed";
      } else if (hasImages && !message) {
        messageType = "image";
      }
      const userMessage = {
        role: "user",
        content: message || "",
        // 纯图片时传空字符串
        created_at: new Date().toISOString(),
        message_type: messageType,
        image_url: uploadedImages.length > 0 ? uploadedImages : void 0,
        images: uploadedImages.length > 0 ? uploadedImages : void 0
      };
      messages.value.push(userMessage);
      inputMessage.value = "";
      selectedImages.value = [];
      scrollToBottom();
      if (message && message.includes("查询")) {
        loadingText.value = "正在查询中请稍后...";
      } else {
        loadingText.value = "正在输入中...";
      }
      loading.value = true;
      try {
        const response = await common_vendor.index.request({
          url: `${API_BASE_URL}/api/public/chat`,
          method: "POST",
          data: {
            platform: "property",
            message: message || "",
            // 纯图片时传空字符串
            tenant_project_id: projectId,
            tenant_project_name: projectName || "",
            platform_user_id: userPhone,
            conversation_id: conversationId.value,
            message_type: messageType,
            image_url: uploadedImages.length > 0 ? uploadedImages : void 0
          },
          header: {
            "Content-Type": "application/json"
          }
        });
        if (response.statusCode === 200) {
          const result = response.data;
          console.log("[Customer] HTTP接口响应数据:", result);
          let httpReplyMessage = null;
          let suggestedQuestions = [];
          let needConfirmation = false;
          let confirmationType = null;
          if (result.reply && typeof result.reply === "string") {
            httpReplyMessage = result.reply;
            suggestedQuestions = result.suggested_questions || [];
            needConfirmation = result.need_confirmation || false;
            confirmationType = result.confirmation_type || null;
          } else if (result.reply && result.reply.message) {
            httpReplyMessage = result.reply.message;
            suggestedQuestions = result.reply.suggested_questions || result.suggested_questions || [];
            needConfirmation = result.reply.need_confirmation || result.need_confirmation || false;
            confirmationType = result.reply.confirmation_type || result.confirmation_type || null;
          } else if (result.reply && result.reply.content) {
            httpReplyMessage = result.reply.content;
            suggestedQuestions = result.reply.suggested_questions || result.suggested_questions || [];
            needConfirmation = result.reply.need_confirmation || result.need_confirmation || false;
            confirmationType = result.reply.confirmation_type || result.confirmation_type || null;
          } else if (result.message) {
            httpReplyMessage = result.message;
            suggestedQuestions = result.suggested_questions || [];
            needConfirmation = result.need_confirmation || false;
            confirmationType = result.confirmation_type || null;
          } else if (result.content) {
            httpReplyMessage = result.content;
            suggestedQuestions = result.suggested_questions || [];
            needConfirmation = result.need_confirmation || false;
            confirmationType = result.confirmation_type || null;
          } else if (result.answer) {
            httpReplyMessage = result.answer;
            suggestedQuestions = result.suggested_questions || [];
            needConfirmation = result.need_confirmation || false;
            confirmationType = result.confirmation_type || null;
          } else if (result.response) {
            httpReplyMessage = result.response;
            suggestedQuestions = result.suggested_questions || [];
            needConfirmation = result.need_confirmation || false;
            confirmationType = result.confirmation_type || null;
          } else if (typeof result === "string") {
            httpReplyMessage = result;
          }
          if (httpReplyMessage) {
            console.log("[Customer] HTTP接口返回回答消息:", httpReplyMessage);
            console.log("[Customer] 建议问题:", suggestedQuestions);
            console.log("[Customer] 需要确认:", needConfirmation, "确认类型:", confirmationType);
            let formattedMessage = httpReplyMessage;
            if (typeof formattedMessage === "string") {
              formattedMessage = formattedMessage.replace(/↵/g, "\n").replace(/\\n/g, "\n");
            }
            lastMessageContent.value = formattedMessage;
            loading.value = false;
            messages.value.push({
              role: "ai",
              content: formattedMessage,
              created_at: new Date().toISOString(),
              quickQuestions: suggestedQuestions.length > 0 ? suggestedQuestions : void 0,
              needConfirmation,
              confirmationType
            });
            scrollToBottom();
          } else {
            console.log("[Customer] 消息发送成功，等待WebSocket回复");
          }
        } else {
          throw new Error("请求失败");
        }
      } catch (error) {
        console.error("发送消息失败:", error);
        common_vendor.index.showToast({
          title: "发送失败，请稍后重试",
          icon: "none"
        });
        messages.value.push({
          role: "ai",
          content: "抱歉，网络连接出现问题，请稍后再试。"
        });
        loading.value = false;
        scrollToBottom();
      }
    };
    common_vendor.onUnmounted(() => {
      if (socketTask || isConnected.value) {
        common_vendor.index.closeSocket();
        socketTask = null;
        isConnected.value = false;
        console.log("页面卸载，WebSocket连接已关闭");
      }
    });
    common_vendor.onLoad(async () => {
      quickQuestionsData.value = await getQuickQuestions();
      console.log("页面加载时已获取开场白按钮数据:", quickQuestionsData.value.length);
      getHistoryMessages(1);
    });
    return (_ctx, _cache) => {
      return common_vendor.e({
        a: common_vendor.f(messages.value, (message, index, i0) => {
          return common_vendor.e({
            a: message.role === "ai"
          }, message.role === "ai" ? {} : {}, {
            b: message.image_url && message.image_url.length > 0
          }, message.image_url && message.image_url.length > 0 ? {
            c: common_vendor.f(message.image_url, (image, imgIndex, i1) => {
              return {
                a: image,
                b: common_vendor.o(($event) => previewImage(image, message.image_url), imgIndex),
                c: imgIndex
              };
            }),
            d: message.image_url.length === 1 ? "widthFix" : "aspectFill",
            e: message.image_url.length === 1 ? 1 : ""
          } : message.images && message.images.length > 0 ? {
            g: common_vendor.f(message.images, (image, imgIndex, i1) => {
              return {
                a: image,
                b: common_vendor.o(($event) => previewImage(image, message.images), imgIndex),
                c: imgIndex
              };
            }),
            h: message.images.length === 1 ? "widthFix" : "aspectFill",
            i: message.images.length === 1 ? 1 : ""
          } : message.metadata && message.metadata.image_url && message.metadata.image_url.length > 0 ? {
            k: common_vendor.f(message.metadata.image_url, (image, imgIndex, i1) => {
              return {
                a: image,
                b: common_vendor.o(($event) => previewImage(image, message.metadata.image_url), imgIndex),
                c: imgIndex
              };
            }),
            l: message.metadata.image_url.length === 1 ? "widthFix" : "aspectFill",
            m: message.metadata.image_url.length === 1 ? 1 : ""
          } : {}, {
            f: message.images && message.images.length > 0,
            j: message.metadata && message.metadata.image_url && message.metadata.image_url.length > 0,
            n: message.content && message.content.trim()
          }, message.content && message.content.trim() ? {
            o: common_vendor.f(formatMessageContent(message.content), (line, lineIndex, i1) => {
              return {
                a: common_vendor.t(line),
                b: "text-" + lineIndex
              };
            })
          } : {}, {
            p: message.quickQuestions && message.quickQuestions.length > 0
          }, message.quickQuestions && message.quickQuestions.length > 0 ? {
            q: common_vendor.f(message.quickQuestions, (question, qIndex, i1) => {
              return {
                a: common_vendor.t(question),
                b: qIndex,
                c: common_vendor.o(($event) => handleQuickQuestion(question), qIndex)
              };
            })
          } : {}, {
            r: message.needConfirmation
          }, message.needConfirmation ? {
            s: message.selectedConfirmation === "是" ? 1 : "",
            t: message.selectedConfirmation !== void 0 ? 1 : "",
            v: common_vendor.o(($event) => handleConfirmation(message, "是"), index),
            w: message.selectedConfirmation === "否" ? 1 : "",
            x: message.selectedConfirmation !== void 0 ? 1 : "",
            y: common_vendor.o(($event) => handleConfirmation(message, "否"), index)
          } : {}, {
            z: message.created_at && !message.quickQuestions
          }, message.created_at && !message.quickQuestions ? common_vendor.e({
            A: message.role === "ai"
          }, message.role === "ai" ? {
            B: common_vendor.o(($event) => copyMessage(message.content), index)
          } : {}, {
            C: common_vendor.t(formatTime(message.created_at)),
            D: message.role === "user"
          }, message.role === "user" ? {
            E: common_vendor.o(($event) => copyMessage(message.content), index)
          } : {}) : {}, {
            F: index,
            G: `msg-${index}`,
            H: common_vendor.n(message.role === "user" ? "user-message" : "ai-message")
          });
        }),
        b: loading.value
      }, loading.value ? {
        c: common_vendor.t(loadingText.value)
      } : {}, {
        d: selectedImages.value.length > 0
      }, selectedImages.value.length > 0 ? common_vendor.e({
        e: common_vendor.f(selectedImages.value, (image, index, i0) => {
          return {
            a: image,
            b: "b15798f7-0-" + i0,
            c: common_vendor.o(($event) => removeImage(index), index),
            d: index
          };
        }),
        f: common_vendor.p({
          type: "closeempty",
          size: "14",
          color: "#fff"
        }),
        g: selectedImages.value.length < 9
      }, selectedImages.value.length < 9 ? {
        h: common_vendor.p({
          type: "plus",
          size: "30",
          color: "#999"
        }),
        i: common_vendor.o(chooseImage)
      } : {}) : {}, {
        j: common_vendor.o(($event) => isInputFocused.value = true),
        k: common_vendor.o(($event) => isInputFocused.value = false),
        l: common_vendor.o(handleSendMessage),
        m: inputMessage.value,
        n: common_vendor.o(($event) => inputMessage.value = $event.detail.value),
        o: !inputMessage.value.trim() && !isInputFocused.value && selectedImages.value.length === 0
      }, !inputMessage.value.trim() && !isInputFocused.value && selectedImages.value.length === 0 ? {
        p: common_vendor.p({
          type: "camera",
          size: "24",
          color: "#666"
        }),
        q: common_vendor.o(chooseImage)
      } : {}, {
        r: (inputMessage.value.trim() || isInputFocused.value || selectedImages.value.length > 0) && !loading.value
      }, (inputMessage.value.trim() || isInputFocused.value || selectedImages.value.length > 0) && !loading.value ? {
        s: common_vendor.p({
          type: "paperplane-filled",
          size: "20",
          color: "#fff"
        }),
        t: common_vendor.o(handleSendMessage)
      } : {}, {
        v: loading.value
      }, loading.value ? {
        w: common_vendor.p({
          type: "spinner-cycle",
          size: "20",
          color: "#ccc"
        })
      } : {});
    };
  }
});
const MiniProgramPage = /* @__PURE__ */ common_vendor._export_sfc(_sfc_main, [["__scopeId", "data-v-b15798f7"], ["__file", "/Users/zsq/Sources/github/2025property-pay/pay-customer/src/pages/ai/chat.vue"]]);
wx.createPage(MiniProgramPage);
