package cn.com.ty.lift.ud.userCoupon.mapper;


import cn.com.ty.lift.ud.userCoupon.controller.query.UserCouponQuery;
import cn.com.ty.lift.ud.userCoupon.mapper.entity.UserCoupon;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.math.BigDecimal;
import java.util.List;
/**
 * 用户卡券 -Repository
 * 
 * @author Xson
 * @date 2020-05-12
 */
public interface UserCouponMapper extends BaseMapper<UserCoupon> {
	
	List<UserCoupon> selectByQuery(@Param("ew") Wrapper wrapper, @Param("page") UserCouponQuery page);

    int countByQuery(@Param("ew") Wrapper wrapper);

	@Update("UPDATE user_coupon SET used_flag=0 WHERE coupon_id=#{couponId} ")
	void updateUsedFlagByCouponId(@Param("couponId")Long couponId);
	
	@Select(" SELECT COUNT(*) FROM user_coupon a LEFT JOIN coupon b ON a.coupon_id=b.id WHERE a.user_id=#{userId} AND a.used_flag=1 AND b.type=#{type} ")
	Integer getCouponNum(@Param("userId")Long userId,@Param("type")Integer type);
	
	@Select(" SELECT * FROM user_coupon a LEFT JOIN coupon b ON a.coupon_id=b.id WHERE a.user_id=#{userId} AND a.used_flag=1 AND b.type=#{type} AND b.full_reduction<=#{amount}")
	List<UserCoupon> queryAllCoupon(@Param("userId")Long userId,@Param("type")Integer type,@Param("amount")BigDecimal amount);
	
	@Select(" SELECT * FROM user_coupon a LEFT JOIN coupon b ON a.coupon_id=b.id WHERE a.user_id=#{userId} AND a.used_flag=1 AND b.type=#{type}")
	List<UserCoupon> queryAllRed(@Param("userId")Long userId,@Param("type")Integer type);
	
	/**
	 * 使用红包
	 * @param couponId 红包id
	 * @param status 状态
	 * @param userId 用户id
	 * @param orderid 订单id
	 * @return
	 */
	@Update("UPDATE user_coupon SET used_flag=#{status},order_id=#{orderid} WHERE id=#{id} ")
	int updateOrderIdAndStatusByCouponIdAndUserId(@Param("id")Long id,@Param("status")Integer status,@Param("orderid")Long orderid);
}
