// src/stores/websocket.js
import { defineStore } from "pinia";
import { $root as protobuf } from "@/common/proto/proto";
import { useWalletStore } from "@/stores/modules/walletStore";
import { getMessageApi, friendRequest, groupList } from "@/api/path/im.api";
import { showDialog } from 'vant';
import { useSystemStore } from "@/stores/modules/systemStore";
import * as MsgType from "@/common/constant/msgType";
import {
  setMessageHook,
  handleMessageHook,
} from "@/views/im/hook/messagesHook";

// 配置常量
const WS_CONFIG = {
  HEARTBEAT_INTERVAL: 30000, // 30秒
  HEARTBEAT_TIMEOUT: 10000, // 10秒
  HEARTBEAT_RETRY_LIMIT: 3,
  RECONNECT_BASE_INTERVAL: 1000,
  RECONNECT_MAX_INTERVAL: 30000,
  RECONNECT_MAX_ATTEMPTS: Infinity,
  RECONNECT_MULTIPLIER: 1.5,
  MESSAGE_QUEUE_MAX_SIZE: 100,
  MESSAGE_QUEUE_FLUSH_INTERVAL: 5000,
};


export const useWebSocketStore = defineStore("webSocketStore", {
  state: () => ({
    socket: null,
    peer: null,
    connectionState: "disconnected", // 'connecting', 'connected', 'disconnecting', 'error'
    reconnectAttempts: 0,
    sessionId:null,//当前会话id
    messages: [],
    groupMembersList:{},//群成员列表
    toUserInfo: {}, // 会话目标信息
    toUserAudioInfo: {}, // 会话目标音频信息
    unreadMessages: [],
    uuid: null,
    onMessageCallbacks: [],
    messageQueue: [],
    lastActivityTime: 0,
    stats: {
      sentMessages: 0,
      receivedMessages: 0,
      failedMessages: 0,
      reconnects: 0,
    },
    heartbeat: {
      timer: null,
      timeout: null,
      retryCount: 0,
    },
    reconnect: {
      timer: null,
      currentAttempt: 0,
    },
    queueFlushTimer: null,
    loading:false,
    applyfriend:{},//好友申请数据
    unread:false,//判断有无好友申请
    chatDelAuth: {}, //控制会话权限
    chatGroupAuth: {}, // 群会话权限
    chatRefresh:0,//强制刷新会话列表
    needRefreshIm:0,//软刷新会话列表
    indexs:0,// 接收消息计数器
    isassign:'',//是否@自己
  }),

  persist: {
    key: "toUserInfo",
    storage: localStorage,
    paths: ["toUserInfo", "uuid"],
    serializer: {
      serialize: (state) =>
        JSON.stringify({
          toUserInfo: state.toUserInfo,
          uuid: state.uuid,
        }),
      deserialize: (str) => {
        const data = JSON.parse(str);
        return {
          toUserInfo: data.toUserInfo || {},
          uuid: data.uuid || null,
        };
      },
    },
  },

  getters: {
    isConnected(state) {
      return state.connectionState === "connected";
    },
    hasUnreadMessages(state) {
      return state.unreadMessages.length > 0;
    },
    connectionStatus(state) {
      return state.connectionState;
    },
  },

  actions: {
    // 监听前后台切换
    changeAppState(state) { 
      // if(state){
      //   // 前台
      // }
      // else {
      //   // 后台
      // }
      // 检测是否断开连接
      if(!this.isConnected){
        console.warn("前后台切换Websocket 已断开重新连接");
        this.disconnect();
        this.connect(this.uuid);
      }
    },
    // 监听网络变化
    changeNetworkState(state) { 
      // 检测是否断开连接
      if(!this.isConnected){
        console.warn("网络波动Websocket 已断开重新连接");
        this.disconnect();
        this.connect(this.uuid);
      }
    },
    // 初始化连接
    connect(userUuid, callback) {
      if (!userUuid) {
        console.error("连接失败: 缺少 userUuid");
        return;
      }

      // 如果正在连接或已连接，则先断开
      if (
        this.connectionState === "connected" ||
        this.connectionState === "connecting"
      ) {
        this.disconnect();
      }

      this.uuid = userUuid;
      this.connectionState = "connecting";
      this.stats.reconnects++;

      try {
        const wsUrl = `${import.meta.env.VITE_PRO_IM_WSS}?user=${userUuid}`;
        this.socket = new WebSocket(wsUrl);

        this.socket.onopen = () => {
          this.connectionState = "connected";
          this.reconnect.currentAttempt = 0;
          this.lastActivityTime = Date.now();
          this.startHeartbeat();
          this.startQueueFlush();

          if (callback && typeof callback === "function") {
            callback();
          }

          console.log("WebSocket 连接成功");
          this.flushMessageQueue(); // 连接成功后立即发送队列中的消息
        };

        this.socket.onmessage = (event) => {
          this.lastActivityTime = Date.now();
          this.handleMessage(event.data);
        };

        this.socket.onclose = () => {
          this.connectionState = "disconnected";
          this.cleanupTimers();

          if (
            this.reconnect.currentAttempt < WS_CONFIG.RECONNECT_MAX_ATTEMPTS
          ) {
            console.error("WebSocket被关闭, 重新连接");
            this.scheduleReconnect();
          }
        };

        this.socket.onerror = (error) => {
          this.connectionState = "error";
          console.error("WebSocket 错误并 重新连接:", error);
          this.cleanupTimers();
          this.scheduleReconnect();
        };
      } catch (error) {
        console.error("创建 WebSocket 失败并 重新连接:", error);
        this.connectionState = "error";
        this.scheduleReconnect();
      }
    },

    // 断开连接
    disconnect() {
      this.connectionState = "disconnecting";
      this.cleanupTimers();

      if (this.socket) {
        try {
          this.socket.close();
        } catch (e) {
          console.error("关闭 WebSocket 时出错:", e);
        }
        this.socket = null;
      }

      if (this.peer) {
        this.peer.close();
        this.peer = null;
      }

      this.connectionState = "disconnected";
    },

    // 清理所有定时器
    cleanupTimers() {
      if (this.heartbeat.timer) clearTimeout(this.heartbeat.timer);
      if (this.heartbeat.timeout) clearTimeout(this.heartbeat.timeout);
      if (this.reconnect.timer) clearTimeout(this.reconnect.timer);
      if (this.queueFlushTimer) clearInterval(this.queueFlushTimer);

      this.heartbeat.timer = null;
      this.heartbeat.timeout = null;
      this.reconnect.timer = null;
      this.queueFlushTimer = null;
      this.heartbeat.retryCount = 0;
    },

    // 启动心跳检测
    startHeartbeat() {
      this.cleanupHeartbeat();

      this.heartbeat.timer = setTimeout(() => {
        if (this.isConnected) {
          try {
            const pingMsg = {
              type: "heatbeat",
              content: "ping",
              timestamp: Date.now(),
            };

            this.sendRawMessage(pingMsg);

            // 设置响应超时检测
            this.heartbeat.timeout = setTimeout(() => {
              this.heartbeat.retryCount++;

              if (
                this.heartbeat.retryCount >= WS_CONFIG.HEARTBEAT_RETRY_LIMIT
              ) {
                console.error("心跳响应超时，关闭连接并重新连接");
                this.disconnect();
              } else {
                if(this.heartbeat.retryCount > 1){
                  console.warn(
                    `心跳无响应，第${this.heartbeat.retryCount - 1}次重试`
                  );
                }
                this.startHeartbeat(); // 重新发送心跳
              }
            }, WS_CONFIG.HEARTBEAT_TIMEOUT);
          } catch (error) {
            console.error("心跳发送失败:", error);
            this.scheduleReconnect();
          }
        }
      }, WS_CONFIG.HEARTBEAT_INTERVAL);
    },

    // 清理心跳定时器
    cleanupHeartbeat() {
      if (this.heartbeat.timer) clearTimeout(this.heartbeat.timer);
      if (this.heartbeat.timeout) clearTimeout(this.heartbeat.timeout);
      this.heartbeat.timer = null;
      this.heartbeat.timeout = null;
    },

    // 安排重连
    scheduleReconnect() {
      if (this.reconnect.timer) return;

      this.reconnect.currentAttempt++;

      // 指数退避算法计算重连间隔
      const delay = Math.min(
        WS_CONFIG.RECONNECT_BASE_INTERVAL *
          Math.pow(
            WS_CONFIG.RECONNECT_MULTIPLIER,
            this.reconnect.currentAttempt - 1
          ),
        WS_CONFIG.RECONNECT_MAX_INTERVAL
      );

      console.log(
        `将在 ${delay}ms 后尝试第 ${this.reconnect.currentAttempt} 次重连`
      );

      this.reconnect.timer = setTimeout(() => {
        this.reconnect.timer = null;
        if (!this.isConnected && this.uuid) {
          this.connect(this.uuid);
        }
      }, delay);
    },

    // 发送原始消息（不经过队列）
    sendRawMessage(messageData) {
      if (!this.isConnected) {
        throw new Error("WebSocket 未连接");
      }
      try {
        const MessageType = protobuf.lookupType("protocol.Message");
        const messagePB = MessageType.create(messageData);
        const buffer = MessageType.encode(messagePB).finish();
        this.socket.send(buffer);
        this.stats.sentMessages++;
        return true;
      } catch (error) {
        console.error("消息编码错误:", error);
        this.stats.failedMessages++;
        return false;
      }
    },

    // 发送消息（自动排队)
    sendMessage(messageData) {
      const walletStore = useWalletStore();

      // 构造完整消息
      const fullMessage = {
        to: this.toUserInfo.uuid,
        from: walletStore.account,
        ...messageData,
        fromUsername: walletStore.username,
        avatar: walletStore.avatar,
        timestamp: Date.now(),
      };

      // 如果连接正常，直接发送
      if (this.isConnected) {
        const success = this.sendRawMessage(fullMessage);
        if (success) {
          setMessageHook(fullMessage, this);
          return true;
        }
      }

      // 如果发送失败或未连接，加入队列
      if (this.messageQueue.length < WS_CONFIG.MESSAGE_QUEUE_MAX_SIZE) {
        this.messageQueue.push(fullMessage);
        console.log("消息已加入队列，等待发送");
        return true;
      } else {
        console.error("消息队列已满，丢弃消息");
        return false;
      }
    },

    // 启动队列刷新定时器
    startQueueFlush() {
      if (this.queueFlushTimer) return;

      this.queueFlushTimer = setInterval(() => {
        this.flushMessageQueue();
      }, WS_CONFIG.MESSAGE_QUEUE_FLUSH_INTERVAL);
    },

    // 发送队列中的所有消息
    flushMessageQueue() {
      if (!this.isConnected || this.messageQueue.length === 0) return;

      while (this.messageQueue.length > 0) {
        const message = this.messageQueue.shift();
        try {
          const success = this.sendRawMessage(message);
          if (success) {
            setMessageHook(message, this);
          } else {
            // 发送失败，重新放回队列开头
            this.messageQueue.unshift(message);
            break;
          }
        } catch (error) {
          console.error("发送队列消息失败:", error);
          this.messageQueue.unshift(message);
          break;
        }
      }
    },

    // 处理接收到的消息
    handleMessage(data) {
      const MessageType = protobuf.lookupType("protocol.Message");
      const reader = new FileReader();

      reader.onload = (event) => {
        try {
          const messagePB = MessageType.decode(
            new Uint8Array(event.target.result)
          );
          const message = MessageType.toObject(messagePB, {
            longs: String,
            enums: String,
            bytes: String,
          });

          this.stats.receivedMessages++;
          this.lastActivityTime = Date.now();
          handleMessageHook(message, this);

          // 调用所有回调函数
          this.onMessageCallbacks.forEach((cb) => {
            try {
              cb(message);
            } catch (e) {
              console.error("消息回调错误:", e);
            }
          });

          if (message.type === "heatbeat") {
            this.heartbeat.retryCount = 0; // 重置心跳重试计数
            return;
          }
        } catch (error) {
          console.error("消息解码错误:", error);
          this.stats.failedMessages++;
        }
      };

      reader.readAsArrayBuffer(data);
    },


    // ************功能*************//
    // 添加消息回调
    addOnMessageCallback(cb) {
      if (typeof cb === "function" && !this.onMessageCallbacks.includes(cb)) {
        this.onMessageCallbacks.push(cb);
      }
    },

    // 移除消息回调
    removeOnMessageCallback(cb) {
      this.onMessageCallbacks = this.onMessageCallbacks.filter(
        (item) => item !== cb
      );
    },

    // 新消息入栈本地
    pushMessage(message, sessionId = null) {
      const systemStore = useSystemStore();
      if(!sessionId){
        sessionId = message.from;
      } 
      if (!systemStore.messageList[sessionId]) {
        systemStore.messageList[sessionId] = [];
        if (sessionId == message.from){
          this.getMessages({ uuid: message.from, friendUsername: message.to, messageType: message.messageType },true);
        }
      }
      systemStore.messageList[sessionId].push(message);
      // 检测当前消息
      if (this.toUserInfo.uuid === sessionId) { 
        this.messages.push(message);
        this.indexs +=1;
      }
      console.log('pushMessage', systemStore.messageList, this.messages)
      // 更新会话最新消息
      this.updateSessionNewMessage(message, sessionId)
    },
    // 更新本地真实消息id
    modifyMessageId(message, msg, sessionId = null) { 
      const systemStore = useSystemStore();
      if(!sessionId){
        sessionId = message.from;
      }
      if (!systemStore.messageList[sessionId]) {
        systemStore.messageList[sessionId] = [];
      }
      systemStore.messageList[sessionId] = systemStore.messageList[sessionId].map(item => {
        if (!item.id && item.msgId + '' === msg?.msgId + '') return {...item, id: msg.id, msgId: undefined, err: !msg.id?true:undefined};
        if (item.id + '' === msg?.msgId + '') return {...item, content: "", url: ""};
        return item;
      });
      // 检测当前消息
      if (this.toUserInfo.uuid === sessionId) { 
        this.messages = this.messages.map(item => {
          if (!item.id && item.msgId + '' === msg?.msgId + '') return {...item, id: msg.id, msgId: undefined, err: !msg.id?true:undefined};
          if (item.id + '' === msg?.msgId + '') return {...item, content: "", url: ""};
          return item;
        });
      }
      // console.log("修改消息", message, sessionId, systemStore.messageList, this.toUserInfo.uuid, this.messages);
    },
    // 更新本地消息
    modifyMessage(message, msgId, sessionId = null) { 
      const systemStore = useSystemStore();
      if(!sessionId){
        sessionId = message.from;
      } 
      if (!systemStore.messageList[sessionId]) {
        systemStore.messageList[sessionId] = [];
      }
      systemStore.messageList[sessionId] = systemStore.messageList[sessionId].map(item => {
        if(typeof msgId === 'function'){
          let msg = {};
          if(msg = msgId(item, sessionId)){
            return {...item,...msg};
          }
        }
        else if (item.id + '' === msgId + '') return {...item, ...message, content: "", url: ""};
        return item;
      });
      // 检测当前消息
      if (this.toUserInfo.uuid === sessionId) { 
        this.messages = this.messages.map(item => {
          if(typeof msgId === 'function'){
            let msg = {};
            if(msg = msgId(item, sessionId)){
              return {...item,...msg};
            }
          }
          else if (item.id + '' === msgId + '') return {...item, ...message, content: "", url: ""};
          return item;
        });
      }
      // console.log('this.messages',this.messages)
    },
    // 删除本地消息
    deleteMessage(message, msgId, sessionId = null) { 
      const systemStore = useSystemStore();
      if(!sessionId){
        sessionId = message.from;
      } 
      if (!systemStore.messageList[sessionId]) {
        systemStore.messageList[sessionId] = [];
      }
      // 删除所有消息
      if (msgId === true || msgId === 'all') {
        systemStore.messageList[sessionId] = [];
        if (this.toUserInfo.uuid === sessionId) { 
          this.messages = [];
        }
        return;
      }
      // console.log("删除消息", message, sessionId, systemStore.messageList, this.messages);
      systemStore.messageList[sessionId] = systemStore.messageList[sessionId].filter(item => {
        if (item.id + '' === msgId + '') return false;
        return true;
      });
      // 检测当前消息
      if (this.toUserInfo.uuid === sessionId) { 
        this.messages = this.messages.filter(item => {
          if (item.id + '' === msgId + '') return false;
          return true;
        });
      }
    },
    // 发送消息已收到
    systemReceiptMessage(message, msg){
      if(!msg || !msg.uniqueId){
        return;
      }
      const response = {
        from: message.to,
        to: message.from,
        messageType: MsgType.MESSAGE_SYSTEM_RECEIPT,
        content: JSON.stringify({
          uniqueId: msg.uniqueId,
          timestamp: Date.now(),
        }),
      };
      console.log("systemReceiptMessage", response);
      this.sendMessage(response)
    },
    // 获取会话消息
    getSessionMessages(sessionId) { 
      const systemStore = useSystemStore();
      if (!systemStore.messageList[sessionId]) {
        systemStore.messageList[sessionId] = [];
      }
      return [...systemStore.messageList[sessionId]];
    },
    // 设置当前会话消息
    setSessionMessages(sessionId, messages,all=false) { 
      const systemStore = useSystemStore();
      let data = Array.isArray(messages) ? messages : (typeof messages === 'object' ? [messages] : []);
      if (!systemStore.messageList[sessionId]) {
        systemStore.messageList[sessionId] = [];
      }
      if(all){
        systemStore.messageList[sessionId] =  data.filter(val=>!systemStore.messageList[sessionId].find(v=>v.id == val.id))
        return;
      }
      systemStore.messageList[sessionId] = data;
    },
    // 更换会话
    changeSessionMessage(sessionId) { 
      this.sessionId = sessionId;
      this.messages = this.getSessionMessages(sessionId);
    },

    // 获取历史消息
    async getMessages(params,all=false) {
      const router = useRouter();
      const systemStore = useSystemStore();
      this.loading = true  // 开始加载
      this.changeSessionMessage(params.uuid);
      if (this.messages.length > 0 && !all) {
        this.loading = false;
        return;
      }
      try {
        const res = await getMessageApi({
          messageType: params.messageType,
          uuid: params.uuid,
          friendUsername: params.friendUsername,
        });
        if(res.code == 200){
          this.setSessionMessages(this.sessionId, (res.data || []), all);
          this.changeSessionMessage(this.sessionId);
          // return this.messages;
        }else{
          showDialog({
            title: '提示',
            message: res.msg,
            confirmButtonColor:"#4765dd",
          }).then(() => {
            systemStore.needRefreshIm = true;
            router.back();
          });
        }
      } catch (error) {
        console.error("获取消息失败:", error);
        throw error;
      } finally {
        this.loading = false // 结束加载
      }
    },
    // 更新会话列表消息
    updateSessionNewMessage(message, sessionId, msg = null) { 
      console.log("更新会话列表消息:", message, sessionId, msg);

      // 过滤接收的系统消息
      if (MsgType.MSG_SYSTEM_GROUP.includes(message.messageType)){
        return;
      }

      const systemStore = useSystemStore();
      let index = systemStore.ImsessionList.findIndex(val=> val.uuid == sessionId);
      // 已读未读
      let unReadNum = 0;
      const ts = message.timestamp || Math.floor(Date.now());

      const time = new Date(ts).toLocaleString().replaceAll("/", "-");
      // 消息类型映射
      // const mapSet = {
      //   [MsgType.MSG_TYPE.FILE]: '[文件]',
      //   [MsgType.MSG_TYPE.IMAGE]: '[图片]',
      //   [MsgType.MSG_TYPE.AUDIO]: '[音频]',
      //   [MsgType.MSG_TYPE.VIDEO]: '[视频]',
      //   [MsgType.MSG_TYPE.AUDIO_ONLINE]: '[语音通话]',
      //   [MsgType.MSG_TYPE.VIDEO_ONLINE]: '[视频通话]',
      //   // [Constant.CANCELL_AUDIO_ONLINE]:'[通话结束]',
      //   // [Constant.REJECT_AUDIO_ONLINE]: '[对方拒绝]',
      //   // [Constant.CANCELL_VIDEO_ONLINE]: '[通话结束]',
      //   // [Constant.REJECT_VIDEO_ONLINE]: '[对方拒绝]',
      // };
      // 检测最新消息
      // let lastMsg = message.contentType === MsgType.MSG_TYPE.TEXT || message.contentType === MsgType.MSG_TYPE.NOTICE ? (msg?msg.content : message.content) : (mapSet[message.contentType] || '[语音视频]');
      let lastMsg = msg ? msg.content : message.content;
      // 阅后即焚消息
      if(message.isTemp){
        lastMsg = '[阅后即焚]';
      }
      // 额外数据
      const ext = {
        updatedAt: time,
      };
      // 修改群公告信息
      if (message.nickname) {
        ext.sessionName = message.nickname
      }
      if (message.notice) {
        ext.notice = message.notice
      }
      if (message.slience || message.slience === 0) {
        ext.slience = message.slience
      }
      if (message.stick || message.stick === 0) {
        ext.stick = message.stick
      }
      // 补充消息完整性

      // 更新并排序
      if(index >= 0){
        systemStore.ImsessionList = [...systemStore.ImsessionList].map((item)=>{
          if (item.uuid == sessionId){
            // console.log('111', item, lastMsg, lastMsg,item.message)
            return { ...item, ...ext, unReadNum: item.unReadNum + 1, message: lastMsg || item.message};
          }
          return item;
        }).sort((a, b) => b.stick - a.stick || new Date(b.updatedAt) - new Date(a.updatedAt));
        // 软刷新会话列表
        this.needRefreshIm += 1;
        return;
      }
      // 强制刷新会话列表
      this.chatRefresh += 1;
    },


    // ************ 接收方 方法 ************//
    // 监听好友系统消息
    listenFriendSystem(message) { 
      // 好友申请
      if (message.messageType == MsgType.MESSAGE_APPLY_FRIEND) {
        this.addFriendApply(message.from);  
      }
      // 好友通过
      if (message.messageType == MsgType.MESSAGE_PASS_FRIEND) {
        // 移除好友申请记录
        this.deleteFriendApply(message.from);
        // 恢复会话功能
        this.funRestoreDelAuth(message.from);
        // 需要更新会话或创建会话
        this.chatRefresh += 1;
      }
      // 好友删除
      if (message.messageType == MsgType.MESSAGE_DELETE_FRIEND) {
        // 禁用会话功能
        this.funDeleteDelAuth(message.from);
        // 需要删除会话

        // 删除本地消息记录
        this.deleteMessage(message, true);
      }
    },
    // 监控群系统消息
    listenGroupSystemMessage(message, msg = null) { 
      console.log('群系统消息', message, msg);
      // 解散群/提出群/退群
      if (message.messageType == MsgType.DELETE_GROUP || message.messageType == MsgType.REMOVE_GROUP || message.messageType == MsgType.EXIT_GROUP) {
        // 如果存在于users中(被提出或退出的人)或者解散群
        if ((msg && msg.users && msg.users.includes(message.to)) || message.messageType == MsgType.DELETE_GROUP) {
          // 禁用会话功能
          this.funDeleteDelAuth(message.from);
          // 删除会话
          this.deleteSessionChat(message.from);
        }
      }
      // 创建群/加入群/邀请入群
      if (message.messageType == MsgType.CREATE_GROUP || message.messageType == MsgType.JION_GROUP || message.messageType == MsgType.INVITATION_GROUP) {
        // console.log('群系统消息', message, msg);
        if (message.messageType == MsgType.JION_GROUP || message.messageType == MsgType.INVITATION_GROUP) {
          // 恢复会话功能
          this.funRestoreDelAuth(message.from);
        }
        // 刷新会话列表
        // this.needRefreshIm += 1;
      }
      // 群通知
      if (message.messageType == MsgType.MESSAGE_NOTICE_GROUP) {
        // 更新群名称和群公告
        this.funGroupNotice(msg);
      }
      // 处理群置顶
      if (message.messageType === MsgType.MESSAGE_STICKY_GROUP) {
      }
      // 更新群成员列表
      this.fetchGroupMembers(message.from,true);
      // 处理@群成员
      if (message.messageType == MsgType.MESSAGE_CC_GROUP){
        let ccArr = msg?.cc.split(',');
        if (this.groupMembersList && this.groupMembersList[message.from]) {
          this.isassign = this.groupMembersList[message.from].filter(val => ccArr.includes(val.userId + '')).find(val => val.uuid == message.to)
        }
      } 
      // 处理群个人昵称
      if (message.messageType == MsgType.MESSAGE_NICKNAME_GROUP){
        this.modifyMessage(message,(val)=>{
          return msg.uuid == val.fromUuid?{
            fromUsername: msg.name
          } : (msg.uuid == val.toUuid ? {
            toUsername: msg.name
          }:{})
        })
      }
    },

    // 语音视频通知
    // 群通知更新群名称和公告
    funGroupNotice(msg){
      this.toUserInfo = {
        ...this.toUserInfo,
        // 群公告
        notice: msg && msg.notice?msg.notice: this.toUserInfo.notice,
        nickname: msg && msg.name?msg.name:this.toUserInfo.nickname,
        // 群名称
        sessionName: msg && msg.name?msg.name:this.toUserInfo.sessionName,
      }
    },
    // 群消息置顶
    funGroupTop(message = null) { 
    },

    // ************ 发送方 方法 ************//
    // 同意或者拒绝好友操作
    funApprovalFriend(message){
      if (message.messageType == MsgType.MESSAGE_REJECT_FRIEND || message.messageType == MsgType.MESSAGE_PASS_FRIEND) {
        // 删除申请记录
        this.deleteFriendApply(message.to);
        // 恢复会话权限
        this.funRestoreDelAuth(message.to);
        // 刷新/更新会话列表
        this.chatRefresh += 1;
      }
      this.funDeleteFriend(message)
    },
    // 删除好友操作
    funDeleteFriend(message) { 
      if (message.messageType == MsgType.MESSAGE_DELETE_FRIEND) {
        // 禁用会话功能
        this.funDeleteDelAuth(message.to);
        // 删除本地消息记录
        this.deleteMessage(message, true,message.to);
        // 更新会话列表
      }
    },



    // ************ 公用 ************//
    // 删除好友申请记录
    deleteFriendApply(uuid){
      if (this.applyfriend[uuid]) {
        delete this.applyfriend[uuid]
      }
      this.unread = Object.keys(this.applyfriend).length > 0;
    },
    // 更新好友申请记录
    updateFriendApply(list){
      Array.isArray(list) && list.forEach(val=>{
        if (typeof val == 'string'){
          this.applyfriend[val] = 1;
          return;
        }
        this.applyfriend[val.uuid] = 1
      });
      this.unread = Object.keys(this.applyfriend).length > 0;
    },
    // 添加好友申请记录
    addFriendApply(uuid){ 
      this.applyfriend[uuid] = 1;
      this.unread = true;
    },
    // 初始化好友申请记录
    async funInitfriend(uuid){
      if (Object.keys(this.applyfriend).length > 0){
        this.unread = true;
        return
      };
      const res = await friendRequest({ uuid, status: 1,state:1 });
      this.updateFriendApply(res.data || []);
      // if (res.data && res.data.length > 0){
      //   res.data.forEach(val=>{
      //     this.applyfriend[val.uuid] = 1
      //   })
      // }
      // this.unread = res.data && res.data.length > 0;
    },
    // 初始化用户群权限
    async funInitGroupAuth(uuid){
    },
    // 更新用户群权限
    updateGroupAuth(data){ 
      Array.isArray(data) && data.forEach(item=>{
        if(typeof item === 'string'){
          this.chatGroupAuth[item] = 1;
          return;
        }
        this.chatGroupAuth[item.uuid] = 1
      });
      console.log(this.chatGroupAuth)
    },
    // 校验会话权限
    verifyChatAuth(uuid){
      if(this.chatDelAuth[uuid] && !this.chatGroupAuth[uuid]){
        return false;
      }
      return true;
    },
    //恢复会话权限
    funRestoreDelAuth(uuid) {
      if (this.chatDelAuth[uuid]) {
        delete this.chatDelAuth[uuid]
      }
      this.chatGroupAuth[uuid] = 1;
    },
    // 禁用会话权限
    funDeleteDelAuth(uuid){
      this.chatDelAuth[uuid] = 1;
      if(this.chatGroupAuth[uuid]){
        delete this.chatGroupAuth[uuid]
      }
    },
    // 更新会话未读状态
    funUpdateUnread(uuid) {
      const systemStore = useSystemStore();
      let index = systemStore.ImsessionList ? systemStore.ImsessionList.findIndex(s => (s.uuid || s.id) === uuid) : -1;
      if (index > -1) {
        systemStore.ImsessionList[index].unReadNum = 0;
      }
    },
    // 删除会话列表
    deleteSessionChat(uuid) {
      const systemStore = useSystemStore();
      let sessions = systemStore.ImsessionList ? [...systemStore.ImsessionList] : [];
      let index = sessions.findIndex(s => (s.uuid || s.id) === uuid);
      if (index > -1) {
        sessions.splice(index, 1);
        systemStore.ImsessionList = sessions;
      }
    },
    // 群成员列表
    async fetchGroupMembers(uuid,force = false) {
      // if (this.toUserInfo.type !== 'group') {
      //   return []
      // }

      // 如果已有缓存且不强制刷新，直接返回
      if (!force && this.groupMembersList[uuid]) {
        return this.groupMembersList[uuid]
      }

      try {
        const res = await groupList(uuid)
        const members = res.data || []
        // 更新缓存
        this.groupMembersList[uuid] = members
        return members
      } catch (e) {
        console.error('获取群成员失败', e)
        return []
      }
    },
    // 清除数据
    deleteData(){
      const systemStore = useSystemStore();
      systemStore.messageList = {};
      this.messages = [];
      this.groupMembersList = {};
      this.toUserInfo = {};
      this.messageQueue = [];
      systemStore.ImsessionList = [];
      this.onMessageCallbacks = [];
      this.applyfriend = {};
      this.unread = false;
      this.chatDelAuth = {};
      this.chatGroupAuth = {};
      this.chatRefresh = 0;
      this.needRefreshIm = 0;
      this.indexs = 0;
      this.isassign = false;
      this.disconnect();
    }
  },
});
