import store from '..'
import { titleNotify } from '../../utils'
import { filterCallingMessage } from '../../utils/common'
import { getOpenIM } from '@/utils/openIM';
import da from "element-ui/src/locale/lang/da";

const OpenIM = getOpenIM();
const conversationModules = {
  state: {
    currentConversation: {},
    currentMessageList: [],
    nextReqMessageID: '',
    isCompleted: false, // 当前会话消息列表是否已经拉完了所有消息
    conversationList: [],
    callingInfo: {
      memberList: [],
      type: 'C2C',   //C2C，GROUP
    },
    audioCall: false,
    isShowConversationList: false,
    selectedMessageList:[],
    relayType: 1,   // 1: 转发  2: 逐条转发 3: 合并转发
    mergerMessageList: [],
    mergerMessage: {},
    relayMessage: {},
    selectMessage: false,
    orderType:null,//1 图文 2视频
    ordreId:null,
    imType:0,//1问诊 2随访

  },
  getters: {
    toAccount: state => {
      if (!state.currentConversation) return '';
      if (state.currentConversation.conversationID) {
        return state.currentConversation.conversationID.split("_").find(part => part.includes('U'));
      }
    },
    currentConversationType: state => {
      if (!state.currentConversation || !state.currentConversation.conversationType) {
        return ''
      }
      return state.currentConversation.conversationType
    },
    totalUnreadCount: state => {
      const result = state.conversationList.reduce((count, conversation) => {
        // 当前会话不计算总未读
        if (!store.getters.hidden && state.currentConversation.conversationID === conversation.conversationID) {
          return count
        }
        return count + conversation.unreadCount
      }, 0)
      titleNotify(result)
      return result
    },
    // 用于当前会话的图片预览
    imgUrlList: state => {
      console.log("state.currentMessageList",state.currentMessageList)
      return state.currentMessageList
        .filter(message => message.contentType === 102) // 筛选出没有撤回并且类型是图片类型的消息
        .map(message => message.pictureElem.sourcePicture.url)
    }
  },
  mutations: {
    setImType(state, value) {
      state.imType = value
    },
    /**
     * 显示trtcCalling 群通话成员列表
     * @param {Object} state
     * @param {Conversation} setCallingList
     */
    setCallingList(state, value) {
      state.callingInfo.memberList = value.memberList
      state.callingInfo.type = value.type
    },

    /**
     * 显示trtcCalling 语音通话
     * @param {Object} state
     * @param {Conversation} showAudioCall
     */

    showConversationList(state, value) {
      state.isShowConversationList = value
    },
    setSelectedMessageList(state, value) {
      state.selectedMessageList = value
    },
    setRelayType(state, value) {
      state.relayType = value
    },
    setMergerMessage(state, value) {
      state.mergerMessage = value
      state.mergerMessageList = [...state.mergerMessageList, value]
    },
    setRelayMessage(state, value) {
      state.relayMessage = value
    },
    updateMergerMessage(state, value) {
      state.mergerMessage = value
      state.mergerMessageList.pop()

    },
    setSelectedMessage(state, value) {
      state.selectMessage = value
    },
    resetSelectedMessage(state, value) {
      state.selectMessage = value
      Object.assign(state, {
        selectedMessageList: [],
      })
    },
    resetMergerMessage(state, value) {
      state.mergerMessagePop = value
      Object.assign(state, {
        mergerMessage: {},
        mergerMessageList: [],
      })
    },
    /**
     * 显示trtcCalling 语音通话
     * @param {Object} state
     * @param {Conversation} showAudioCall
     */

    showAudioCall(state, value) {
      state.audioCall = value
    },

    /**
     * 更新当前会话
     * 调用时机: 切换会话时
     * @param {Object} state
     * @param {Conversation} conversation
     */
    updateCurrentConversation(state, conversation) {
      state.currentConversation = conversation
      state.currentMessageList = []
      state.nextReqMessageID = ''
      state.isCompleted = false
    },
    /**
     * 更新会话列表
     * 调用时机：触发会话列表更新事件时。C
     *
     * @param {Object} state
     * @param {Conversation[]} conversationList
     */
    updateConversationList(state, conversationList) {
      console.log("获取会话列表")
      console.log("conversationList",conversationList)
      /*conversationList.forEach(function(item) {
          console.log(item)
        const latestMsgObj = JSON.parse(item.latestMsg);
          if(latestMsgObj.textElem.content!=null&&latestMsgObj.textElem.content!=""){
            // try{
            //   var json=JSON.parse(item.lastMessage.cloudCustomData);
            // }
            // catch(e){
            // }
          }
      });*/
      /*const userIds = conversationList
        .map(conv => {
          const parts = conv.conversationID?.split("_");
          if (!parts) return null;
          // 查找包含"U"的部分（假设用户ID格式类似"U123"）
          const userPart = parts.find(part => part.includes('U'));
          return userPart || null;
        })
        .filter(Boolean);

      if (userIds.length === 0) return;

      // 批量获取用户信息
      return OpenIM.getUsersInfo(userIds)
        .then(({ data: userInfos }) => {
          console.log("用户信息列表", userInfos);

          // 创建用户信息映射表
          const userMap = {};
          userInfos.forEach(user => {
            userMap[user.userID] = user;
          });

          // 更新会话列表中的用户信息
          const updatedList = conversationList.map(conv => {
            const parts = conv.conversationID?.split("_");
            const userId = parts && parts.length > 2 ? parts.find(part => part.includes('U')) : null;
            if (userId && userMap[userId]) {
              return {
                ...conv,
                faceURL: userMap[userId].faceURL,
                showName: userMap[userId].nickname
              };
            }
            return conv;
          });

          state.conversationList = updatedList
        });*/
      state.conversationList = conversationList
    },
    /**
     * 重置当前会话
     * 调用时机：需要重置当前会话时，例如：当前会话是一个群组，正好被踢出群时（被踢群事件触发），重置当前会话
     * @param {Object} state
     */
    resetCurrentConversation(state) {
      state.currentConversation = {}
    },
    /**
     * 将消息插入当前会话列表
     * 调用时机：收/发消息事件触发时
     * @param {Object} state
     * @param {Message[]|Message} data
     * @returns
     */
    pushCurrentMessageList(state, data) {
      // 还没当前会话，则跳过
      console.log("触发消息列表更新",state.currentConversation)
      if (!state.currentConversation.conversationID) {
        return
      }
      console.log("会话详细信息",state.currentConversation)
      console.log("消息详细信息",data)
      if (Array.isArray(data)) {
        // 筛选出当前会话的消息
        const result = data.filter(item => item.recvID===JSON.parse(state.currentConversation.latestMsg).recvID&& item.sendID === JSON.parse(state.currentConversation.latestMsg).sendID)
        console.log("收到消息1")
        console.log("state.currentConversation.conversationID会话id",state.currentConversation.conversationID)
        console.log("result[0]",result[0])
        if(result[0].ex!=null&&result[0].ex!=""){
          try{
            var json=JSON.parse(result[0].ex);
            console.log("消息json",json)
            if(json.type!=null&&json.type!=""){
              state.type=json.type;
              state.orderId=json.orderId;
              state.imType=json.imType;
              state.followId=json.followId;
              state.orderType=json.orderType;
            }
          }
          catch(e){
          }
        }
        state.currentMessageList = [...state.currentMessageList, ...result]
        filterCallingMessage(state.currentMessageList)
      //} else if ("si_"+data.sendID+"_"+data.recvID === state.currentConversation.conversationID) {
      } else if (data.recvID===JSON.parse(state.currentConversation.latestMsg).recvID&& data.sendID === JSON.parse(state.currentConversation.latestMsg).sendID) {
        console.log("会话id22222",state.currentConversation.conversationID)
        state.currentMessageList = [...state.currentMessageList, data]
        console.log("收到消息2")
        console.log(data)
        if(data.ex!=null&&data.ex!=""){
          var json=JSON.parse(data.ex);
          console.log(json)
          try{
            if(json.type!=null&&json.type!=""){
              state.type=json.type;
              state.orderId=json.orderId;
              state.imType=json.imType;
              state.followId=json.followId;
              state.orderType=json.orderType;
            }
          }
          catch(e){
          }
        }
        filterCallingMessage(state.currentMessageList)
      }
    },
    /**
     * 从当前消息列表中删除某条消息
     * @param {Object} state
     * @param {Message} message
     */
    removeMessage(state, message) {
      const index = state.currentMessageList.findIndex(({ ID }) => ID === message.ID)
      if (index >= 0) {
        state.currentMessageList.splice(index, 1)
      }
    },
    reset(state) {
      Object.assign(state, {
        currentConversation: {},
        currentMessageList: [],
        nextReqMessageID: '',
        isCompleted: false, // 当前会话消息列表是否已经拉完了所有消息
        conversationList: []
      })
    }
  },
  actions: {

    /**
     * 获取消息列表
     * 调用时机：打开某一会话时或下拉获取历史消息时
     * @param {Object} context
     * @param {String} conversationID
     */
    async getMessageList(context, conversationID) {
      if (context.state.isCompleted) {
        context.commit('showMessage', {
          message: '已经没有更多的历史消息了哦',
          type: 'info'
        })
        return
      }

      const { currentMessageList, lastClientMsgID } = context.state

      try {
        // 调用 OpenIM 的历史消息接口
        const res = await OpenIM.getAdvancedHistoryMessageList({
          conversationID: conversationID,
          count: 100,
          startClientMsgID: lastClientMsgID || '', // 第一次为空
          lastMinSeq: 0,
          viewType:0
        })

        let messageList = res.data.messageList || []
        //过滤掉双方成为好友通知
        messageList = messageList.filter(message => message.contentType !== 1201)
        console.log("q切换会话获取聊天记录",messageList)
        if (messageList.length === 0) {
          context.state.isCompleted = true
          context.commit('showMessage', {
            message: '已经没有更多的历史消息了哦',
            type: 'info'
          })
          return
        }

        // 更新 lastClientMsgID 为本次最早的消息，用于下次分页
        context.state.lastClientMsgID = messageList[0].clientMsgID
        // 插入历史消息到前面
        console.log("messageList",messageList)
        context.state.currentMessageList = [...messageList, ...currentMessageList]

        console.log(context.state.currentMessageList)
        // 过滤通话相关消息（如有）
        //filterCallingMessage(context.state.currentMessageList)
      } catch (error) {
        console.error('获取历史消息失败:', error)
        context.commit('showMessage', {
          message: '获取历史消息失败',
          type: 'error'
        })
      }
    },
    /**
     * 切换会话
     * 调用时机：切换会话时
     * @param {Object} context
     * @param {String} conversationID
     */
    checkoutConversation(context, conversation) {
      console.log("conversation",conversation)

      context.commit('resetCurrentMemberList')
      context.commit('resetSelectedMessage', false)
      context.commit('resetFriendContent')
      /*console.log("用户id"+context.state.currentConversation.userID)
      console.log("会话类型"+context.state.currentConversation.conversationType)
      console.log("会话id"+context.state.currentConversation.conversationID)*/
      // 1.切换会话前，将切换前的会话进行已读上报
      //if (context.state.currentConversation.conversationID) {
        //console.log("标记切换前会话为已读",context.state.currentConversation)
        const prevConversationID = context.state.currentConversation.conversationID
        OpenIM.markConversationMessageAsRead(prevConversationID).then(({ data }) => {
          // 调用成功
        })
          .catch(({ errCode, errMsg }) => {
            if (errCode !== 10303) {
              console.error("标记已读失败");
            }
          });
        /*OpenIM.getOneConversation({
          sourceID: context.state.currentConversation.userID,
          sessionType: context.state.currentConversation.conversationType,
        }).then(({ data }) => {
          console.log("当前会话未读数量",data.unreadCount)

          /!*if (data.unreadCount>0){
            OpenIM.markConversationMessageAsRead(prevConversationID)
          }*!/
        })
          .catch(({ errCode, errMsg }) => {
            // 调用失败
          });*/
      //}
      //console.log("标记待切换会话为已读",conversation.conversationID)
      // 2.待切换的会话也进行已读上报
      OpenIM.markConversationMessageAsRead(conversation.conversationID).then(({ data }) => {
        // 调用成功
      })
        .catch(({ errCode, errMsg }) => {
          if (errCode !== 10303) {
            console.error("标记已读失败");
          }
        });
      /*console.log("context.state.currentConversation",context.state.currentConversation)
      console.log("conversation",conversation)*/

      /*OpenIM.getOneConversation({
        sourceID: conversation.userID,
        sessionType: conversation.conversationType,
      }).then(({ data }) => {
        console.log("下一个会话未读数量",data.unreadCount)

        /!*if (data.unreadCount>0){

          // 2.待切换的会话也进行已读上报
          OpenIM.markConversationMessageAsRead(conversation.conversationID)
        }*!/
      })
        .catch(({ errCode, errMsg }) => {
          // 调用失败
        });*/

      // 3. 获取会话信息
      return OpenIM.getOneConversation({
        sourceID:conversation.userID,
        sessionType:conversation.conversationType
      }).then(({ data }) => {
        console.log("获取会话信息",data);
        console.log(data);
        context.state.lastClientMsgID = ''
        context.state.currentMessageList = []
        context.state.isCompleted = false
        console.log("ex的值",data.ex)
        if(data.ex){
          try{
            context.state.imType=JSON.parse(data.ex).imType;
            context.state.orderId=JSON.parse(data.ex).orderId;
            context.state.orderType=JSON.parse(data.ex).orderType;
            context.state.followId=JSON.parse(data.ex).followId;
            context.state.type=JSON.parse(data.ex).type;
          }
          catch(e){
          }
        }else{
          console.log("m没有ex")
          context.state.imType=''
          context.state.orderId='';
          context.state.orderType='';
          context.state.followId='';
          context.state.type='';
        }
        OpenIM.getAllConversationList()
          .then(({ data }) => {
            // 调用成功
            console.log("--------------------------------------------------------------------------------------------------------------------")
            console.log(data)
            context.commit('updateConversationList', data)
          })
          .catch(({ errCode, errMsg }) => {
            // 调用失败
          })
        // 3.1 更新当前会话
        context.commit('updateCurrentConversation', data)
        // 3.2 获取消息列表
        context.dispatch('getMessageList', conversation.conversationID)
        // 3.3 拉取第一页群成员列表
        if (data.conversationType === 4) {
          return context.dispatch('getGroupMemberList', data.groupID)
        }
        return Promise.resolve()
      })
    }
  }
}

export default conversationModules
