/**
 * 设备选择模块 - 用于统计页面的设备切换
 * 这个模块会被持久化到 localStorage
 */
const deviceModule = {
  namespaced: true,

  state: {
    selectedDeviceSn: '', // 当前选中的设备 SN
    deviceList: [], // 设备列表
  },

  mutations: {
    SET_SELECTED_DEVICE(state, deviceSn) {
      state.selectedDeviceSn = deviceSn
    },

    SET_DEVICE_LIST(state, list) {
      state.deviceList = list
      // 如果没有选中的设备，且列表不为空，自动选中第一个
      if (!state.selectedDeviceSn && list.length > 0) {
        state.selectedDeviceSn = list[0].deviceSn
      }
    }
  },

  actions: {
    setSelectedDevice({ commit }, deviceSn) {
      commit('SET_SELECTED_DEVICE', deviceSn)
    },

    setDeviceList({ commit }, list) {
      commit('SET_DEVICE_LIST', list)
    }
  },

  getters: {
    selectedDeviceSn: state => state.selectedDeviceSn,
    deviceList: state => state.deviceList,
    selectedDevice: state => {
      return state.deviceList.find(d => d.deviceSn === state.selectedDeviceSn)
    }
  }
}

export default deviceModule
