import {
  addSomeInArray,
  addTimeMsgInItem,
  decryptoMsg,
  addLinkItem,
  formatPinMsg,
  checkAtMe
} from '@/util/util.js'
import _ from 'lodash'
import Vue from 'vue'
import Message from '@/store/db/Message.js'
import { initGroupData } from '@/store/state'
const objMessage = new Message()

const mutations = {
  initGroup (state, data) {
    state.userId = data.userId
    state.groupId = data.groupId
    state.useCache = data.useCache
  },
  initState (state, data) {
    let groupData = initGroupData()

    for (let i in groupData) {
      if (i == 'userId' || i == 'userInfo') {
        break
      } else state[i] = groupData[i]
    }
  },
  setGroupInfo (state, data) {
    state.groupName = data.groupName
    state.userCounts = data.userCounts
    state.members = data.members
    state.groupNotice = data.groupNotice
    state.url = data.url
    state.inviteUrl = data.inviteUrl
    state.sessionInfo = data.sessionInfo || {}
    state.isJoin = data.isJoin
    state.coverPhoto = data.coverPhoto
    state.adminList = data.adminList
    state.blockList = data.blockList
    state.shareName = data.shareName
    state.creator = data.creator
    state.eosInfo = data.eosInfo
    state.membersArray = data.membersArray
    state.membersNum = data.membersNum

    if (data.pinMsg) {
      formatPinMsg(data.pinMsg, state.userId)
      state.pinList = [ data.pinMsg ]
      // removeItemIfEixt(state.pinList, state.chatList, item => item.hash)
    }
    state.pinMsg = data.pinMsg || {}
  },
  setGroupUserInfo (state, data) {
    state.userInfo = data
    state.userId = data.user_id
  },
  /**
   * @des 添加历史消息到当前chatList队列
   * @param {Object} state
   * @param {Array} data 待添加的消息队列
   */
  addHistoryList (state, data) {
    if (data.length) {
      addSomeInArray(data)
      // removeItemIfEixt(state.pinList, data, item => item.hash)

      // 根据 hash 求data相对于chatList的差集（去重）
      let newList = _.differenceBy(data, state.chatList, 'hash') || []
      state.chatList = newList.concat(state.chatList)
    }
  },
  /**
   * 清空聊天记录
  */
  clearChatList (state) {
    state.chatList = []
    state.pinMsg = {}
    state.groupId = null
  },
  /**
   * @des 消息列表插入置顶消息
   * @param {*} state
   * @param {*} data
   */
  addPinChatItem (state, data) {
    let item = {
      name: data ? data.nick_name : 'unknown',
      content: data.content,
      userId: data.userId,
      timestamp: data.timestamp,
      avatar: data ? data.cover_photo : '',
      hash: data.hash,
      type: data.userId == state.userId ? 'me' : 'you',
      msg_type: data.msg_type,
      loading: false,
      res: data.res,
      joinMsg: '',
      fail: false
    }

    state.chatList.splice(0, 0, item)
  },
  addChatItem (state, data) {
    let newMsg = !!data.newMsg
    let fromdb = !!data.fromdb
    let chatList = state.chatList
    if (data.group_id && data.group_id != state.groupId) return
    if (data.list) data = data.list

    if (data && data.length > 0) {
      addSomeInArray(data)
      // removeItemIfEixt(state.pinList, data, item => item.hash)
      if (fromdb) state.atList = []

      // 检测是否被@
      newMsg && !fromdb && data.forEach(item => {
        if (checkAtMe(item.content, state.userInfo.user_name)) {
          state.atList.push(item)
        }
      })

      // // 根据 hash 求data相对于chatList的差集（去重）
      let newList = _.differenceBy(data, chatList, 'hash') || []
      chatList = chatList.concat(newList)
    } else {
      let user = state.members[data.from] || data.user_info
      let item = {
        name: user ? user.nick_name : 'unknown',
        content: data.content,
        userId: data.from,
        timestamp: data.timestamp,
        avatar: user ? user.cover_photo : '',
        hash: data.hash,
        type: data.from == state.userId ? 'me' : 'you',
        msg_type: data.msg_type,
        loading: Boolean(data.loading),
        res: data.res,
        joinMsg: data.joinMsg,
        fail: false
      }
      // 针对自己发送的情况
      if (data.createTime) {
        item.createTime = data.createTime
      }

      addTimeMsgInItem(item, chatList)
      addLinkItem(item)
      if (!chatList.some(n => { return item.hash && n.hash === item.hash })) {
        chatList.push(item)
      }
    }

    state.chatList = chatList
  },
  addPacketItem (state, data) {
    let item = {
      name: state.members[data.from]
        ? state.members[data.from].nick_name
        : 'unknown',
      timestamp: data.timestamp,
      avatar: state.members[data.from] ? state.members[data.from].cover_photo : '',
      userId: data.from,
      msg_type: data.type === 'new_redpack' ? 4 : 5,
      content: JSON.parse(decryptoMsg(data.content)),
      type: data.from == state.userId ? 'me' : 'you',
      ext: { grabbed: 0, redpack_status: 0 },
      hash: data.hash
    }
    addTimeMsgInItem(item, state.chatList)
    state.chatList.push(item)
    state.endHash = data.hash
  },
  addPacketTip (state, data) {
    let item = {
      content: {
        trxId: data.content.redpack_trx_id,
        title: data.content.title
      },
      ext: {
        grabbed: 1,
        redpack_status: 0
      },
      avatar: state.members[data.from] ? state.members[data.from].cover_photo : '',
      name: state.members[data.from]
        ? state.members[data.from].nick_name
        : 'unknown',
      from: data.from,
      to: data.to,
      redPackTip: true
    }
    state.chatList.push(item)
  },
  unpdatePacketItem (state, { type, trxId, data }) {
    let list = state.chatList
    let ind = list.findIndex(e => {
      return e.msg_type == 4 && e.content.trxId == trxId
    })
    let item = list[ind]
    item.ext[type] = data
    Vue.set(state.chatList, ind, item)

    objMessage.updatePackInfo(item.hash, type, data)
  },
  reSendChatItem (state, data) {
    let chatList = state.chatList

    chatList.forEach(item => {
      if (item.createTime == data.createTime) {
        item.loading = true
        item.fail = false
      }
    })
  },
  removeAtListLast (state) {
    state.atList.pop()
  },
  clearAtList (state) {
    state.atList = []
  },
  /**
   * 撤回消息，设置消息数据为{ repealMsg: true }
   * @param {state} state
   * @param {Object|Number} data
   */
  repealChatItem (state, data) {
    let { chatList } = state
    for (let i = chatList.length - 1; i >= 0; i--) {
      let item = chatList[i]
      if (item.hash === data.hash) {
        Vue.set(item, 'repealMsg', true)
        Vue.set(item, 'from', data.from)
      }
    }

    // if (pinList.length) {
    //   removeItemIfEixt(pinList, [data], item => item.hash)
    // }

    objMessage.removeMsg(data['session_id'], data.hash)
  },

  deleteChatItem (state, hash) {
    let index = state.chatList.findIndex(item => item.hash === hash)
    state.chatList.splice(index, index)
  },

  addUnreadNums (state) {
    state.unreadNums++
  },

  resetUnreadNums (state) {
    state.unreadNums = 0
  },

  setHash (state, data) {
    if (data.startHash) {
      state.startHash = data.startHash
    }
    if (data.endHash) {
      state.endHash = data.endHash
    }
  },
  clearHash (state, data) {
    state.endHash = null
  },
  /**
   * @des 更新置顶
   */
  updatePin (state, data) {
    state.sessionInfo.is_pin = data
  },
  /**
   * @des 更新免打扰
   */
  updateMute (state, data) {
    state.sessionInfo.is_mute = data
  },
  /**
   * @des 更新加入信息
   */
  updateJoin (state, data) {
    state.isJoin = data
  },
  /**
   * @des 更新群信息
   */
  updateGroup (state, { key, data }) {
    state[key] = data
  },
  /**
   * @更新群成员
  */
  updateMembers (state, data) {
    state.members = Object.assign({}, data, state.members)
  },
  /**
   * @更新群成员组
   * @param type {add,del}
   * @param userInfo 用户信息
  */
  updateMembersArray (state, { type, userInfo }) {
    if (type == 'add') {
      let isAdd = state.membersArray.some((item) => {
        return userInfo.user_id == item.user_id
      })

      if (!isAdd) {
        ++state.membersNum
        state.membersArray.push(userInfo)
      }
    } else {
      let index = state.membersArray.findIndex((item) => {
        return item.user_id == userInfo.user_id
      })

      if (index > -1) {
        --state.membersNum
        state.membersArray.splice(index, 1)
      }
    }
  },
  /**
   * @des 更新members里自己的头像
   */
  updateMemberAvatar (state, { userId, imageUrl }) {
    let members = state.members
    let chatList = state.chatList

    for (let i = 0; i < chatList.length; i++) {
      let id = chatList[i]['userId']
      if (id == userId) {
        let item = chatList[i]
        item['avatar'] = imageUrl
        Vue.set(state.chatList, i, item)
      }
    }
    for (let k in members) {
      if (k == userId) {
        let item = members[k]
        item['cover_photo'] = imageUrl
        Vue.set(state.members, k, item)
        return
      }
    }
  },
  /**
   * @des 更新members里自己的名字
   */
  updateMemberNickName (state, { userId, nickName }) {
    let members = state.members
    let chatList = state.chatList

    for (let i = 0; i < chatList.length; i++) {
      let id = chatList[i]['userId']
      if (id == userId) {
        let item = chatList[i]
        item['name'] = nickName
        Vue.set(state.chatList, i, item)
      }
    }
    for (let k in members) {
      if (k == userId) {
        let item = members[k]
        item['nick_name'] = nickName
        Vue.set(state.members, k, item)
        return
      }
    }
  },

  /**
   * @des 更新聊天输入框聚焦状态
   */
  updateChatInputFocus (state, focus) {
    state.chatInputFocus = focus
  },
  /**
   * @des 更新群组封禁人员列表
   * @param {String} param.type [delete,add]
   * @param {String} param.id
   */
  updateGroupBlockList (state, param) {
    let { type, id } = param
    if (type === 'delete') {
      let index = state.blockList.findIndex(uid => uid == id)
      index !== -1 && state.blockList.splice(index, 1)
    } else if (type === 'add') {
      state.blockList.push(id)
    }
  },
  /**
   * @param {Object|Null} param
   */
  updateGroupPinMsg (state, param) {
    if (param) {
      param.visible = true
      formatPinMsg(param, state.userId)
      state.pinMsg = param
    } else {
      state.pinMsg = {}
    }
  },
  /**
   * @des 更新是否停止搜索监听
   * @param {Object|Null} param
   */
  updateIsNewAt (state, param) {
    state.isNewAt = param.isNewAt
    state.isNewAtFound = param.isNewAtFound
  },
  /**
   * @des 更新搜索框提示列表
   * @param {Object|Null} param
   */
  updateGroupSearchList (state, param) {
    state.searchList = param
  },
  initGroupData (state) {
    let data = initGroupData()

    for (let i in state) {
      if (data.hasOwnProperty(i)) state[i] = data[i]
    }
  },
  /**
   * @des 更新刚发送消息的状态
   * @param {Number} data.index
   * @param {String} data.hash
   */
  updataChatItem (state, data) {
    let listItem = state.chatList[data.index]
    listItem.hash = data.hash
    listItem.loading = false
  }
}

export default mutations
