import { createSoceket } from '@/utils/WebSocketUtil'
import { getMessage } from '@/api/message'

const state = {
  messageList: [],
  socketState: false
}
const mutations = {
  // 初始化socket
  INIT_SOCKET: (state, commit) => {
    createSoceket({ commit })
  },
  // 更新消息 像消息队列中添加一条消息
  UPDATE_MESSAGE: (state, message) => {
    state.messageList.unshift(message)
  },
  // 初始化消息列表
  INIT_MESSAGE: (state, list) => {
    state.messageList = list
    console.log(state.messageList)
  },
  // 设置会话状态
  SET_SCOKET_STATE: (state, flag) => {
    state.socketState = flag
  },
  // 修改消息状态
  SET_MESSAGE_STATE: (state, info) => {
    if (info.type === 1) {
      state.messageList = state.messageList.map(v => {
        if (v.authId === info.id) {
          v.status = 1
        }
        return v
      })
    } else {
      state.messageList = state.messageList.map(v => {
        if (v.authProductId === info.id) {
          v.status = 1
        }
        return v
      })
    }
  },
  CLEAR_MESSAGE: (state) => {
    state.messageList = []
  }
}
const actions = {
  // 初始化消息state
  initMessage({ commit }) {
    getMessage().then(res => {
      if (res.code !== 0) {
        return
      }
      commit('INIT_MESSAGE', res.data)
      commit('INIT_SOCKET', commit)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
