import Vue from 'vue'
import API from '@/api'
import _ from 'lodash'
import Session from '@/store/db/Session.js'

const state = {
  popInviteType: 1, // 弹框邀请类型{1:建群,2:邀请好友进群,3:删除群好友,4:添加群管理,5:转让群主}
  sessionList: [], // 会话列表
  isLogin: true,
  toApp: false,
  friendList: [] // 好友列表
}

const objSession = new Session()
const mutations = {
  setSessionList (state, data) {
    // 按is_pin(是否置顶) 属性排序
    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)
  },
  setSessionItemUnread (state, data) {
    console.log('进来寻找session', data.unread, data, data.cont)
    state.sessionList.forEach((item) => {
      if (item.session_id == `${data.session_id}`) {
        let unread = item.unread
        if (data.unread && data.curSession != data.session_id) {
          unread += data.unread
        } else {
          unread = 0
        }

        Vue.set(item, 'unread', unread)
        Vue.set(item, 'cont', data.cont ? data.cont : item.cont)
        objSession.setUnread(item.session_id, unread)
      }
    })
  },
  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) {
    objSession.setPin(sessionId, 1)
    state.sessionList.forEach((item, index) => {
      if (item.session_id == sessionId) {
        item.is_pin = 1
        state.sessionList.unshift(state.sessionList.splice(index, 1)[0])
      }
    })
  },
  /**
   * @des 根据取消置顶目标更新会话列表顺序
   * @param {Object} state
   * @param {String} sessionId  待取消置顶的会话
   */
  cancelSessionListByPin (state, sessionId) {
    objSession.setPin(sessionId, 0)
    let targetItem = null
    state.sessionList.forEach((item, index) => {
      if (item.session_id == sessionId) {
        item.is_pin = 0
        targetItem = state.sessionList.splice(index, 1)[0]
      } else if (targetItem && item.is_pin < 1) {
        // 插入到合适的位置
        state.sessionList.splice(index, 0, targetItem)
        targetItem = null
      }
    })

    // state.sessionList.push(targetItem)
  },
  /**
   * @des 根据免打扰更新会话列表
   * @param {Object} state
   * @param {String} sessionId  免打扰的会话
   */
  updateSessionListByMute (state, sessionId) {
    objSession.setMute(sessionId, 1)
    state.sessionList.forEach((item, index) => {
      if (item.session_id == sessionId) {
        item.is_mute = 1
      }
    })
  },
  /**
   * @des 根据免打扰置顶目标更新会话列表
   * @param {Object} state
   * @param {String} sessionId  待取消免打扰的会话
   */
  cancelSessionListByMute (state, sessionId) {
    objSession.setMute(sessionId, 0)
    state.sessionList.forEach((item, index) => {
      if (item.session_id == sessionId) {
        item.is_mute = 0
      }
    })
  },
  /**
   * @des 根据群id删除会话列表item
   * @param {Object} state
   * @param {String} sessionId  待取消免打扰的会话
   */
  removeSessionListById (state, sessionId) {
    state.sessionList = _.filter(state.sessionList, (item, index) => {
      return item.session_id != sessionId
    })
  },
  /**
   *设置弹框邀请类型
   *type1.建群2.邀请好友进群3.添加群管理
  */
  setPopInviteType (state, type) {
    if (!/\d/.test(type)) return
    state.popInviteType = type
  }
}

const actions = {
  async getSessionList ({ commit, state }, params) {
    let list = await objSession.getSortList()
    if (list) {
      // 从indexDB拿数据
      commit('setSessionList', list)
    }

    API.session.sessionList(function ({ data }) {
      commit('setSessionList', data.data)
      // 存储到indexDB
      objSession.replaceObjects(data.data)
    })
  },
  async getUserInfo ({ commit, state, rootState }) {
    try {
      let { data } = await API.user.getInfo({
        target_id: rootState.userId
      })
      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) {}
  }
}

const getters = {
  muteList: state => {
    // 免打扰
    return state.sessionList.filter(v => {
      if (v.is_mute == '1') {
        return v.session_id
      }
    })
  }
}

export default {
  state,
  mutations,
  actions,
  getters
}
