import { fetchReceivedCouponCount, receiveCoupon } from '@/services/api/coupon.js'

const state = {
	expiredNum: 0, // 已过期
	unusedNum: 0, // 未使用
	usedNum: 0 // 已使用
}

const mutations = {
	//设置优惠券数量
	SET_COUPON_COUNT: (state, data) => {
		state.expiredNum = data.expiredNum
		state.unusedNum = data.unusedNum
		state.usedNum = data.usedNum
	}
}

const actions = {
	// 领取优惠券
	async receiveCoupon({ rootGetters, dispatch }, { couponId, couponShareId }) {
		try {
			const res = await receiveCoupon({ couponId, couponShareId, userId: rootGetters.userId })
			uni.showToast({
				icon: 'success',
				title: '领取成功'
			})
			await dispatch('initCouponCount')
			return res
		} catch (e) {
			console.log(e)
		}
	},
	// 初始化已领取优惠券数量
	async initCouponCount({ commit, rootGetters }) {
		try {
			const res = await fetchReceivedCouponCount({ userId: rootGetters.userId })
			commit('SET_COUPON_COUNT', res.data)
			return res
		} catch (e) {
			console.log(e)
		}
	}
}

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