/**
 * Vuex Warehouse Module - 仓库状态管理
 * @module store/modules/warehouse
 * 
 * 用于管理仓库选择、货架信息等仓库相关状态
 */

// 从本地存储获取初始状态
const getWarehouseInitialState = () => {
  return {
    // 当前选中的仓库 ID
    selectedWarehouse: uni.getStorageSync('selectedWarehouse') || '',
    
    // 仓库列表
    warehouseList: [],
    
    // 选择的位置索引（用于仓库选择器）
    selectedPosition: parseInt(uni.getStorageSync('selectedPositionIndex') || '0')
  }
}

const state = getWarehouseInitialState()

const mutations = {
  /**
   * 设置选中的仓库
   * @param {String} warehouseId - 仓库 ID
   */
  setSelectedWarehouse(state, warehouseId) {
    state.selectedWarehouse = warehouseId
    uni.setStorageSync('selectedWarehouse', warehouseId)
  },

  /**
   * 设置仓库列表
   * @param {Array} list - 仓库列表
   */
  setWarehouseList(state, list) {
    state.warehouseList = list
  },

  /**
   * 更新选择位置索引
   * @param {Number} position - 位置索引
   */
  updateSelectedPosition(state, position) {
    state.selectedPosition = position
    uni.setStorageSync('selectedPositionIndex', position)
  },

  /**
   * 清除仓库选择
   */
  clearWarehouseSelection(state) {
    state.selectedWarehouse = ''
    state.selectedPosition = 0
    uni.removeStorageSync('selectedWarehouse')
    uni.removeStorageSync('selectedPositionIndex')
  }
}

const actions = {
  /**
   * 加载仓库列表
   * @returns {Promise<Array>} 仓库列表
   */
  async loadWarehouseList({ commit }) {
    try {
      const res = await uni.request({
        url: '/zhishu/warehouse/list',
        method: 'GET'
      })
      
      if (res.data && res.data.data) {
        commit('setWarehouseList', res.data.data)
        return res.data.data
      }
      return []
    } catch (error) {
      console.error('加载仓库列表失败:', error)
      return []
    }
  },

  /**
   * 选择仓库
   * @param {String} warehouseId - 仓库 ID
   */
  selectWarehouse({ commit }, warehouseId) {
    commit('setSelectedWarehouse', warehouseId)
  }
}

const getters = {
  /**
   * 获取当前选中的仓库 ID
   */
  selectedWarehouse: state => state.selectedWarehouse,
  
  /**
   * 获取仓库列表
   */
  warehouseList: state => state.warehouseList,
  
  /**
   * 获取选择位置索引
   */
  selectedPosition: state => state.selectedPosition,
  
  /**
   * 根据仓库 ID 获取仓库信息
   */
  getWarehouseById: state => (id) => {
    return state.warehouseList.find(w => w.id === id) || null
  }
}

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