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

const state = {
  messageList: [],
  socketState: false
}
const mutations = {
  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) => {
    console.log(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
      })
    }
  }
}
const actions = {
  initMessage({ commit }) {
    getMessage().then(res => {
      if (res.code !== 0) {
        return
      }
      commit('INIT_MESSAGE', res.data)
      commit('INIT_SOCKET', commit)
    })
  },
  colseSocket() {
    closeWebSocket()
  }
}

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