const state = {
  users: [], //用户
  sessionList: [],
  activeIndex: 0,
  uid: '',
  groups: [],
}
const mutations = {
  setUsersStatus(state, list) {
    let users = state.users
    for (const iterator of list) {
      for (const iterato of users) {
        if (iterato.uid === iterator.uid) {
          iterato.status = iterator.status
          break
        }
      }
    }
  },
  setUsers(state, list) {
    state.users = list
  },
  addSession(state, data) {
    let list = state.sessionList
    let index = list.findIndex((h) => h.uid === data.uid)
    if (index !== -1) {
      state.activeIndex = index
      // let item = list[index];
      // list.splice(index, 1);
      // list.unshift(item);
    } else {
      list.unshift(data)
      state.activeIndex = 0
    }
  },
  setUnread(state, { uid, unread }) {
    let list = state.sessionList
    let index = list.findIndex((h) => h.uid === uid)
    let item
    // 取消未读
    if (state.activeIndex === index && unread) {
      list[index].unread = false
      return
    }
    // 来消息置顶
    if (index !== -1) {
      item = list[index]
      list.splice(index, 1)
      if (state.activeIndex < index) {
        state.activeIndex = index + 1
        item.unread = !!unread
      } else if (state.activeIndex === index) {
        state.activeIndex = 0
      } else {
        item.unread = !!unread
      }
    } else {
      item = state.users.find((item) => item.uid === uid)
      state.activeIndex += 1
    }

    list.unshift(item)
    // for (const iterator of state.sessionList) {
    //   if(iterator.uid === uid){
    //     iterator.unread = !iterator.unread;
    //     break
    //   }
    // }
  },
  setActiveIndex(state, index) {
    state.activeIndex = index
    state.sessionList
  },
  setGroups(state, list) {
    state.groups = list
  },
  setUid(state, uid) {
    state.uid = uid
  },
}
const actions = {
  // 在线状态
  setUsersStatus({ commit }, list) {
    commit('setUsersStatus', list)
  },
  // 用户
  setUsers({ commit }, list) {
    commit('setUsers', list)
  },
  // 历史聊天
  addSession({ commit }, data) {
    commit('addSession', data)
  },
  // 未读
  setUnread({ commit }, uid) {
    commit('setUnread', uid)
  },
  setActiveIndex({ commit }, index) {
    commit('setActiveIndex', index)
  },
  setUid({ commit }, uid) {
    commit('setUid', uid)
  },
  setGroups({ commit }, list) {
    commit('setGroups', list)
  },
}

export default { state, mutations, actions }
