import API from '@/api'

const state = {
  sessionList: [], // 会话列表
  isLogin: true,
  toApp: false,
  friendList: [] // 好友列表
}

const mutations = {
  setSessionList (state, data) {
    state.sessionList = data
  },
  addSession (state, data) {
    state.sessionList.push(data)
  },
  chatAppLogin (state, flag) {
    state.isLogin = flag
  },
  toApp (state, flag) {
    state.toApp = flag
  },
  addSessionItem (state, data) {
    state.sessionList.unshift(data)
  },
  setFriendList (state, data) {
    state.friendList = data
  }
}

const actions = {
  async getSessionList ({ commit, state }, params) {
    try {
      let { data } = await API.session.sessionList()
      commit('setSessionList', data.data)
    } catch (error) {}
  },
  async getUserInfo ({ commit, state }) {
    try {
      let { data } = await API.user.getInfo()
      commit('setUserInfo', data.data)
    } catch (error) {}
  },
  /**
   * 撤回消息
   * @param {Object} params
   * {index:number, session_id:string, hash:string}
   */
  async doRepealPersonMsg ({ dispatch, commit, state, rootState }, params = {}) {
    try {
      await API.person.repealPersonMsg({
        session_id: rootState.curSession,
        hash: params.hash
      })
    } catch (error) {}
  },
  async getFriendList ({ commit, state }) {
    try {
      let { data } = await API.group.getFriends()
      commit('setFriendList', data.data)
    } catch (error) {}
  }
}

export default {
  state,
  mutations,
  actions
}
