import API from '@/api'

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

const mutations = {
  setSessionList (state, data) {
    // 按is_pin(是否置顶) 属性排序
    state.sessionList = data.sort((a, b) => {
      return b.is_pin - a.is_pin
    })
  },
  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
  },
  setSessionItem (state, data) {
    state.sessionList.forEach(item => {
      if (item.session_id == data.session_id) {
        item = data
      }
    })
  },
  /**
   * @des 根据置顶目标更新会话列表顺序
   * @param {Object} state
   * @param {String} sessionId  待置顶的会话
   */
  updateSessionListByPin (state, sessionId) {
    state.sessionList.forEach((item, index) => {
      if (item.session_id == sessionId) {
        state.sessionList.unshift(state.sessionList.splice(index, 1)[0])
      }
    })
  },
  /**
   * @des 根据取消置顶目标更新会话列表顺序
   * @param {Object} state
   * @param {String} sessionId  待取消置顶的会话
   */
  cancelSessionListByPin (state, sessionId) {
    state.sessionList.forEach((item, index) => {
      if (item.session_id == sessionId) {
        state.sessionList.push(state.sessionList.splice(index, 1)[0])
      }
    })
  }
}

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)
      commit('setGroupUserInfo', data.data)
    } catch (error) {}
  },
  /**
   * @des 更新用户群组列表中指定sessionId的内容
   * @param {String} params.sessionId 待更新的sessionId
   * @param {Object} params.data 待更新的内容
   */
  updateSessionItem ({ commit, state }, params) {
    let targetObj = state.sessionList.find(n => {
      return n.session_id == params.sessionId
    })

    targetObj = Object.assign(targetObj, params.data)
    commit('setSessionItem', targetObj)
  },
  /**
   * 撤回消息
   * @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
}
