package com.fzm.mall.server.admin.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.SystemClock;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fzm.mall.server.admin.constant.MallResponseError;
import com.fzm.mall.server.admin.exception.MyException;
import com.fzm.mall.server.admin.marketing.model.Coupon;
import com.fzm.mall.server.admin.user.mapper.UserCouponMapper;
import com.fzm.mall.server.admin.user.model.UserCoupon;
import com.fzm.mall.server.admin.user.service.IUserCouponService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 用户与优惠券对应表 服务实现类
 * </p>
 *
 * @author fzm
 * @since 2021-04-13
 */
@Service
@Transactional
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class UserCouponServiceImpl extends ServiceImpl<UserCouponMapper, UserCoupon> implements IUserCouponService {

    private final UserCouponMapper userCouponMapper;

    @Override
    public void restoreCoupon(String uid, List<Coupon> couponList) {
        couponList.forEach(coupon -> {
            UserCoupon userCoupon = userCouponMapper.selectOne(new QueryWrapper<UserCoupon>().eq("uid", uid).eq("coupon_id", coupon.getCouponId()));
            boolean couponIsEffective = (coupon.getStartTime() <= SystemClock.now()) && (coupon.getEndTime() >= SystemClock.now());
            int status = UserCoupon.STATUS_INVALID;
            if (couponIsEffective) {
                status = UserCoupon.STATUS_EFFECTIVE;
            }
            userCoupon.setStatus(status);
            int update = userCouponMapper.update(userCoupon, new UpdateWrapper<UserCoupon>().eq("uid", uid)
                    .eq("coupon_id", coupon.getCouponId()).eq("update_time", userCoupon.getUpdateTime()));
            if (update == 0) {
                throw new MyException(MallResponseError.UPDATE_FAIL);
            }
        });
    }
}
