<template>
  <view class="page chat-box" id="chatBox">
    <nav-bar>
      <view class="nav-title-wrapper">{{ title }}</view>
    </nav-bar>
    
    <view class="lang-wrap">
      <view class="lang-btn" @click="showLangDrop = !showLangDrop">
        {{ langList.find(item => item.value === currentLang)?.label }} ▾
      </view>
    
      <view v-if="showLangDrop" class="lang-drop-panel">
        <view 
          v-for="item in langList" 
          :key="item.value"
          class="lang-drop-item"
          :class="{ active: item.value === currentLang }"
          @click="selectLang(item.value)"
        >
          {{ item.label }}
        </view>
      </view>
    
      <view v-if="showLangDrop" class="lang-mask" @click="showLangDrop = false"></view>
    </view>
    <view class="chat-main-box" :style="{ height: chatMainHeight + 'px' }">
      <view class="chat-message" @click="switchChatTabBox('none')">
        <view v-if="showAutoQuestionTip" class="guess-question-box">
          <!-- <view class="guess-title">{{ $t('chat.guessWantAsk') }}</view> -->
          <view class="guess-list">
            <view
              class="guess-item"
              v-for="(q, i) in commonQuestions"
              :key="i"
              @click="sendQuestionMessage(q)"
            >
              <text class="item-bullet">*</text>
              <text class="item-text">{{ q }}</text>
            </view>
          </view>
        </view>
        <scroll-view
          class="scroll-box"
          scroll-y="true"
          upper-threshold="200"
          @scrolltoupper="onScrollToTop"
          @scroll="onScroll"
          :scroll-into-view="'chat-item-' + scrollMsgIdx"
          :scroll-top="scrollTop"
        >
          <view v-if="chat" class="chat-wrap">
            <view v-for="(msgInfo, idx) in chat.messages" :key="idx">
              <chat-message-item
                :ref="'message' + msgInfo.id"
                v-if="idx >= showMinIdx"
                :headImage="headImage(msgInfo)"
                @call="onRtCall(msgInfo)"
                :showName="showName(msgInfo)"
                @resend="onResendMessage"
                @recall="onRecallMessage"
                @delete="onDeleteMessage"
                @copy="onCopyMessage"
                @longPressHead="onLongPressHead(msgInfo)"
                @download="onDownloadFile"
                @audioStateChange="onAudioStateChange"
                :id="'chat-item-' + idx"
                :msgInfo="msgInfo"
                :groupMembers="groupMembers"
              >
              </chat-message-item>
            </view>
          </view>
        </scroll-view>
        <view
          v-if="!isInBottom"
          class="scroll-to-bottom"
          @click="onClickToBottom"
        >
          {{ newMessageSize > 0 ? $t('chat.newMessages', { count: newMessageSize }) : "⬇️" }}
        </view>
      </view>
      <view
        v-if="atUserIds.length > 0"
        class="chat-at-bar"
        @click="openAtBox()"
      >
        <view class="iconfont icon-at">&nbsp;</view>
        <scroll-view
          v-if="atUserIds.length > 0"
          class="chat-at-scroll-box"
          scroll-x="true"
          scroll-left="120"
        >
          <view class="chat-at-items">
            <view v-for="m in atUserItems" class="chat-at-item" :key="m.userId">
              <head-image
                :name="m.showNickName"
                :url="m.headImage"
                size="minier"
              ></head-image>
            </view>
          </view>
        </scroll-view>
      </view>
      <view class="send-bar">
        <view class="send-text">
          <editor
            id="editor"
            class="send-text-area"
            :placeholder="isReceipt ? $t('chat.receiptMessage') : $t('chat.inputPlaceholder')"
            :read-only="isReadOnly"
            @focus="onEditorFocus"
            @blur="onEditorBlur"
            @ready="onEditorReady"
            @input="onTextInput"
          >
          </editor>
        </view>
        <view
          v-if="chat && chat.type == 'GROUP'"
          class="iconfont icon-at"
          @click="openAtBox()"
        ></view>
        <view
          class="iconfont icon-icon_emoji"
          @click="onShowEmoChatTab()"
        ></view>
        <view
          v-if="isEmpty"
          class="iconfont icon-add"
          @click="onShowToolsChatTab()"
        >
        </view>
        <button
          v-if="!isEmpty || atUserIds.length"
          class="btn-send"
          type="primary"
          @click="sendTextMessage()"
          size="mini"
        >
          {{ $t('chat.send') }}
        </button>
      </view>
    </view>
    <view class="chat-tab-bar">
      <scroll-view
        v-if="chatTabBox == 'tools'"
        class="chat-tools"
        :style="{ height: keyboardHeight + 'px' }"
      >
        <view class="chat-tools-list">
          <view class="chat-tools-item" v-if="isFileOpen">
            <file-upload
              ref="fileUpload"
              :onBefore="onUploadFileBefore"
              :onSuccess="onUploadFileSuccess"
              :onError="onUploadFileFail"
            >
              <view class="tool-icon iconfont icon-folder"></view>
            </file-upload>
            <view class="tool-name">{{ $t('chat.file') }}</view>
          </view>
          <view class="chat-tools-item">
            <image-upload
              :maxCount="9"
              sourceType="album"
              :onBefore="onUploadImageBefore"
              :onSuccess="onUploadImageSuccess"
              :onError="onUploadImageFail"
            >
              <view class="tool-icon iconfont icon-picture"></view>
            </image-upload>
            <view class="tool-name">{{ $t('chat.album') }}</view>
          </view>
          <view class="chat-tools-item">
            <image-upload
              sourceType="camera"
              :onBefore="onUploadImageBefore"
              :onSuccess="onUploadImageSuccess"
              :onError="onUploadImageFail"
            >
              <view class="tool-icon iconfont icon-camera"></view>
            </image-upload>
            <view class="tool-name">{{ $t('chat.camera') }}</view>
          </view>
        </view>
      </scroll-view>
      <scroll-view
        v-if="chatTabBox === 'emo'"
        class="chat-emotion"
        scroll-y="true"
        :style="{ height: keyboardHeight + 'px' }"
      >
        <view class="emotion-item-list">
          <image
            class="emotion-item emoji-large"
            :title="emoText"
            :src="$emo.textToPath(emoText)"
            v-for="(emoText, i) in $emo.emoTextList"
            :key="i"
            @click="selectEmoji(emoText)"
            mode="aspectFit"
            lazy-load="true"
          ></image>
        </view>
      </scroll-view>
    </view>
    <!-- @用户时选择成员 -->
    <chat-at-box
      ref="atBox"
      :ownerId="group.ownerId"
      :members="groupMembers"
      @complete="onAtComplete"
    ></chat-at-box>
    <!-- 群语音通话时选择成员 -->
    <!-- #ifndef MP-WEIXIN -->
    <group-member-selector
      ref="selBox"
      :members="groupMembers"
      :maxSize="configStore.webrtc.maxChannel"
      @complete="onInviteOk"
    ></group-member-selector>
    <group-rtc-join ref="rtcJoin" :groupId="group.id"></group-rtc-join>
    <!-- #endif -->
  </view>
</template>

<script>
import UNI_APP from "@/.env.js";
import useFriendStore from "@/store/friendStore.js";
import useUserStore from "@/store/userStore.js";
import useChatStore from "@/store/chatStore.js";
import useGroupStore from "@/store/groupStore.js";
export default {
  data() {
    return {
      userInfo: {},
      group: {},
			showLangDrop: false,
      groupMembers: [],
      showAutoQuestionTip: true,
      commonQuestions: [], // 空数组，接口获取
      autoReplyList: [], // 存储完整回复列表
      isReceipt: false,
      scrollMsgIdx: 0,
      chatTabBox: "none",
      currentTargetId: null,
      currentChatType: "PRIVATE",
      _activeChatIdx: 0,
      showRecord: false,
      chatMainHeight: 800,
      keyboardHeight: 290,
      screenHeight: 1000,
      windowHeight: 1000,
      initHeight: 1000,
      atUserIds: [],
      showMinIdx: 0,
      reqQueue: [],
      isSending: false,
      isShowKeyBoard: false,
      editorCtx: null,
      isEmpty: true,
      isFocus: false,
      isReadOnly: false,
      playingAudio: null,
      isInBottom: true,
      newMessageSize: 0,
      scrollTop: 0,
      scrollViewHeight: 0,
      maxTmpId: 0,
      isFileOpen: false,
      isPasting: false,
      hasPasteListener: false,
			showLangModal: false, // 新增
			currentLang: uni.getStorageSync("app_language") || "zh",
			langList: [
			  { label: "中文", value: "zh" },
			  { label: "English", value: "en" },
			  { label: "日本語", value: "jp" },
			  { label: "한국어", value: "kor" },
			  { label: "Tiếng Việt", value: "vie" }, // 越南语
			  { label: "Русский", value: "ru" }, // 俄语
			  { label: "Deutsch", value: "de" }, // 德语
			  { label: "Français", value: "fra" }, // 法语
			  { label: "Português", value: "pt" }, // 葡萄牙语
			  { label: "العربية", value: "ara" }, // 阿拉伯语
			],
    };
  },
  methods: {
		// 刷新页面自动合并旧客服消息到当前客服
		autoMergeOldCustomerOnRefresh() {
		  try {
		    const userStore = useUserStore();
		    const chatStore = useChatStore();
		
		    if (!this.isPrivate || !userStore.userInfo?.id) return;
		
		    const currentKfId = this.currentTargetId;
		    if (!currentKfId) return;
		
		
		    // 合并缓存（核心，已经成功）
		    chatStore.forceMergeAllOldCustomerToNew(currentKfId);
		
		    // 刷新视图
		    setTimeout(() => {
		      this.reloadChatMessages(currentKfId);
		    }, 300);
		  } catch (e) {
		    console.log("自动合并失败", e);
		  }
		},
		reloadChatMessages(targetId) {
		  try {
		    const chat = this.chatStore.chats.find(
		      (c) => c.targetId == targetId && c.type === "PRIVATE"
		    );
		    if (chat) {
		      // 只刷新视图，不请求后端，彻底避免500
		      this.$forceUpdate();
		      this.$nextTick(() => {
		        this.scrollToBottom();
		      });
		    }
		  } catch (e) {}
		},
		// 下拉选择语言（必刷新）
		selectLang(lang) {
		  this.currentLang = lang;
		  this.showLangDrop = false;
		
		  // 保存到后端
		  this.$http({
		    url: "/user/updateLanguage",
		    method: "POST",
		    data: { language: lang }
		  }).then(() => {
		    console.log("语言保存成功");
		  }).finally(() => {
		    this.$i18n.locale = lang;
		    uni.setStorageSync("app_language", lang);
		    setTimeout(() => {
		      window.location.reload();
		    }, 100);
		  });
		},
    loadCommonQuestions(userId) {
      this.$http({
        url: "/auto/reply/list",
        method: "get",
      })
        .then((res) => {
          let list = res || [];
          this.autoReplyList = list;
          this.commonQuestions = list.map((item) => item.replyTitle);
        })
        .catch(() => {});
    },

    sendQuestionMessage(replyTitle) {
      let autoReply = this.autoReplyList.find(
        (item) => item.replyTitle === replyTitle
      );
      if (!autoReply) return;
   
      if (this.isBanned) {
        this.showBannedTip();
        return;
      }
  
      let userMsgInfo = {
        tmpId: this.generateId(),
        type: this.$enums.MESSAGE_TYPE.TEXT,
        content: autoReply.replyTitle,
        receipt: this.isReceipt,
        selfSend: true,
        sendId: this.mine.id,
        sendTime: new Date().getTime(),
        status: this.$enums.MESSAGE_STATUS.SENDED,
      };
   
      this.fillTargetId(userMsgInfo, this.chat.targetId);
      const chat = this.chat;
      if (!chat) return;
   
      let tmpUserMessage = this.buildTmpMessage(userMsgInfo);
      tmpUserMessage.status = this.$enums.MESSAGE_STATUS.SENDED;
      this.chatStore.insertMessage(tmpUserMessage, chat);
      this.moveChatToTop();
   
      this.triggerAutoReply(autoReply);
   
      this.scrollToBottom();
      this.isReceipt = false;
    },
   
    triggerAutoReply(autoReply) {
      let tmpId = this.generateId();
   
      let replyMsgInfo = {
				tmpId: tmpId,
				sendId: this.chat.targetId,
				recvId: this.mine.id,
				type: autoReply.replyType,
				receipt: false,
				selfSend: false,
				sendTime: new Date().getTime(),
				status: this.$enums.MESSAGE_STATUS.SENDED,
			};
		 
			if (autoReply.replyType === 0) {
				replyMsgInfo.content = autoReply.replyContent;
			} else if (autoReply.replyType === 1) {
				replyMsgInfo.content = JSON.stringify({
					originUrl: autoReply.replyContent,
					thumbUrl: autoReply.replyContent,
				});
			}
		 
			let typingMessage = {
				id: this.generateId(),
				tmpId: tmpId,
				sendId: this.chat.targetId,
				recvId: this.mine.id,
				selfSend: false,
				sendTime: new Date().getTime(),
				type: this.$enums.MESSAGE_TYPE.TIP_TEXT,
				content: this.$t('chat.typing'),
				status: this.$enums.MESSAGE_STATUS.SENDING
			};
			this.chatStore.insertMessage(typingMessage, this.chat);
			this.chatStore.deleteMessage(typingMessage, this.chat);

			let replyMessage = {
				id: this.generateId(),
				tmpId: tmpId,
				sendId: this.chat.targetId,
				recvId: this.mine.id,
				selfSend: false,
				sendTime: new Date().getTime(),
				type: autoReply.replyType,
				content: replyMsgInfo.content,
				status: this.$enums.MESSAGE_STATUS.SENDED,
			};
	 
			if (this.isGroup) {
				replyMessage.groupId = this.chat.targetId;
				replyMessage.readedCount = 0;
			}
	 
			this.chatStore.insertMessage(replyMessage, this.chat);
			this.scrollToBottom();
		},
    
    onRecorderInput() {
      this.showRecord = true;
      this.switchChatTabBox("none");
    },
    onKeyboardInput() {
      this.showRecord = false;
      this.switchChatTabBox("none");
    },
    onSendRecord(data) {
      if (this.isBanned) {
        this.showBannedTip();
        return;
      }
      let msgInfo = {
        tmpId: this.generateId(),
        content: JSON.stringify(data),
        type: this.$enums.MESSAGE_TYPE.AUDIO,
        receipt: this.isReceipt,
      };
      this.fillTargetId(msgInfo, this.chat.targetId);
      const chat = this.chat;
      if (!chat) return;
      let tmpMessage = this.buildTmpMessage(msgInfo);
      this.chatStore.insertMessage(tmpMessage, chat);
      this.moveChatToTop();
      this.sendMessageRequest(msgInfo)
        .then((m) => {
          tmpMessage = JSON.parse(JSON.stringify(tmpMessage));
          tmpMessage.id = m.id;
          tmpMessage.status = m.status;
          this.chatStore.updateMessage(tmpMessage, chat);
          this.moveChatToTop();
          this.scrollToBottom();
          this.isReceipt = false;
        })
        .catch(() => {
          tmpMessage = JSON.parse(JSON.stringify(tmpMessage));
          tmpMessage.status = this.$enums.MESSAGE_STATUS.FAILED;
          this.chatStore.updateMessage(tmpMessage, chat);
        });
    },
    onRtCall(msgInfo) {
      if (msgInfo.type == this.$enums.MESSAGE_TYPE.ACT_RT_VOICE) {
        this.onPriviteVoice();
      } else if (msgInfo.type == this.$enums.MESSAGE_TYPE.ACT_RT_VIDEO) {
        this.onPriviteVideo();
      }
    },
    onPriviteVideo() {
      const friendInfo = encodeURIComponent(JSON.stringify(this.friend));
      uni.navigateTo({
        url: `/pages/chat/chat-private-video?mode=video&friend=${friendInfo}&isHost=true`,
      });
    },
    onPriviteVoice() {
      const friendInfo = encodeURIComponent(JSON.stringify(this.friend));
      uni.navigateTo({
        url: `/pages/chat/chat-private-video?mode=voice&friend=${friendInfo}&isHost=true`,
      });
    },
    onGroupVideo() {
      let ids = [this.mine.id];
      this.$refs.selBox.init(ids, ids, []);
      this.$refs.selBox.open();
    },
    onInviteOk(ids) {
      if (ids.length < 2) {
        return;
      }
      let users = [];
      ids.forEach((id) => {
        let m = this.groupMembers.find((m) => m.userId == id);
        users.push({
          id: m.userId,
          nickName: m.showNickName,
          headImage: m.headImage,
          isCamera: false,
          isMicroPhone: true,
        });
      });
      const groupId = this.group.id;
      const inviterId = this.mine.id;
      const userInfos = encodeURIComponent(JSON.stringify(users));
      uni.navigateTo({
        url: `/pages/chat/chat-group-video?groupId=${groupId}&isHost=true
						&inviterId=${inviterId}&userInfos=${userInfos}`,
      });
    },
    moveChatToTop() {
      let chatIdx = this.chatStore.findChatIdx(this.chat);
      this.chatStore.moveTop(chatIdx);
    },
    switchReceipt() {
      this.isReceipt = !this.isReceipt;
    },
    openAtBox() {
      this.$refs.atBox.init(this.atUserIds);
      this.$refs.atBox.open();
    },
    onAtComplete(atUserIds) {
      this.atUserIds = atUserIds;
    },
    onLongPressHead(msgInfo) {
      if (
        !msgInfo.selfSend &&
        this.isGroup &&
        this.atUserIds.indexOf(msgInfo.sendId) < 0
      ) {
        this.atUserIds.push(msgInfo.sendId);
      }
    },
    headImage(msgInfo) {
      if (this.isGroup) {
        let member = this.groupMembers.find((m) => m.userId == msgInfo.sendId);
        return member ? member.headImage : "";
      } else {
        return msgInfo.selfSend
          ? this.mine.headImageThumb
          : this.chat.headImage;
      }
    },
    showName(msgInfo) {
      if (this.isGroup) {
        let member = this.groupMembers.find((m) => m.userId == msgInfo.sendId);
        return member ? member.showNickName : "";
      } else {
        return msgInfo.selfSend ? this.mine.nickName : this.chat.showName;
      }
    },
    sendTextMessage() {
      this.editorCtx.getContents({
        success: (e) => {
          this.editorCtx.clear();
          if (this.isBanned) {
            this.showBannedTip();
            return;
          }

          let sendText = "";
          e.delta.ops.forEach((op) => {
            if (op.insert.image) {
              sendText += `#${op.attributes.alt};`;
            } else {
              sendText += op.insert;
            }
          });

          sendText = sendText.trim();
          if (!sendText && this.atUserIds.length == 0) {
            return uni.showToast({
              title: this.$t('chat.cannotSendBlank'),
              icon: "none",
            });
          }

          let receiptText = this.isReceipt ? this.$t('chat.receiptMessage') : "";
          let atText = this.createAtText();
          let msgInfo = {
            tmpId: this.generateId(),
            content: receiptText + sendText + atText,
            atUserIds: this.atUserIds,
            receipt: this.isReceipt,
            type: this.$enums.MESSAGE_TYPE.TEXT,
          };

          this.atUserIds = [];
          this.isReceipt = false;
          this.fillTargetId(msgInfo, this.chat.targetId);

          const chat = this.chat;
          if (!chat) return;

          let tmpMessage = this.buildTmpMessage(msgInfo);
          const tmpMessageCopy = JSON.parse(JSON.stringify(tmpMessage));
          this.chatStore.insertMessage(tmpMessageCopy, chat);

          const chatIndex = this.chatStore.chats.findIndex(
            (c) => c.targetId === chat.targetId && c.type === chat.type
          );

          if (chatIndex !== -1) {
            const targetChat = this.chatStore.chats[chatIndex];
            const msgIndex = targetChat.messages.findIndex(
              (m) => m.tmpId === msgInfo.tmpId
            );

            if (msgIndex !== -1) {
              this.$nextTick(() => {
                this.scrollToBottom();
              });

              this.sendMessageRequest(msgInfo)
                .then((m) => {
                  const updatedMessage = {
                    ...targetChat.messages[msgIndex],
                    id: m.id,
                    status: m.status,
                    content: m.content,
                  };
                  this.$set(targetChat.messages, msgIndex, updatedMessage);
                  this.$forceUpdate();
                })
                .catch(() => {
                  const failedMessage = {
                    ...targetChat.messages[msgIndex],
                    status: this.$enums.MESSAGE_STATUS.FAILED,
                  };
                  this.$set(targetChat.messages, msgIndex, failedMessage);
                  this.$forceUpdate();

                  uni.showToast({
                    title: this.$t('chat.sendFailed'),
                    icon: "none",
                  });
                });
            }
          }
        },
      });
    },
    createAtText() {
      let atText = "";
      this.atUserIds.forEach((id) => {
        if (id == -1) {
          atText += ` @${this.$t('chat.atAll')}`;
        } else {
          let member = this.groupMembers.find((m) => m.userId == id);
          if (member) {
            atText += ` @${member.showNickName}`;
          }
        }
      });
      return atText;
    },
    fillTargetId(msgInfo, targetId) {
      if (this.isGroup) {
        msgInfo.groupId = targetId;
      } else {
        msgInfo.recvId = targetId;
      }
    },
    scrollToBottom() {
      let size = this.messageSize;
      if (size > 0) {
        this.scrollToMsgIdx(size - 1);
      }
    },
    scrollToMsgIdx(idx) {
      if (idx == this.scrollMsgIdx && idx > 0) {
        this.$nextTick(() => {
          this.scrollMsgIdx = idx - 1;
          this.scrollToMsgIdx(idx);
        });
        return;
      }
      this.$nextTick(() => {
        this.scrollMsgIdx = idx;
      });
    },
    onShowEmoChatTab() {
      this.showRecord = false;
      this.switchChatTabBox("emo");
    },
    onShowToolsChatTab() {
      this.showRecord = false;
      this.switchChatTabBox("tools");
    },
    switchChatTabBox(chatTabBox) {
      if (this.chatTabBox != chatTabBox) {
        this.chatTabBox = chatTabBox;
        if (chatTabBox != "tools" && this.$refs.fileUpload) {
          this.$refs.fileUpload.hide();
        }
        setTimeout(() => this.reCalChatMainHeight(), 30);
      }
    },
    selectEmoji(emoText) {
      let path = this.$emo.textToPath(emoText);
      this.isReadOnly = true;
      this.isEmpty = false;
      this.$nextTick(() => {
        this.editorCtx.insertImage({
          src: path,
          alt: emoText,
          extClass: "emoji-small",
          nowrap: true,
          complete: () => {
            this.isReadOnly = false;
            this.editorCtx.blur();
          },
        });
      });
    },
    onUploadImageBefore(file) {
      if (this.isBanned) {
        this.showBannedTip();
        return;
      }
      let data = {
        originUrl: file.path,
        thumbUrl: file.path,
      };
      let msgInfo = {
        tmpId: this.generateId(),
        fileId: file.uid,
        sendId: this.mine.id,
        content: JSON.stringify(data),
        sendTime: new Date().getTime(),
        selfSend: true,
        type: this.$enums.MESSAGE_TYPE.IMAGE,
        readedCount: 0,
        status: this.$enums.MESSAGE_STATUS.SENDING,
      };
      this.fillTargetId(msgInfo, this.chat.targetId);
      this.chatStore.insertMessage(msgInfo, this.chat);
      this.moveChatToTop();
      file.msgInfo = msgInfo;
      file.chat = this.chat;
      let chat = this.chat;
      this.getImageSize(file).then((size) => {
        msgInfo = JSON.parse(JSON.stringify(msgInfo));
        data.width = size.width;
        data.height = size.height;
        msgInfo.content = JSON.stringify(data);
        this.chatStore.updateMessage(msgInfo, chat);
        this.scrollToBottom();
      });
      return true;
    },
    onUploadImageSuccess(file, res) {
      let msgInfo = JSON.parse(JSON.stringify(file.msgInfo));
      msgInfo.content = JSON.stringify(res.data);
      msgInfo.receipt = this.isReceipt;
      this.sendMessageRequest(msgInfo)
        .then((m) => {
          msgInfo.id = m.id;
          msgInfo.status = m.status;
          this.isReceipt = false;
          this.chatStore.updateMessage(msgInfo, file.chat);
        })
        .catch(() => {
          msgInfo.status = this.$enums.MESSAGE_STATUS.FAILED;
          this.chatStore.updateMessage(msgInfo, file.chat);
        });
    },
    onUploadImageFail(file, err) {
      let msgInfo = JSON.parse(JSON.stringify(file.msgInfo));
      msgInfo.status = this.$enums.MESSAGE_STATUS.FAILED;
      this.chatStore.updateMessage(msgInfo, file.chat);
    },
    onUploadFileBefore(file) {
      if (this.isBanned) {
        this.showBannedTip();
        return;
      }
      let data = {
        name: file.name,
        size: file.size,
        url: file.path,
      };
      let msgInfo = {
        tmpId: this.generateId(),
        sendId: this.mine.id,
        content: JSON.stringify(data),
        sendTime: new Date().getTime(),
        selfSend: true,
        type: this.$enums.MESSAGE_TYPE.FILE,
        readedCount: 0,
        status: this.$enums.MESSAGE_STATUS.SENDING,
      };
      this.fillTargetId(msgInfo, this.chat.targetId);
      this.chatStore.insertMessage(msgInfo, this.chat);
      this.moveChatToTop();
      file.msgInfo = msgInfo;
      file.chat = this.chat;
      return true;
    },
    onUploadFileSuccess(file, res) {
      let data = {
        name: file.name,
        size: file.size,
        url: res.data,
      };
      let msgInfo = JSON.parse(JSON.stringify(file.msgInfo));
      msgInfo.content = JSON.stringify(data);
      msgInfo.receipt = this.isReceipt;
      this.sendMessageRequest(msgInfo)
        .then((m) => {
          msgInfo.id = m.id;
          msgInfo.status = m.status;
          this.isReceipt = false;
          this.chatStore.updateMessage(msgInfo, file.chat);
        })
        .catch(() => {
          msgInfo.status = this.$enums.MESSAGE_STATUS.FAILED;
          this.chatStore.updateMessage(msgInfo, file.chat);
        });
    },
    onUploadFileFail(file, res) {
      let msgInfo = JSON.parse(JSON.stringify(file.msgInfo));
      msgInfo.status = this.$enums.MESSAGE_STATUS.FAILED;
      this.chatStore.updateMessage(msgInfo, file.chat);
    },
    onResendMessage(msgInfo) {
      if (msgInfo.type != this.$enums.MESSAGE_TYPE.TEXT) {
        uni.showToast({
          title: this.$t('chat.resendNotSupported'),
          icon: "none",
        });
        return;
      }
      const chat = this.chat;
      if (!chat) return;
      this.chatStore.deleteMessage(msgInfo, chat);
      msgInfo.tmpId = this.generateId();
      let tmpMessage = this.buildTmpMessage(msgInfo);
      this.chatStore.insertMessage(tmpMessage, chat);
      this.moveChatToTop();
      this.sendMessageRequest(msgInfo)
        .then((m) => {
          tmpMessage = JSON.parse(JSON.stringify(tmpMessage));
          tmpMessage.id = m.id;
          tmpMessage.status = m.status;
          tmpMessage.content = m.content;
          this.chatStore.updateMessage(tmpMessage, chat);
        })
        .catch(() => {
          tmpMessage = JSON.parse(JSON.stringify(tmpMessage));
          tmpMessage.status = this.$enums.MESSAGE_STATUS.FAILED;
          this.chatStore.updateMessage(tmpMessage, chat);
        });
    },

    onDeleteMessage(msgInfo) {
      uni.showModal({
        title: this.$t('chat.deleteMessage'),
        content: this.$t('chat.confirmDelete'),
        confirmText: this.$t('common.confirm'),
        cancelText: this.$t('common.cancel'),
        success: (res) => {
          if (!res.cancel) {
            this.chatStore.deleteMessage(msgInfo, this.chat);
            uni.showToast({
              title: this.$t('chat.deleteSuccess'),
              icon: "none",
            });
          }
        },
      });
    },
    onRecallMessage(msgInfo) {
      uni.showModal({
        title: this.$t('chat.recallMessage'),
        content: this.$t('chat.confirmRecall'),
        confirmText: this.$t('common.confirm'),
        cancelText: this.$t('common.cancel'),
        success: (res) => {
          if (!res.cancel) {
            let url = `/message/${this.chat.type.toLowerCase()}/recall/${
              msgInfo.id
            }`;
            this.$http({
              url: url,
              method: "DELETE",
            }).then((m) => {
              m.selfSend = true;
              this.chatStore.recallMessage(m, this.chat);
            });
          }
        },
      });
    },
    onCopyMessage(msgInfo) {
      uni.setClipboardData({
        data: msgInfo.content,
        success: () => {
          uni.showToast({ title: this.$t('chat.copySuccess') });
        },
        fail: () => {
          uni.showToast({ title: this.$t('chat.copyFailed'), icon: "none" });
        },
      });
    },
    onDownloadFile(msgInfo) {
      let url = JSON.parse(msgInfo.content).url;
      uni.downloadFile({
        url: url,
        success(res) {
          if (res.statusCode === 200) {
            var filePath = encodeURI(res.tempFilePath);
            uni.openDocument({
              filePath: filePath,
              showMenu: true,
            });
          }
        },
        fail(e) {
          uni.showToast({
            title: this.$t('chat.downloadFailed'),
            icon: "none",
          });
        },
      });
    },
    onClickToBottom() {
      setTimeout(() => {
        this.scrollToBottom();
        setTimeout(() => {
          this.isInBottom = true;
          this.newMessageSize = 0;
        }, 100);
      }, 300);
    },
    onScroll(e) {
      this.scrollViewHeight = e.detail.scrollHeight;
    },
    onScrollToTop() {
      if (this.showMinIdx > 0) {
        if (uni.getSystemInfoSync().platform == "ios") {
          this.holdingScrollBar(this.scrollViewHeight);
        } else {
          this.scrollToMsgIdx(this.showMinIdx);
        }
        this.showMinIdx = this.showMinIdx > 20 ? this.showMinIdx - 20 : 0;
      }
      this.isInBottom = false;
    },
    onScrollToBottom(e) {
      this.isInBottom = true;
      this.newMessageSize = 0;
    },
    holdingScrollBar(scrollViewHeight) {
      const query = uni.createSelectorQuery().in(this);
      setTimeout(() => {
        query.select(".chat-wrap").boundingClientRect();
        query.exec((data) => {
          this.scrollTop = data[0].height - scrollViewHeight;
          if (this.scrollTop < 10) {
            this.holdingScrollBar();
          } else {
            const delays = [100, 300, 1000];
            delays.forEach((delay) =>
              setTimeout(() => (this.scrollTop += 5), delay)
            );
          }
        });
      }, 10);
    },
    onShowMore() {
      if (this.isGroup) {
        uni.navigateTo({
          url: "/pages/group/group-info?id=" + this.group.id,
        });
      } else {
        uni.navigateTo({
          url: "/pages/common/user-info?id=" + this.userInfo.id,
        });
      }
    },
    onTextInput(e) {
      this.isEmpty = e.detail.html == "<p><br></p>";
    },
    onEditorReady() {
      this.$nextTick(() => {
        const query = uni.createSelectorQuery().in(this);
        query
          .select("#editor")
          .context((res) => {
            this.editorCtx = res.context;
            // #ifdef H5
            if (!window.__pasteHandlerAdded__) {
              window.__pasteHandlerAdded__ = true;
              if (window.__isPasting__ === undefined) {
                window.__isPasting__ = false;
              }
              if (this.pasteHandler) {
                document.removeEventListener('paste', this.pasteHandler);
              }
              this.pasteHandler = this.onDocumentPaste.bind(this);
              document.addEventListener('paste', this.pasteHandler);
            }
            // #endif
          })
          .exec();
      });
    },
    onEditorFocus(e) {
      this.isFocus = true;
      this.scrollToBottom();
      this.switchChatTabBox("none");
    },
    onEditorBlur(e) {
      this.isFocus = false;
    },
    async onDocumentPaste(e) {
      // #ifdef H5
      const timestamp = new Date().toISOString();
      const activeElement = document.activeElement;
      const isInEditor = activeElement && (
        activeElement.closest('#editor') || 
        activeElement.closest('.ql-editor')
      );

      if (!isInEditor) {
        return;
      }

      if (window.__isPasting__) {
        e.preventDefault();
        e.stopPropagation();
        return;
      }

      const items = (e.clipboardData || e.originalEvent.clipboardData).items;
      let hasImage = false;

      for (let i = 0; i < items.length; i++) {
        const item = items[i];
        if (item.kind === 'file' && item.type.startsWith('image/')) {
          e.preventDefault();
          e.stopPropagation();
          hasImage = true;
          window.__isPasting__ = true;

          try {
            const file = item.getAsFile();
            const base64 = await this.fileToBase64(file);
            const tempFile = {
              path: base64,
              uid: this.generateId(),
              size: file.size,
              name: file.name || 'pasted-image.png'
            };
            await this.handlePasteImage(tempFile);
          } catch (error) {
            console.error("处理粘贴图片失败:", error);
          } finally {
            window.__isPasting__ = false;
          }
          break;
        }
      }

      if (!hasImage) {
        this.isPasting = false;
      }
      // #endif
    },

    async fileToBase64(file) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = (event) => {
          resolve(event.target.result);
        };
        reader.onerror = (error) => {
          reject(error);
        };
        reader.readAsDataURL(file);
      });
    },

    async handlePasteImage(file) {
      if (!this.chat) {
        return;
      }

      try {
        if (this.isBanned) {
          this.showBannedTip();
          return;
        }

        let data = {
          originUrl: file.path,
          thumbUrl: file.path,
        };

        let msgInfo = {
          tmpId: this.generateId(),
          fileId: file.uid,
          sendId: this.mine.id,
          content: JSON.stringify(data),
          sendTime: new Date().getTime(),
          selfSend: true,
          type: this.$enums.MESSAGE_TYPE.IMAGE,
          readedCount: 0,
          status: this.$enums.MESSAGE_STATUS.SENDING,
        };

        this.fillTargetId(msgInfo, this.chat.targetId);
        this.chatStore.insertMessage(msgInfo, this.chat);
        this.moveChatToTop();
        file.msgInfo = msgInfo;
        file.chat = this.chat;

        const size = await this.getImageSize(file);
        msgInfo = JSON.parse(JSON.stringify(msgInfo));
        data.width = size.width;
        data.height = size.height;
        msgInfo.content = JSON.stringify(data);
        this.chatStore.updateMessage(msgInfo, this.chat);
        this.scrollToBottom();

        await this.uploadPastedImage(file);

      } catch (error) {
        console.error("处理粘贴图片失败:", error);
        this.isPasting = false;
      }
    },

    async uploadPastedImage(file) {
      // #ifdef H5
      try {
        const base64Data = file.path.split(',')[1];
        const byteCharacters = atob(base64Data);
        const byteArrays = [];
        for (let offset = 0; offset < byteCharacters.length; offset += 512) {
          const slice = byteCharacters.slice(offset, offset + 512);
          const byteNumbers = new Array(slice.length);
          for (let i = 0; i < slice.length; i++) {
            byteNumbers[i] = slice.charCodeAt(i);
          }
          const byteArray = new Uint8Array(byteNumbers);
          byteArrays.push(byteArray);
        }
        const blob = new Blob(byteArrays, { type: 'image/png' });

        const formData = new FormData();
        formData.append('file', blob, file.name);

        const response = await fetch(UNI_APP.BASE_URL + `/image/upload?isPermanent=false&thumbSize=50`, {
          method: 'POST',
          body: formData
        });

        const data = await response.json();

        if (data.code === 200) {
          let msgInfo = JSON.parse(JSON.stringify(file.msgInfo));
          msgInfo.content = JSON.stringify(data.data);
          msgInfo.receipt = this.isReceipt;
          this.chatStore.updateMessage(msgInfo, file.chat);

          const m = await this.sendMessageRequest(msgInfo);
          msgInfo.id = m.id;
          msgInfo.status = m.status;
          this.isReceipt = false;
          this.chatStore.updateMessage(msgInfo, file.chat);
        } else {
          uni.showToast({
            icon: "none",
            title: data.message || this.$t('chat.uploadFailed'),
          });
          let msgInfo = JSON.parse(JSON.stringify(file.msgInfo));
          msgInfo.status = this.$enums.MESSAGE_STATUS.FAILED;
          this.chatStore.updateMessage(msgInfo, file.chat);
        }
      } catch (error) {
        uni.showToast({
          icon: "none",
          title: this.$t('chat.uploadFailed'),
        });
        let msgInfo = JSON.parse(JSON.stringify(file.msgInfo));
        msgInfo.status = this.$enums.MESSAGE_STATUS.FAILED;
        this.chatStore.updateMessage(msgInfo, file.chat);
      }
      // #endif
    },
    onAudioStateChange(state, msgInfo) {
      const playingAudio = this.$refs["message" + msgInfo.id][0];
      if (state == "PLAYING" && playingAudio != this.playingAudio) {
        this.playingAudio && this.playingAudio.stopPlayAudio();
        this.playingAudio = playingAudio;
      }
    },
    loadReaded(fid) {
      this.$http({
        url: `/message/private/maxReadedId?friendId=${fid}`,
        method: "get",
      }).then((id) => {
        this.chatStore.readedMessage({
          friendId: fid,
          maxId: id,
        });
      });
    },
    readedMessage() {
      if (this.unreadCount > 0) {
        let url = "";
        if (this.isGroup) {
          url = `/message/group/readed?groupId=${this.chat.targetId}`;
        } else {
          url = `/message/private/readed?friendId=${this.chat.targetId}`;
        }
        this.$http({
          url: url,
          method: "PUT",
        }).then(() => {});
      }
      this.chatStore.resetUnreadCount(this.chat);
    },
    loadGroup(groupId) {
      this.$http({
        url: `/group/find/${groupId}`,
        method: "GET",
      }).then((group) => {
        this.group = group;
        this.chatStore.updateChatFromGroup(group);
        this.groupStore.updateGroup(group);
      });

      this.$http({
        url: `/group/members/${groupId}`,
        method: "GET",
      }).then((groupMembers) => {
        this.groupMembers = groupMembers;
      });
    },
    updateFriendInfo() {
      if (this.isFriend) {
        let friend = JSON.parse(JSON.stringify(this.friend));
        friend.headImage = this.userInfo.headImageThumb;
        friend.nickName = this.userInfo.nickName;
        friend.showNickName = friend.remarkNickName
          ? friend.remarkNickName
          : friend.nickName;
        this.friendStore.updateFriend(friend);
        this.chatStore.updateChatFromFriend(friend);
      } else {
        this.chatStore.updateChatFromUser(this.userInfo);
      }
    },
    async loadFriend(friendId) {
      return new Promise((resolve) => {
        this.$http({
          url: `/user/find/${friendId}`,
          method: "GET",
        }).then((userInfo) => {
          this.userInfo = userInfo;
          this.updateFriendInfo();
          resolve(); // 让外部可以 then
        }).catch(() => {
          resolve();
        });
      });
    },
    rpxTopx(rpx) {
      let info = uni.getSystemInfoSync();
      let px = (info.windowWidth * rpx) / 750;
      return Math.floor(rpx);
    },
    sendMessageRequest(msgInfo) {
      return new Promise((resolve, reject) => {
        this.reqQueue.push({ msgInfo, resolve, reject });
        this.processReqQueue();
      });
    },
    processReqQueue() {
      if (this.reqQueue.length && !this.isSending) {
        this.isSending = true;
        const reqData = this.reqQueue.shift();
        this.$http({
          url: this.messageAction,
          method: "post",
          data: reqData.msgInfo,
        })
          .then((res) => {
            reqData.resolve(res);
          })
          .catch((e) => {
            reqData.reject(e);
          })
          .finally(() => {
            this.isSending = false;
            this.processReqQueue();
          });
      }
    },
    reCalChatMainHeight() {
      let sysInfo = uni.getSystemInfoSync();
      let h = this.windowHeight;
      h -= 50;
      if (this.isShowKeyBoard || this.chatTabBox != "none") {
        h -= this.keyboardHeight;
        this.scrollToBottom();
      }
      // #ifdef APP-PLUS
      h -= sysInfo.statusBarHeight;
      // #endif
      this.chatMainHeight = h;
      // #ifndef APP
      if (uni.getSystemInfoSync().platform == "ios") {
        const delays = [50, 100, 500];
        delays.forEach((delay) => {
          setTimeout(() => {
            uni.pageScrollTo({
              scrollTop: 0,
              duration: 10,
            });
          }, delay);
        });
      }
      // #endif
    },
    listenKeyBoard() {
      // #ifdef H5
      if (navigator.platform == "Win32") {
        return;
      }
      if (uni.getSystemInfoSync().platform == "ios") {
        if (window.visualViewport) {
          window.visualViewport.addEventListener("resize", this.resizeListener);
        } else {
          window.addEventListener("focusin", this.focusInListener);
          window.addEventListener("focusout", this.focusOutListener);
        }
      } else {
        window.addEventListener("resize", this.resizeListener);
      }
      // #endif
      // #ifndef H5
      uni.onKeyboardHeightChange(this.keyBoardListener);
      // #endif
    },
    unListenKeyboard() {
      // #ifdef H5
      window.removeEventListener("focusin", this.focusInListener);
      window.removeEventListener("focusout", this.focusOutListener);
      window.removeEventListener("resize", this.resizeListener);
      if (window.visualViewport) {
        window.visualViewport.removeEventListener(
          "resize",
          this.resizeListener
        );
      }
      // #endif
      // #ifndef H5
      uni.offKeyboardHeightChange(this.keyBoardListener);
      // #endif
    },
    keyBoardListener(res) {
      this.isShowKeyBoard = res.height > 0;
      if (this.isShowKeyBoard) {
        this.keyboardHeight = res.height;
        // #ifdef APP-PLUS
        let sysInfo = uni.getSystemInfoSync();
        if (sysInfo.platform == "ios") {
          this.keyboardHeight -= this.screenHeight - this.windowHeight;
        }
        // #endif
      }
      setTimeout(() => this.reCalChatMainHeight(), 30);
    },
    resizeListener() {
      let keyboardHeight = this.initHeight - window.innerHeight;
      if (window.visualViewport && uni.getSystemInfoSync().platform == "ios") {
        keyboardHeight = this.initHeight - window.visualViewport.height;
      }
      let isShowKeyBoard = keyboardHeight > 150;
      if (isShowKeyBoard) {
        this.keyboardHeight = keyboardHeight;
      }
      if (this.isShowKeyBoard != isShowKeyBoard) {
        this.isShowKeyBoard = isShowKeyBoard;
        setTimeout(() => this.reCalChatMainHeight(), 30);
      }
    },
    focusInListener() {
      this.isShowKeyBoard = true;
      setTimeout(() => this.reCalChatMainHeight(), 30);
    },
    focusOutListener() {
      this.isShowKeyBoard = false;
      setTimeout(() => this.reCalChatMainHeight(), 30);
    },
    showBannedTip() {
      let msgInfo = {
        tmpId: this.generateId(),
        sendId: this.mine.id,
        sendTime: new Date().getTime(),
        type: this.$enums.MESSAGE_TYPE.TIP_TEXT,
      };
      if (this.isPrivate) {
        msgInfo.recvId = this.mine.id;
        msgInfo.content = this.$t('chat.userBanned', { reason: this.userInfo.reason });
      } else {
        msgInfo.groupId = this.group.id;
        msgInfo.content = this.$t('chat.groupBanned', { reason: this.group.reason });
      }
      this.chatStore.insertMessage(msgInfo, this.chat);
    },
    buildTmpMessage(msgInfo) {
      let message = JSON.parse(JSON.stringify(msgInfo));
      message.sendId = this.mine.id;
      message.sendTime = new Date().getTime();
      message.status = this.$enums.MESSAGE_STATUS.SENDING;
      message.selfSend = true;
      if (this.isGroup) {
        message.readedCount = 0;
      }
      return message;
    },
    getImageSize(file) {
      return new Promise((resolve) => {
        uni.getImageInfo({
          src: file.path,
          success: (res) => {
            resolve(res);
          },
          fail: (err) => {
            console.error("获取图片信息失败", err);
          },
        });
      });
    },
    generateId() {
      const id =
        String(new Date().getTime()) + String(Math.floor(Math.random() * 1000));
      if (this.maxTmpId > id) {
        return this.generateId();
      }
      this.maxTmpId = id;
      return id;
    },

    async getSetting() {
      this.$http({
        url: "/getSetting",
        method: "post",
      }).then((res) => {
        if(res.isFileOpen === 1){
          this.isFileOpen = true;
        }
      });
    },
  },
  computed: {
    title() {
      if (!this.chat) return this.$t('chat.title');
      let title = this.chat.showName;
      if (this.isGroup) {
        let size = this.groupMembers.filter((m) => !m.quit).length;
        title += `(${size})`;
      }
      return title;
    },
    chat() {
      if (!this.currentTargetId) return null;
      return (
        this.chatStore.chats.find(
          (c) =>
            c.targetId === this.currentTargetId &&
            c.type === this.currentChatType
        ) || null
      );
    },

    activeChatIdx: {
      get() {
        return this._activeChatIdx || 0;
      },
      set(val) {
        this._activeChatIdx = val;
      },
    },
    mine() {
      return this.userStore.userInfo;
    },
    friend() {
      return this.friendStore.findFriend(this.userInfo.id);
    },
    messageAction() {
      if (!this.chat) return "";
      return `/message/${this.chat.type.toLowerCase()}/send`;
    },
    messageSize() {
      if (!this.chat || !this.chat.messages) {
        return 0;
      }
      return this.chat.messages.length;
    },
    unreadCount() {
      if (!this.chat || !this.chat.unreadCount) {
        return 0;
      }
      return this.chat.unreadCount;
    },
    isBanned() {
      return (
        (this.isPrivate && this.userInfo.isBanned) ||
        (this.isGroup && this.group.isBanned)
      );
    },
    atUserItems() {
      let atUsers = [];
      this.atUserIds.forEach((id) => {
        if (id == -1) {
          atUsers.push({
            id: -1,
            showNickName: this.$t('chat.atAll'),
          });
          return;
        }
        let member = this.groupMembers.find((m) => m.userId == id);
        if (member) {
          atUsers.push(member);
        }
      });
      return atUsers;
    },
    memberSize() {
      return this.groupMembers.filter((m) => !m.quit).length;
    },
    isGroup() {
      return this.chat && this.chat.type == "GROUP";
    },
    isPrivate() {
      return this.chat && this.chat.type == "PRIVATE";
    },
    loading() {
      return this.chatStore.loading;
    },
  },
  watch: {
    chat: {
      handler(newChat, oldChat) {
        if (newChat && newChat.messages && newChat.messages.length > 0) {
          if (this.isInBottom) {
            this.$nextTick(() => {
              this.scrollToBottom();
            });
          }
        }
      },
      deep: true,
      immediate: true,
    },
    "chat.messages.length": function (newLength, oldLength) {
      if (newLength > oldLength && this.isInBottom) {
        this.$nextTick(() => {
          this.scrollToBottom();
        });
      }
    },
    messageSize: function (newSize, oldSize) {
      if (newSize > oldSize && oldSize > 0) {
        let lastMessage = this.chat.messages[newSize - 1];
        if (this.$msgType.isNormal(lastMessage.type)) {
          if (this.isInBottom || lastMessage.selfSend) {
            this.scrollToBottom();
          } else {
            this.newMessageSize++;
          }
        }
      }
    },
    unreadCount: {
      handler(newCount, oldCount) {
        if (newCount > 0) {
          this.readedMessage();
        }
      },
    },
    loading: {
      handler(newLoading, oldLoading) {
        if (!newLoading && this.isPrivate) {
          this.loadReaded(this.chat.targetId);
        }
      },
    },
  },
  async onLoad(options) {
		
    try {
			this.currentLang = uni.getStorageSync("app_language") || "zh";
      uni.showLoading({ title: this.$t('common.loading'), mask: true });

      let targetId = null;
      let type = "PRIVATE";

      if (options.targetId) {
        targetId = Number(options.targetId);
        type = options.type || "PRIVATE";
      } else {
        if (this.friendStore.friends.length === 0)
          await this.friendStore.loadFriend();
        const first = this.friendStore.friends[0];
        if (!first) {
          uni.hideLoading();
          return uni.showToast({ title: this.$t('chat.noFriends'), icon: "none" });
        }
        targetId = first.id;
      }

      await this.chatStore.loadChat();
      await new Promise((r) => setTimeout(r, 300));

      let chat = this.chatStore.chats.find(
        (c) => c.type === type && c.targetId === targetId
      );
      if (!chat) {
        const friend =
          this.friendStore.findFriend(targetId) || this.friendStore.friends[0];
        chat = {
          targetId,
          type,
          showName: friend?.nickName || this.$t('common.customerService'),
          headImage: friend?.headImage || "",
          isDnd: false,
          lastContent: "",
          lastSendTime: Date.now(),
          unreadCount: 0,
          messages: [],
        };
        this.chatStore.chats.unshift(chat);
      }

      this.currentTargetId = targetId;
      this.currentChatType = type;

      await this.$nextTick();
      if (!this.chat) {
        console.error("Chat 初始化失败");
        uni.hideLoading();
        return;
      }

      this.readedMessage();
      // this.loadFriend(targetId);
			await this.loadFriend(targetId);

      this.loadReaded(targetId);
      this.loadCommonQuestions(targetId);

      this.listenKeyBoard();
      this.windowHeight = uni.getSystemInfoSync().windowHeight;
      this.screenHeight = uni.getSystemInfoSync().screenHeight;
      this.reCalChatMainHeight();

      await this.getSetting();
      this.$nextTick(() => this.scrollToBottom());
			this.autoMergeOldCustomerOnRefresh();
    } catch (err) {
      console.error("错误：", err);
    } finally {
      uni.hideLoading();
    }
  },
  onUnload() {
    this.unListenKeyboard();
    // #ifdef H5
    if (this.hasPasteListener && this.pasteHandler) {
      document.removeEventListener('paste', this.pasteHandler);
      this.hasPasteListener = false;
      this.pasteHandler = null;
    }
    // #endif
  },
};
</script>

<style lang="scss">
	.lang-wrap {
	  position: fixed;
	  top: var(--status-bar-height);
	  right: 40rpx;
	  z-index: 9999 !important;
	  height: $im-nav-bar-height;
	  display: flex;
	  align-items: center;
	}
	
	.lang-btn {
	  font-size: 24rpx;
	  color: #333;
	  padding: 6rpx 14rpx;
	  background: #ffffff;
	  border: 1px solid #eeeeee;
	  border-radius: 30rpx;
	  white-space: nowrap;
	  cursor: pointer;
	}
	
	.lang-drop-panel {
	  position: absolute;
	  top: 100%;
	  right: 0;
	  min-width: 180rpx;
	  background: #fff;
	  border-radius: 12rpx;
	  box-shadow: 0 4rpx 20rpx rgba(0,0,0,0.15);
	  overflow: hidden;
	  margin-top: 12rpx;
	  z-index: 10000;
	}
	
	.lang-drop-item {
	  padding: 24rpx 30rpx;
	  font-size: 28rpx;
	  color: #333;
	  text-align: center;
	  cursor: pointer;
	
	  &.active {
	    background-color: #f5f7ff;
	    color: #007bff;
	    font-weight: 500;
	  }
	
	  &:active {
	    background-color: #f0f0f0;
	  }
	}
	
	.lang-mask {
	  position: fixed;
	  top: 0;
	  left: 0;
	  right: 0;
	  bottom: 0;
	  z-index: 9998;
	}
	
	.nav-title-wrapper {
	  width: 100%;
	  text-align: center;
	}
.chat-box {
  $icon-color: rgba(0, 0, 0, 0.88);
  position: relative;
  background-color: #fafafa;

  .header {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 60rpx;
    padding: 5px;
    background-color: #fafafa;
    line-height: 50px;
    font-size: $im-font-size-large;
    box-shadow: $im-box-shadow-lighter;
    z-index: 1;

    .btn-side {
      position: absolute;
      line-height: 60rpx;
      cursor: pointer;

      &.right {
        right: 30rpx;
      }
    }
  }

  .chat-main-box {
    // #ifndef APP-PLUS
    top: $im-nav-bar-height;
    // #endif
    // #ifdef APP-PLUS
    top: calc($im-nav-bar-height + var(--status-bar-height));
    // #endif
    position: fixed;
    width: 100%;
    display: flex;
    flex-direction: column;
    z-index: 2;

    .chat-message {
      flex: 1;
      padding: 0;
      overflow: hidden;
      position: relative;
      background-color: white;

      .scroll-box {
        height: 100%;
        padding-top: 200rpx;
        box-sizing: border-box;
      }

      .guess-question-box {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        z-index: 10;
        background-color: #f6f6f6;
        padding: 20rpx 30rpx;
        border-radius: 12rpx;
        margin: 10rpx 20rpx;
        box-sizing: border-box;

        .guess-title {
          font-size: 32rpx;
          color: #333333;
          font-weight: 500;
          margin-bottom: 20rpx;
        }

        .guess-list {
          display: flex;
          flex-direction: column;
          gap: 16rpx;
        }

        .guess-item {
          display: flex;
          align-items: center;
          gap: 10rpx;
          font-size: 30rpx;
          color: #009e5f;
          cursor: pointer;

          .item-bullet {
            line-height: 1;
          }

          .item-text {
            line-height: 1.4;
          }

          &:active {
            opacity: 0.7;
          }
        }
      }

      .scroll-to-bottom {
        position: absolute;
        right: 30rpx;
        bottom: 30rpx;
        font-size: $im-font-size;
        color: $im-color-primary;
        font-weight: 600;
        background: white;
        padding: 10rpx 30rpx;
        border-radius: 25rpx;
        box-shadow: $im-box-shadow-dark;
      }
    }

    .chat-at-bar {
      display: flex;
      align-items: center;
      padding: 0 10rpx;

      .icon-at {
        font-size: $im-font-size-larger;
        color: $im-color-primary;
        font-weight: bold;
      }

      .chat-at-scroll-box {
        flex: 1;
        width: 80%;

        .chat-at-items {
          display: flex;
          align-items: center;
          height: 70rpx;

          .chat-at-item {
            padding: 0 3rpx;
          }
        }
      }
    }

    .send-bar {
      display: flex;
      align-items: center;
      padding: 10rpx;
      border-top: $im-border solid 1px;
      background-color: $im-bg;
      min-height: 80rpx;
      padding-bottom: 14rpx;

      .iconfont {
        font-size: 60rpx;
        margin: 0 10rpx;
        color: $icon-color;
      }

      .chat-record {
        flex: 1;
      }

      .send-text {
        flex: 1;
        overflow: auto;
        padding: 14rpx 20rpx;
        background-color: #fff;
        border-radius: 8rpx;
        font-size: $im-font-size;
        box-sizing: border-box;
        margin: 0 10rpx;
        position: relative;

        .send-text-area {
          width: 100%;
          height: 100%;
          min-height: 40rpx;
          max-height: 200rpx;
          font-size: 30rpx;
        }
      }

      .btn-send {
        margin: 5rpx;
      }
    }
  }

  .chat-tab-bar {
    width: 100%;
    position: fixed;
    bottom: 0;
    background-color: $im-bg;

    .chat-tools {
      padding: 40rpx;
      box-sizing: border-box;

      .chat-tools-list {
        display: flex;
        flex-wrap: wrap;
        align-content: center;

        .chat-tools-item {
          width: 25%;
          padding: 16rpx;
          box-sizing: border-box;
          display: flex;
          flex-direction: column;
          align-items: center;

          .tool-icon {
            padding: 26rpx;
            font-size: 54rpx;
            border-radius: 20%;
            background-color: white;
            color: $icon-color;

            &:active {
              background-color: $im-bg-active;
            }
          }

          .tool-name {
            height: 60rpx;
            line-height: 60rpx;
            font-size: 28rpx;
          }
        }
      }
    }

    .chat-emotion {
      padding: 40rpx;
      box-sizing: border-box;

      .emotion-item-list {
        display: flex;
        flex-wrap: wrap;
        justify-content: space-between;
        align-content: center;

        .emotion-item {
          text-align: center;
          cursor: pointer;
          padding: 5px;
        }
      }
    }
  }
}
</style>