import ajax from '../../util/ajax'
import api from '../../util/api'

export default {
  namespaced: true,
  state: {
    goodsList: [],
    goodsInfo: {},
    goodsTypes: [],
    goodsSpecs: [],
  },
  mutations: {
    updateList (state, payload) {
      state.goodsList = payload || []
    },
    updateInfo (state, payload) {
      state.goodsInfo = payload || {}
    },
    updateTypes (state, payload) {
      state.goodsTypes = payload || {}
    },
    updateSpecs (state, payload) {
      state.goodsSpecs = payload || {}
    }
  },
  actions: {
    GetGoodsList ({ commit }, payload) {
      return new Promise((resolve, reject) => {
        ajax(api.goodsManager.getGoodsList.url, {
          method: api.goodsManager.getGoodsList.method,
          queryData: {
            ...payload,
          }
        }).then(res => {
          commit('updateList', res)
          resolve(res)
        }).catch(reject)
      })
    },
    GetGoodTypes ({ commit }, payload) {
      return new Promise((resolve, reject) => {
        ajax(api.goodsManager.getGoodsTypeList.url, {
          method: api.goodsManager.getGoodsTypeList.method,
          queryData: {
            ...payload,
          }
        }).then(res => {
          commit('updateTypes', res)
          resolve(res)
        }).catch(reject)
      })
    },
    GetGoodSpecs ({ commit }, payload) {
      ajax(api.goodsManager.getGoodsSpecList.url, {
        method: api.goodsManager.getGoodsSpecList.method,
        queryData: {
          ...payload,
        }
      }).then(res => {
        commit('updateSpecs', res)
      })
    },
    GetGoodsByID ({ commit }, { id }) {
      ajax(api.goodsManager.getGoodsByID.url, {
        method: api.goodsManager.getGoodsByID.method,
        urlData: {
          id: id,
        }
      }).then(res => {
        commit('updateInfo', res)
      })
    },
    AddGoods ({ commit }, payload) {
      ajax(api.goodsManager.addGoods.url, {
        method: api.goodsManager.addGoods.method,
        data: {
          ...payload
        }
      }).then(res => {
        commit('updateInfo', res)
      })
    },
    UpdateGoods ({ commit }, payload) {
      ajax(api.goodsManager.updateGoods.url, {
        method: api.goodsManager.updateGoods.method,
        data: {
          ...payload
        },
        urlData: {
          id: payload.GoodsId,
        }
      }).then(res => {
      })
    },
    DelGoods ({ commit }, { id, callback }) {
      ajax(api.goodsManager.deleteGoods.url, {
        method: api.goodsManager.deleteGoods.method,
        urlData: {
          id: id,
        }
      }).then(res => {
        callback()
      })
    },
    SetNull ({ commit }) {
      commit('updateInfo', {})
    },
    UpdateInfo ({ commit }, payload) {
      commit('updateInfo', payload)
    }
  }
}
