/**
 * 设备选择模块 - 用于统计页面的设备切换
 * 这个模块会被持久化到 localStorage
 */

// localStorage 的 key
const STORAGE_KEY = 'device_selected_sn'

// 从 localStorage 读取上次选中的设备
const loadSelectedDevice = () => {
  try {
    const saved = localStorage.getItem(STORAGE_KEY)
    return saved || ''
  } catch (error) {
    console.error('读取选中设备失败:', error)
    return ''
  }
}

// 保存选中的设备到 localStorage
const saveSelectedDevice = (deviceSn) => {
  try {
    localStorage.setItem(STORAGE_KEY, deviceSn)
  } catch (error) {
    console.error('保存选中设备失败:', error)
  }
}

const deviceModule = {
  namespaced: true,

  state: {
    selectedDeviceSn: loadSelectedDevice(), // 从 localStorage 恢复上次选中的设备
    deviceList: [], // 设备列表
  },

  mutations: {
    SET_SELECTED_DEVICE(state, deviceSn) {
      state.selectedDeviceSn = deviceSn
      // 持久化到 localStorage
      saveSelectedDevice(deviceSn)
    },

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

  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
