import Vue from 'vue'
import API from '@/api'
import _ from 'lodash'
import Session from '@/store/db/Session.js'
import User from '@/store/db/User.js'
import { initChatData } from '@/store/state'
import {
  decryptoMsg
} from '@/util/util.js'

const state = initChatData()

const objSession = new Session()
const mutations = {
  setSessionList (state, data) {
    data.forEach(value => {
      let lastMsg = value['last_msg']
      value.cont = lastMsg ? decryptoMsg(lastMsg.content) : ''
    })

    // 按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) {
    let pinSession = state.sessionList.filter(item => {
      return item.is_pin === 1
    })
    let dataPos = pinSession.length || 0
    state.sessionList.splice(dataPos, 0, data)

    objSession.recover(data.session_id)
  },
  // 会话列表未读消息设置
  setSessionItemUnread (state, data) {
    let itemIndex = 0
    state.sessionList.forEach((item, index) => {
      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)
        objSession.setUnread(item.session_id, unread)
        itemIndex = index
      }
    })
    // 重新排序 非pin的会话
    let temp = state.sessionList[itemIndex]
    if (itemIndex && !temp.is_pin && data.cont) {
      state.sessionList.splice(itemIndex, 1)
      mutations.addSessionItem(state, temp)
    }
  },
  setFriendList (state, data) {
    state.friendList = data
  },
  // 左侧会话撤回-用于私聊主动撤回
  setSessionRepeal (state, data) {
    state.sessionList.forEach((item) => {
      if (item.session_id == (data.sessionId || data.group_id)) {
        Vue.set(item.last_msg, 'msg_type', -1)
        Vue.set(item, 'update_time_int', data.timestamp)
      }
    })
  },
  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, data) {
    objSession.setPin(data.session_id, 1)
    state.sessionList.forEach((item, index) => {
      if (item.session_id == data.session_id) {
        item.is_pin = data.is_pin
        item.pin_time_int = data.pin_time_int
        state.sessionList.unshift(state.sessionList.splice(index, 1)[0])
      }
    })
  },
  /**
   * @des 根据取消置顶目标更新会话列表顺序
   * @param {Object} state
   * @param {String} sessionId  待取消置顶的会话
   */
  cancelSessionListByPin (state, data) {
    objSession.setPin(data.session_id, 0)
    let targetItem = null
    state.sessionList.forEach((item, index) => {
      if (item.session_id == data.session_id) {
        item.is_pin = data.is_pin
        item.pin_time_int = data.pin_time_int
        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) {
    objSession.remove(sessionId)
    state.sessionList = _.filter(state.sessionList, (item, index) => {
      return item.session_id != sessionId
    })
  },
  /**
   * @des 更新用户群主列表中的last_msg内容
   * @param {String} params.sessionId 待更新的sessionId
   * @param {Object} params.data 待更新的内容
   */
  updateSessionLastmsg (state, params) {
    let targetObj = state.sessionList.find(n => {
      return n.session_id == (params.group_id || params.sessionId || params.session_id)
    })
    if (targetObj) {
      mutations.setSessionLastmsg(state, targetObj, params)
    }
  },
  updateSessionLastMsgNoDecode (state, params) {
    mutations.updateSessionLastmsg(state, Object.assign(params, { noDecryptoMsg: true }))
  },
  setSessionLastmsg (state, targetObj, params) {
    if (!targetObj.last_msg) {
      Vue.set(targetObj, 'last_msg', {})
    }

    let lastMsg = targetObj.last_msg
    Vue.set(lastMsg, 'content', params.content)
    Vue.set(lastMsg, 'from', params.from)
    Vue.set(lastMsg, 'msg_type', params.msg_type)
    Vue.set(lastMsg, 'name', params.name)
    Vue.set(lastMsg, 'nick_name', params.nick_name)
    Vue.set(lastMsg, 'time', params.timestamp)

    Vue.set(targetObj, 'update_time_int', params.timestamp)
    Vue.set(targetObj, 'cont', params.noDecryptoMsg ? params.content : decryptoMsg(params.content))
  },
  initChatData (state) {
    let data = initChatData()

    for (let i in state) {
      if (data.hasOwnProperty(i)) state[i] = data[i]
    }
  }
}

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) {}
  }
}

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

export default {
  state,
  mutations,
  actions,
  getters
}
