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

export default {
  namespaced: true,
  state: {
    couponList: [],
  },
  mutations: {
    updateList (state, payload) {
      state.couponList = payload || []
    },
  },
  actions: {
    GetCouponList ({ commit }, payload) {
      return new Promise((resolve, reject) => {
        ajax(api.couponManager.couponList.url, {
          method: api.couponManager.couponList.method,
          queryData: {
            ...payload,
          }
        }).then(res => {
          commit('updateList', res)
          resolve(res)
        }).catch(reject)
      })
    },
    addCoupon ({ commit }, payload) {
      return new Promise((resolve, reject) => {
        ajax(api.couponManager.addCoupon.url, {
          method: api.couponManager.addCoupon.method,
          data: {
            info: JSON.stringify(payload)
          }
        }).then(res => {
          resolve(res)
        }).catch(reject)
      })
    },
    getCouponById ({ commit }, { id }) {
      return new Promise((resolve, reject) => {
        ajax(api.couponManager.getCouponById.url, {
          method: api.couponManager.getCouponById.method,
          urlData: {
            id,
          }
        }).then(res => {
          resolve(res)
        }).catch(reject)
      })
    },
    editCoupon ({ commit }, payload) {
      return new Promise((resolve, reject) => {
        ajax(api.couponManager.editCoupon.url, {
          method: api.couponManager.editCoupon.method,
          data: {
            info: JSON.stringify(payload)
          },
          urlData: {
            id: payload.CouponId
          },
        }).then(res => {
          resolve(res)
        }).catch(reject)
      })
    },
    GiveCoupon ({ commit }, { id, users }) {
      return new Promise((resolve, reject) => {
        ajax(api.couponManager.giveCoupon.url, {
          method: api.couponManager.giveCoupon.method,
          urlData: {
            id,
            users
          },
        }).then(res => {
          resolve(res)
        }).catch(reject)
      })
    }
  }
}
