import { listWarehouse } from "@/api/jxc/warehouse";

const state = {
  warehouse: {},
  warehouseList: [],
  loading: false,
}
const mutations = {
  SET_WAREHOUSE: (state, warehouse) => {
    state.warehouse = warehouse;
  },
  SET_WAREHOUSE_LIST: (state, warehouseList) => {
    state.warehouseList = warehouseList;
  },
  SET_LOADING: (state, loading) => {
    state.loading = loading;
  },
}

const actions = {
  setWarehouse({ commit, state }, data) {
    if (data) {
      commit('SET_WAREHOUSE_LIST', data);
      const obj = {};
      data.forEach(node => {
        if (node.stockCode) {
          obj[node.stockCode] = node;
        }
      });
      commit('SET_WAREHOUSE', obj);
    }

  },
  getWarehouse({ commit, state }, data) {
    if (state.loading || state.warehouseList.length > 0) {
      return;
    }
    commit('SET_LOADING', true);
    listWarehouse().then(res => {
      if (res.data) {
        commit('SET_WAREHOUSE_LIST', res.data || []);

        if (res.data) {
          const obj = {};
          res.data.forEach(node => {
            if (node.stockCode) {
              obj[node.stockCode] = node;
            }
          });
          commit('SET_WAREHOUSE', obj);
        }

      }
      commit('SET_LOADING', false);
    }).catch(e => {
      commit('SET_LOADING', false);
    });
  }
}

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