import API from '@/api'
import Session from '@/store/db/Session.js'
import User from '@/store/db/User.js'

const objSession = new Session()

const actions = {
  async refreshSessionList ({ commit, state }, params) {
    let list = await objSession.getSortList()
    if (list && list.length) {
      // 从indexDB拿数据
      commit('setSessionList', list)
    }
  },
  async getSessionList ({ dispatch, commit, state }, params) {
    // 本地刷新缓存
    dispatch('refreshSessionList')

    // 从接口读取缓存数据
    API.session.sessionList(async ({ data }) => {
      if (data && data.data) {
        // 清空老数据
        await objSession.clearData()

        // 存储到indexDB，用过滤过的数据来渲染
        let list = await objSession.replaceSession(data.data)
        commit('setSessionList', list)
      }
    })
  },
  async getUserInfo ({ commit, state, rootState }) {
    try {
      let userId = rootState.userId || localStorage.getItem('user_id')
      let { data } = await API.user.getInfo({
        target_id: userId
      })
      commit('setUserInfo', data.data)
      commit('setGroupUserInfo', data.data)

      if (data.data.user_id) {
        // 更新自己的信息
        let objUser = new User()
        let newData = {
          cover_photo: data.data.cover_photo,
          nick_name: data.data.nick_name,
          user_name: data.data.user_name
        }
        objUser.updateObject(newData, { user_id: data.data.user_id })
      }
    } 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 actions
