package cn.ysk.cashier.mybatis.mapper;

import cn.ysk.cashier.vo.TbUserCouponVo;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import cn.ysk.cashier.mybatis.entity.TbActivateInRecord;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;

/**
 * 活动商品赠送表(TbActivateInRecord)表数据库访问层
 *
 * @author ww
 * @since 2024-08-22 14:50:16
 */
public interface TbActivateInRecordMapper extends BaseMapper<TbActivateInRecord> {

    @Select("SELECT" +
            "           pro.cover_img as productCover, " +
            "            pro.name as productName, " +
            "            inRecord.id as id," +
            "            inRecord.full_amount as fullAmount," +
            "            inRecord.discount_amount as discountAmount," +
            "            inRecord.coupon_id as couponId," +
            "            pro.id as proId," +
            "            CASE" +
            "                WHEN inRecord.type = 1 THEN inRecord.NAME" +
            "                WHEN inRecord.type = 2 THEN pro.NAME" +
            "            END AS `name`," +
            "            inRecord.type," +
            "            inRecord.over_num as num," +
            "            inRecord.use_end_time as endTime" +
            "        FROM" +
            "            tb_activate_in_record inRecord" +
            "            LEFT JOIN tb_product pro ON inRecord.pro_id = pro.id and pro.shop_id = #{shopId}" +
            "        WHERE" +
            "            inRecord.vip_user_id = #{vipUserId}" +
            "            and inRecord.shop_id = #{shopId}" +
            "            and inRecord.over_num != 0" +
            "            and inRecord.use_start_time < now()" +
            "            and inRecord.use_end_time > now()" +
            "        order by inRecord.use_end_time asc")
    List<TbUserCouponVo> queryByVipIdAndShopId(@Param("vipUserId") Integer vipUserId, @Param("shopId") Integer shopId);

    @Select("SELECT sum( over_num ) from tb_activate_in_record" +
            "         where coupon_id = #{couponId} " +
            "         and now() < use_end_time group by coupon_id ")
    Integer countNoUseCoupon(@Param("couponId") Integer couponId);


    @Update("update tb_activate_in_record" +
            "        set over_num = #{overNum}" +
            "        where id = #{id}")
    int updateOverNum(@Param("id") Integer id, @Param("overNum") Integer overNum);

    @Update("update tb_activate_in_record" +
            "        set over_num = over_num-#{overNum}" +
            "        where id = #{id} and over_num-#{overNum} >= 0")
    int decrOverNum(@Param("id") Integer id, @Param("overNum") Integer decrOverNum);
}

