import Vue from 'vue'
import nedb from '../../db/nedb'
import base64 from '@/utils/base64'
import bus from '@/utils/bus'

import { Message } from 'element-ui'
import { TriggerConversationPushTask } from '@/api/webSocketApi'

/**
 * Json数组去重
 * @param {Array} arr
 */
function unique(arr) {
  for (let i = 0; i < arr.length; i++) {
    for (let j = i + 1; j < arr.length; j++) {
      if (arr[i].RemoteId === arr[j].RemoteId) {
        // 第一个等同于第二个，splice方法删除第二个
        arr.splice(j, 1)
        j--
      }
    }
  }
  return arr
}

function uniqueMessages(arr) {
  for (let i = 0; i < arr.length; i++) {
    for (let j = i + 1; j < arr.length; j++) {
      if (arr[i].MsgId === arr[j].MsgId) {
        // 第一个等同于第二个，splice方法删除第二个
        arr.splice(j, 1)
        j--
      }
    }
  }
  return arr
}

/**
 * 获取消息的内容
 * @param {Object} talk 消息
 */
function getContent(talk) {
  let digest = ''
  switch (talk.ContentType) {
    case 'Text':
      digest = base64.decode(talk.Content)
      //   if (talk.FriendId.indexOf('@chatroom') > 0 || talk.FriendId.indexOf('@im.chatroom') > 0) {
      if (talk.Members) {
        digest = unescape(escape(digest.replace(/.*?:/, '')).replace('%0A', '%20')).replace(' ', '')
      }
      break
    case 'Picture':
    case 2:
      digest = '[图片]'
      break
    // 语音 3
    case 'Voice':
    case 3:
      digest = '[语音]'
      break
    // 视频 4
    case 'Video':
    case 4:
      digest = '[视频]'
      break
    // 系统消息 5
    case 'System':
    case 5:
      try {
        digest = base64.decode(talk.Content)
      } catch (error) {
        digest = '[系统消息]'
      }
      break
    // 链接消息 6
    case 'Link':
    case 6:
      digest = '[链接]'
      break
    // 扩展的链接消息（小程序分享等），内容为xml格式，暂未使用 7
    case 'LinkExt':
    case 7:
      digest = '[扩展的链接消息]'
      break
    // 文件 8
    case 'File':
    case 8:
      digest = '[文件]'
      break
    // 名片 9
    case 'NameCard':
    case 9:
      digest = '[名片]'
      break
    // 位置信息 10
    case 'Location':
    case 10:
      digest = '[位置消息]'
      break
    // 红包 11
    case 'LuckyMoney':
    case 11:
      digest = '[链接]'
      break
    // 转账 12
    case 'MoneyTrans':
    case 12:
      digest = '[红包]'
      break
    // 小程序 13
    case 'WeApp':
    case 13:
      digest = '[小程序]'
      break
    // Emoji 14
    case 'Emoji':
    case 14:
      digest = '[Emoji]'
      break
    // 群管理消息 15
    case 'RoomManage':
    case 15:
      digest = '[群管理消息]'
      break
    // 红包系统消息 16
    case 'Sys_LuckyMoney':
    case 16:
      digest = '[红包系统消息]'
      break
    // 群系统消息 17
    case 'RoomSystem':
    case 17:
      digest = '[群系统消息]'
      break
    // 拍一拍消息
    case 'PaiYiPai':
    case 26:
      digest = '[群系统消息]'
      try {
        digest = base64.decode(talk.Content)
      } catch (error) {
        digest = '[拍一拍]'
      }
      break
    // 不支持的消息
    default:
      digest = '[不支持的消息]'
      break
  }
  return digest
}

// initial state
const state = {
  // ============== AsidePage用到的变量 ==============
  wechats: [], // 当前用户绑定的微信
  currentWechat: {}, // 会话页面选中的微信

  conversations: {}, // 每个微信的会话
  currentCustomers: [], // 我的客户
  currentContacts: [], // 企业联系人
  allCustomers: [], // 所有的我的客户
  allContacts: [], // 所有的企业联系人
  currentFriends: {}, // 会话页面每个微信选中的好友

  // ============== ConversationFriends用到的变量 ====
  departments: [], // 当前的部门列表
  corporations: [], // 客户公司信息

  lastChatPages: {}, // ConversationFriends页面的tab页面回显
  addressListPages: {}, // ConversationFriends页面的tab页面回显
  chatRoomPages: {}, // ConversationFriends页面的tab页面回显
  // ============== ConversationChats用到的变量 =======
  currentChats: {
    Count: 0, // 消息数
    Messages: [], // 会话列表
    Size: 0, // 固定20
    ConvId: '', // 会话的remoteid
    WxId: '', // 微信id
    Page: 0, // 页
    HasMore: false //
  }, // 会话页面的会话列表

  content: '', // 当前要发送的内容， 默认为空
  remark: '', // 要@的群成员的id
  contentType: 'Text', // 当前要发送的消息类型，默认为文本
  url: '', // 大图的url
  hbDetailVisible: false, // 显示红包详情
  hbDetail: {
    WeChatId: '', // 所属微信号
    Success: false,
    ErrMsg: '',
    HbUrl: '', //
    TotalNum: null, // 红包总个数
    TotalAmount: null, // 红包总金额
    RecNum: null, // 已收红包个数
    Records: [], // 已收红包个数
    RecAmount: null // 已收红包金额
  }, // 红包详情
  // ============== ConversationTools用到的变量 =======
  userLabels: {} // 标签
  // contactMessage: ['AcctId', 'Alias', 'Attr', 'Avatar', 'DepartIds', 'Gender', 'Name', 'RemoteId']
}

// getters
const getters = {
  // 当前账号绑定的微信列表 排序后的
  wechats: (state) => {
    let reWechats = []
    state.wechats.forEach((x) => {
      if (x.isonline === 0) {
        reWechats.push(x)
      }
    })
    state.wechats.forEach((x) => {
      if (x.isonline === 1) {
        reWechats.push(x)
      }
    })
    return reWechats
  },
  // 当前账号绑定的微信昵称Map(id-nick)
  wechatsNameMap: (state) => {
    const wm = {}
    state.wechats.forEach((e) => {
      wm[e.WxId] = e.Name
    })
    return wm
  },
  // 在线的微信
  wechatsOnline: (state) => {
    return state.wechats.filter((x) => x.isonline === 0)
  },
  // 会话页面选择的微信
  currentWechat: (state) => state.currentWechat,
  //   会话页面选择的微信id
  currentWeChatId: (state) => {
    return state.currentWechat.WxId || ''
  },
  // 当前微信的会话降序排列
  currentConvs: (state) => {
    if (state.conversations[state.currentWechat.WxId]) {
      const [...Convers] = state.conversations[state.currentWechat.WxId]
      // 按时间降序
      const pll = Convers.sort((a, b) => {
        return b.UpdateTime - a.UpdateTime
      })
      return pll
    }
    return []
  },
  // 每个设备的未读消息数统计
  messagesNotRead(state) {
    const mnr = {}
    const convs = state.conversations
    for (const key in convs) {
      if (Object.hasOwnProperty.call(convs, key)) {
        mnr[key] = 0
        for (const conv of convs[key]) {
          if (conv.UnreadCnt) {
            mnr[key] = mnr[key] + conv.UnreadCnt
          }
        }
      }
    }
    return mnr
  },
  // 当前微信的客户
  currentCustomers: (state) => {
    return state.currentCustomers
  },
  //   当前微信的企业联系人
  currentContacts: (state) => {
    return state.currentContacts
  },
  // remoteId对应的会话信息
  conversMap: (state, getters) => {
    let cm = {}
    getters.currentConvs.forEach((x) => {
      cm[x.RemoteId] = x
    })
    return cm
  },
  // remoteId对应的好友信息
  contactsMap: (state, getters) => {
    let cm = {}
    getters.currentContacts.forEach((x) => {
      cm[x.RemoteId] = x
    })
    getters.currentCustomers.forEach((x) => {
      cm[x.RemoteId] = x
    })
    return cm
  },
  // 消息接收者对应的name
  allContactsNameMap: (state) => {
    let cm = {}
    state.allContacts.forEach((x) => {
      cm[x.RemoteId] = x.Name
    })
    state.allCustomers.forEach((x) => {
      cm[x.RemoteId] = x.Name
    })
    for (const key in state.conversations) {
      if (Object.hasOwnProperty.call(state.conversations, key)) {
        const wxConversations = state.conversations[key]
        wxConversations.forEach((x) => {
          cm[x.RemoteId] = x.Name
        })
      }
    }
    return cm
  },
  // 会话页面 每个微信的聊天对象
  currentFriends: (state) => state.currentFriends,
  // 当前微信的聊天对象
  currentFriend: (state, getters) => {
    return state.currentFriends[getters.currentWeChatId] || {}
  },
  currentFriendId: (state, getters) => {
    return getters.currentFriend.RemoteId || ''
  },
  // ============== ConversationFriends用到的变量 ====
  departments: (state) => state.departments,
  corporations: (state) => state.corporations,

  lastChatPages: (state) => state.lastChatPages,
  addressListPages: (state) => state.addressListPages,
  chatRoomPages: (state) => state.chatRoomPages,
  // ============== ConversationChats用到的变量 =======
  currentChats: (state) => state.currentChats,

  content: (state) => state.content,
  remark: (state) => state.remark,
  contentType: (state) => state.contentType,
  url: (state) => state.url,
  hbDetailVisible: (state) => state.hbDetailVisible,
  hbDetail: (state) => state.hbDetail,
  // 当前微信的客户标签
  currentLabels: (state, getters) => {
    let labels = state.userLabels
    let wxid = getters.currentWeChatId
    return labels[wxid] || []
  }
}

// actions
const actions = {
  // 更新会话列表
  UpdateConversations: ({ state, commit }, talk) => {
    const wechatId = talk.WxId
    const oldConvs = state.conversations
    const digest = getContent(talk)
    // 如果当前有数据
    if (oldConvs[wechatId]) {
      const targetConvs = JSON.parse(JSON.stringify(oldConvs[wechatId]))
      let flag = true // 目前有该好友的会话信息
      for (const conv of targetConvs) {
        if (conv.RemoteId === talk.ConvId) {
          // 更新时间
          conv.UpdateTime = talk.CreateTime
          // 更新消息内容
          conv.Digest = digest
          // 群消息 发送者
          if (talk.Members) {
            conv.DigestUser = base64.decode(talk.Content).split(':')[0]
          }
          // 设置消息总数
          conv.MsgCnt = conv.MsgCnt ? conv.MsgCnt + 1 : 1

          // 设置未读消息
          if (talk.ContentType !== 'System' && talk.ContentType !== 5) {
            conv.UnreadCnt = conv.UnreadCnt ? conv.UnreadCnt + 1 : 1
          }

          // 是否发送
          if (talk.SenderId === talk.WxId) {
            // conv.IsSend = true
            conv.UnreadCnt = 0
          }
          flag = false
          break
        }
      }
      if (flag) {
        TriggerConversationPushTask(wechatId)
      } else {
        commit('UPDATE_CONVERSATIONS', { wechatId: wechatId, targetConvs: targetConvs })
      }
    } else {
      // 创建一个新的会话太麻烦 还是刷新会话列表吧
      TriggerConversationPushTask(wechatId)
    }
  },
  // 设置会话已读
  SetConvReaded: ({ state, commit }, currentConv) => {
    const wechatId = currentConv.WxId
    const oldConvs = state.conversations
    if (wechatId && oldConvs[wechatId]) {
      const targetConvs = JSON.parse(JSON.stringify(oldConvs[wechatId]))
      for (const conv of targetConvs) {
        if (conv.RemoteId === currentConv.RemoteId) {
          if (conv.UnreadCnt) {
            conv.UnreadCnt = 0
          }
          break
        }
      }
      commit('UPDATE_CONVERSATIONS', { wechatId: wechatId, targetConvs: targetConvs })
    }
  },
  // 更新我的客户
  UpdateCustomers({ getters, dispatch }, message) {
    const { WxId, Contacts, Count } = message
    Contacts.map((x) => {
      x.WxId = WxId
      x.Count = Count
    })
    nedb.customers.insert(Contacts, (err) => {
      if (err) return
      if (WxId === getters.currentWeChatId) {
        dispatch('SetCurrentCustomers', WxId)
      }
    })
  },
  // 删除nedb中的指定微信的客户列表
  RemoveAllCustomersByWechatId({ dispatch }, wxid) {
    nedb.customers.remove({ WxId: wxid }, { multi: true }, (err, removedDocs) => {
      if (err) return
      if (removedDocs) {
        dispatch('SetCurrentCustomers', wxid)
      }
    })
  },
  // 从nedb获取客户数据
  SetCurrentCustomers({ commit }, wxid) {
    nedb.customers.find({ WxId: wxid }, (err, docs) => {
      if (err) return
      commit('SET_CURRENT_CUSTOMERS', docs || [])
    })
  },

  // 更新或添加nedb中的customers数据
  UpdateFriend({ getters, dispatch, commit }, message) {
    const { WxId, Info } = message
    let remoteId = Info.RemoteId
    // 更新我的客户
    nedb.customers.update({ WxId: WxId, RemoteId: remoteId }, { $set: Info }, { upsert: false }, (err, doc) => {
      if (doc && WxId === getters.currentWeChatId) {
        dispatch('SetCurrentCustomers', WxId)
        // 更新当前的好友信息
        if (remoteId === getters.currentFriendId) {
          let { ...data } = getters.currentFriend
          for (const key in Info) {
            if (Object.hasOwnProperty.call(Info, key)) {
              data[key] = Info[key]
            }
          }
          commit('UPDATE_CURRENT_FRIEND', { wxid: WxId, contact: data })
        }
      }
    })
  },

  // 更新或添加nedb中的contacts数据
  UpdateContacts({ getters, dispatch }, message) {
    const { WxId, Contacts, Count } = message
    Contacts.map((x) => {
      x.WxId = WxId
      x.Count = Count
    })
    nedb.contacts.insert(Contacts, (err) => {
      if (err) return
      if (WxId === getters.currentWeChatId) {
        dispatch('SetCurrentContacts', WxId)
      }
    })
  },
  // 删除nedb中的指定微信的企业联系人
  RemoveAllContactsByWechatId({ dispatch }, wxid) {
    nedb.contacts.remove({ WxId: wxid }, { multi: true }, (err, removedDocs) => {
      if (err) return
      if (removedDocs) {
        dispatch('SetCurrentContacts', wxid)
      }
    })
  },
  // 从nedb获取企业联系人数据
  SetCurrentContacts({ commit }, wxid) {
    nedb.contacts.find({ WxId: wxid }, (err, docs) => {
      if (err) {
        commit('SET_CURRENT_CONTACTS', [])
      } else {
        commit('SET_CURRENT_CONTACTS', docs || [])
      }
    })
  },
  // 设置所有的客户和联系人
  SetAllContacts({ commit }) {
    nedb.customers.find({}, (err, docs) => {
      if (err) return
      commit('SET_ALL_CUSTOMERS', docs || [])
    })
    nedb.contacts.find({}, (err, docs) => {
      if (err) return
      commit('SET_ALL_CONTACTS', docs || [])
    })
  },

  // FriendTalkNotice更新会话
  AddChats({ state, commit }, talkNotice) {
    if (talkNotice.WxId === state.currentChats.WxId) {
      commit('UPDATE_CURRENT_CHATS_BY_TALK', talkNotice)
    }
  },
  // 离线消息保存到chats
  AddChatsByHistory({ state, commit }, hms) {
    let ccs = state.currentChats
    if (ccs.WxId === hms.WxId && ccs.ConvId === hms.ConvId) {
      let messages = []
      if (ccs.Messages) {
        messages = JSON.parse(JSON.stringify(ccs.Messages))
      }
      if (hms.Messages) {
        messages = messages.concat(hms.Messages)
      }
      commit('UPDATE_CURRENT_CHATS', { HasMore: hms.HasMore, Messages: uniqueMessages(messages) })
    } else {
      commit('SET_CURRENT_CHATS', hms)
    }
  },

  // 更新当前好友的聊天记录
  InsertLocalChat: ({ getters, commit }, chat) => {
    const { WxId, ConvId } = chat
    if (WxId === getters.currentWeChatId && ConvId === getters.currentFriendId) {
      commit('INSERT_LOCAL_CHAT', chat)
    }
  },
  // 删除自己插入的数据
  RemoveLocalChat: ({ getters, commit }, chat) => {
    const { ConvId, WxId } = chat
    if (WxId === getters.currentWeChatId && ConvId === getters.currentFriendId) {
      commit('REMOVE_LOACL_CHAT', chat)
    }
  },

  // 更新或添加nedb中的customers数据
  UpdateCustomersByLabel({ getters, dispatch, commit }, message) {
    let wxid = message.WxId
    let id = message.AddUsers ? message.AddUsers[0] : message.DelUsers[0]
    // 如果有数据就更新 没有就插入
    nedb.customers.findOne({ WxId: wxid }, (err, doc) => {
      if (err) return
      if (doc) {
        // 老的数据
        let oldContacts = doc.Contacts
        let cc = {}
        for (const oc of oldContacts) {
          if (oc.RemoteId === id) {
            oc.LabelIds = message.LabelIds || []
            cc = oc
            break
          }
        }
        nedb.customers.update(
          { WxId: wxid },
          { $set: { Contacts: oldContacts } },
          { upsert: false },
          (err, numReplaced) => {
            if (err) return
            // 更新 contacts
            if (wxid === getters.currentWeChatId) {
              dispatch('SetCurrentCustomers', wxid)
              let mm = {
                wxid: wxid,
                contact: cc
              }
              commit('SET_CURRENT_FRIENDS', mm)
            }
            // 更新当前的联系人(客户)
          }
        )
      }
    })
  },

  // 更新或添加nedb中的departments数据
  UpdateDepartments({ dispatch }, message) {
    if (message.WxId) {
      // 如果有数据就更新 没有就插入
      nedb.departments.update({ WxId: message.WxId }, message, { upsert: true }, (err, updateDoc) => {
        if (err) return
        dispatch('SetDepartments')
      })
    }
  },
  // 更新或添加nedb中的corporations数据
  UpdateCorporations({ commit, dispatch }, message) {
    if (message.WxId) {
      // 如果有数据就更新 没有就插入
      nedb.corporations.update({ WxId: message.WxId }, message, { upsert: true }, (err, updateDoc) => {
        if (err) return
        dispatch('SetCorporations')
      })
    }
  },
  // 设置departments
  SetDepartments({ commit }) {
    let departmentsMap = {}
    nedb.departments.find({}, (err, docs) => {
      if (err) return
      for (const doc of docs) {
        departmentsMap[doc.WxId] = {}
        if (doc.Departs) {
          for (const depart of doc.Departs) {
            departmentsMap[doc.WxId][depart.RemoteId] = depart.Name
            departmentsMap[doc.WxId][depart.ParentId] = depart.Name
          }
        }
      }
      if (JSON.stringify(departmentsMap) !== '{}') {
        commit('SET_DEPARTMENTS', departmentsMap)
      }
    })
  },
  // 设置corporations
  SetCorporations({ commit }) {
    let corpsMap = {}
    nedb.corporations.find({}, (err, docs) => {
      if (err) return
      for (const doc of docs) {
        if (doc.Corps) {
          for (const corp of doc.Corps) {
            corpsMap[corp.Id] = corp.Name
          }
        }
      }
      if (JSON.stringify(corpsMap) !== '{}') {
        commit('SET_CORPORATIONS', corpsMap)
      }
    })
  },

  // 群管理任务保存到数据库
  AddChatRoomTask({ rootGetters }, doc) {
    doc.userId = rootGetters.userId
    doc.result = 0 // 0表示初始状态 1表示成功 2表示失败
    nedb.chatRoomTask.insert(doc, (err, newDoc) => {
      if (err) return
    })
  },
  // 更新群管理任务
  UpdateChatRoomTask({ rootGetters, dispatch }, mj) {
    let flag = mj.Success ? 1 : 2
    nedb.chatRoomTask.update({ TaskId: mj.TaskId }, { $set: { result: flag } }, {}, (err, numReplaced) => { })
  },
  // 设置备注和标签操作 保存到数据库
  AddMemoTask({ rootGetters }, doc) {
    // doc.userId = rootGetters.userId
    doc.result = 0 // 0表示初始状态 1表示成功 2表示失败
    nedb.memoTask.insert(doc, (err, newDoc) => {
      if (err) return
    })
  },
  // 更新memoTask
  UpdateMemoTask({ rootGetters }, mj) {
    let flag = mj.Success ? 1 : 2 // 0初始状态, 1成功, 2失败
    nedb.memoTask.update({ TaskId: mj.TaskId }, { $set: { result: flag } }, {}, (err, numReplaced) => { })
  }
}

// mutations
const mutations = {
  SET_WECHATS: (state, wechats) => {
    let wechats2 = []
    for (const wechat of wechats) {
      wechats2.push({
        AcctId: '',
        Attr: '',
        Avatar: wechat.avatar,
        CorpId: wechat.corpid,
        IMEI: wechat.deviceid,
        Name: wechat.name,
        Phone: wechat.phone,
        WxId: wechat.wxid,
        isonline: wechat.isonline
      })
    }
    state.wechats = wechats2
  },

  // 设置当前选中的微信
  SET_CURRENT_WECHAT: (state, wechat) => {
    state.currentWechat = wechat
  },
  // 设置每个微信的会话
  SET_CONVERSATIONS: (state, convsData) => {
    const { WxId, Convers } = convsData
    if (!Convers || !WxId) return
    Convers.map((x) => {
      x.WxId = WxId
    })
    if (state.conversations[WxId]) {
      Vue.set(state.conversations, WxId, unique(state.conversations[WxId].concat(Convers)))
    } else {
      Vue.set(state.conversations, WxId, Convers)
    }
  },
  // 删除指定微信的conversations
  DELETE_CONVERSATIONS: (state, wechatId) => {
    Vue.set(state.conversations, wechatId, [])
  },
  // 更新会话列表
  UPDATE_CONVERSATIONS: (state, newData) => {
    Vue.set(state.conversations, newData.wechatId, newData.targetConvs)
  },
  // 根据change notice 更新会话列表
  CHANGE_CONVERSATIONS: (state, converData) => {
    let converInfo = converData.Convers
    let wxid = converData.WxId

    if (state.conversations[wxid]) {
      for (const conv of state.conversations[converData.WxId]) {
        if (conv.Id === converInfo.Id) {
          conv.Digest = converInfo.Digest
          conv.Members = converInfo.Members
          conv.Name = converInfo.Name
          conv.Notice = converInfo.Notice
          conv.HasExternMember = converInfo.HasExternMember
          conv.AvatarList = converInfo.AvatarList

          if (state.currentFriends[wxid].RemoteId === conv.RemoteId) {
            Vue.set(state.currentFriends, wxid, conv)
          }
          break
        }
      }
    }
  },
  // 设置当前微信的联系人列表
  SET_CURRENT_CONTACTS(state, contactsDocs) {
    state.currentContacts = contactsDocs
  },
  // 设置当前微信的客户列表
  SET_CURRENT_CUSTOMERS(state, customersDocs) {
    state.currentCustomers = customersDocs
  },

  // 所有客户
  SET_ALL_CUSTOMERS(state, customersDocs) {
    state.allCustomers = customersDocs
  },
  // 所有联系人
  SET_ALL_CONTACTS(state, customersDocs) {
    state.allContacts = customersDocs
  },

  // 设置当前微信 所选的联系人|会话
  SET_CURRENT_FRIENDS: (state, msg) => {
    Vue.set(state.currentFriends, msg.wxid, msg.contact)
  },
  // 更新当前好友的信息
  UPDATE_CURRENT_FRIEND: (state, data) => {
    Vue.set(state.currentFriends, data.wxid, data.contact)
  },
  // 设置当前好友的聊天记录
  SET_CURRENT_CHATS: (state, chatDocs) => {
    state.currentChats = chatDocs
  },
  // 更新当前好友的聊天记录
  UPDATE_CURRENT_CHATS: (state, docs) => {
    Vue.set(state.currentChats, 'Messages', docs.Messages)
    Vue.set(state.currentChats, 'HasMore', docs.HasMore)
  },
  // 更新当前好友的聊天记录
  INSERT_LOCAL_CHAT: (state, doc) => {
    let { Messages } = state.currentChats
    if (Messages) {
      Messages.push(doc)
    } else {
      Messages = [doc]
    }
    // Vue.set(state.currentChats, 'Messages', state.currentChats.Messages.push(doc))
  },
  // 更新当前好友的聊天记录
  REMOVE_LOACL_CHAT: (state, chat) => {
    const { TaskId } = chat
    // const { TaskId, CreateTime, MsgId, MsgRemoteId } = chat
    let { Messages } = state.currentChats
    let fid = Messages.findIndex((x) => {
      return x.TaskId === Number(TaskId)
    })
    if (fid >= 0) {
      Messages.splice(fid, 1)
      //   Messages.splice(fid, 1, { ...Messages[fid], CreateTime: CreateTime, MsgId: MsgId, MsgRemoteId: MsgRemoteId })
    }
  },
  // 消息撤回成功更改本地数据
  UPDATE_CHAT: (state, message) => {
    const { WxId, MsgRemoteId, ConvId, Flag } = message
    let { Messages } = state.currentChats
    let fid = Messages.findIndex((x) => {
      return x.WxId === WxId && x.ConvId === ConvId && x.MsgRemoteId === MsgRemoteId
    })
    if (fid >= 0) {
      Messages.splice(fid, 1, { ...Messages[fid], Flag: Flag, IsRevoke: true })
    }
  },
  // 更新当前会话的图片详情
  UPDATE_CHATS_BY_DETAIL: (state, detailDoc) => {
    if (state.currentChats.WxId === detailDoc.WxId) {
      if (detailDoc.Url) {
        for (const message of state.currentChats.Messages) {
          if (message.MsgId === detailDoc.MsgId) {
            if (message.Content) {
              let content = {}
              content = JSON.parse(base64.decode(message.Content))
              content.url = detailDoc.Url
              message.Content = base64.encode(JSON.stringify(content))
            }
            break
          }
        }
      } else {
        Message({
          type: 'warning',
          message: '资源地址获取失败！',
          duration: 2000
        })
      }
    }
    // Vue.set(state.currentChats, 'Messages', docs.Messages)
  },
  // 重置聊天记录
  RESET_CURRENT_CHATS: (state, wxid) => {
    state.currentChats = {
      Count: 0,
      Messages: [],
      Size: 0,
      ConvId: '',
      WxId: wxid || '',
      Page: 0,
      HasMore: false
    }
  },
  // 通过聊天通知 更新当前好友的聊天记录
  UPDATE_CURRENT_CHATS_BY_TALK: (state, doc) => {
    let currentConv = state.currentFriends[doc.WxId] || {}
    if (doc.ConvId === currentConv.RemoteId) {
      let count = state.currentChats.Count || 0
      let messages = state.currentChats.Messages || []
      Vue.set(state.currentChats, 'Count', count.Count + 1)
      Vue.set(state.currentChats, 'Messages', messages.concat(doc))
      bus.$emit('setScrollBottom')
    }
  },

  // 删除已经退出群聊的群聊会话
  DELETE_CONV(state, message) {
    const wechatId = message.WeChatId
    const oldConvs = state.conversations[wechatId]
    // 如果当前有数据
    if (oldConvs) {
      for (let index = 0; index < oldConvs.length; index++) {
        const element = oldConvs[index]
        if (element.UserName === message.RoomId) {
          oldConvs.splice(index, 1)
          break
        }
      }
      Vue.set(state.conversations, message.WeChatId, oldConvs)
    }
  },
  // 设置所有的公司列表（假设公司的id是唯一的）
  SET_CORPORATIONS(state, corpsMap) {
    state.corporations = corpsMap
  },
  // 设置企业联系人的部门列表
  SET_DEPARTMENTS(state, departsMap) {
    state.departments = departsMap
  },

  // 设置当前会话的当前页
  SET_LAST_CHAT_PAGES: (state, msg) => {
    Vue.set(state.lastChatPages, msg.wechatId, msg.page)
  },
  // 设置通讯录的当前页
  SET_ADDRESS_LIST_PAGES: (state, msg) => {
    Vue.set(state.addressListPages, msg.wechatId, msg.page)
  },
  // 设置群聊的当前页
  SET_CHAT_ROOM_PAGES: (state, msg) => {
    Vue.set(state.chatRoomPages, msg.wechatId, msg.page)
  },

  // 设置消息内容
  SET_CONTENT: (state, content) => {
    state.content = content
  },
  SET_REMARK: (state, remark) => {
    state.remark = remark
  },
  // 设置消息类型
  SET_CONTENT_TYPE: (state, type) => {
    state.contentType = type
  },
  // 设置大图/视频 的url
  SET_URL: (state, url) => {
    state.url = url
  },
  // 设置显示红包详情
  SET_HB_DETAIL_VISIBLE: (state, visible) => {
    state.hbDetailVisible = visible
  },
  // 设置显示红包详情
  SET_HB_DETAIL: (state, hbdetail) => {
    for (const key in hbdetail) {
      if (hbdetail.hasOwnProperty(key)) {
        Vue.set(state.hbDetail, key, hbdetail[key])
      }
    }
  },
  // 设置userLabels
  UPDATE_USER_LABELS: (state, labelsDocs) => {
    Vue.set(state.userLabels, labelsDocs.WxId, labelsDocs.LabelGroups || [])
  },

  // 微信下线
  WECHAT_OFF_LINE: (state, wechatId) => {
    for (const wechat of state.wechats) {
      if (wechat.WxId === wechatId) {
        wechat.isonline = 1
        // 更新当前微信信息
        if (wechatId === state.currentWechat.WxId) {
          state.currentWechat = wechat
        }
        break
      }
    }
  },
  // 微信上线
  WECHAT_ON_LINE: (state, wechatInfo) => {
    wechatInfo.isonline = 0
    let flagIndex = state.wechats.findIndex((x) => {
      return x.WxId === wechatInfo.WxId
    })
    if (flagIndex >= 0) {
      state.wechats.splice(flagIndex, 1, wechatInfo)
    } else {
      state.wechats.push(wechatInfo)
    }
    // 更新当前微信信息
    if (wechatInfo.WxId === state.currentWechat.WxId) {
      state.currentWechat = wechatInfo
    }
  }
}

export default {
  namespaced: true,
  state,
  getters,
  actions,
  mutations
}
