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

import cn.com.ty.lift.ud.coupon.mapper.entity.Coupon;
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.util.List;

/**
 * 卡券 -Repository
 * 
 * @author Xson
 * @date 2020-05-08
 */
public interface CouponMapper extends BaseMapper<Coupon> {

    @Select("SELECT *  FROM coupon WHERE DATE_FORMAT(validity,'%Y-%m-%d %T') <= NOW()")
    List<Coupon> getAllFailureByDate();

    /**
     * 根据用户及卡券id查询是否有效
     * 
     * @param userId
     *            用户id
     * @param couponIds
     *            卡券集
     * @param scenario
     *            卡券使用范围 0:全场通用1:出诊问诊2:题库3:视频',
     * @return
     */
    @Select("SELECT coupon.* from user_coupon as users ,coupon where users.coupon_id = coupon.id  and coupon.scenario = #{scenario} and coupon.check_falg = 1  and unix_timestamp(coupon.validity) >=  unix_timestamp(NOW()) and users.used_flag = 1 and users.id = #{couponIds} and  users.user_id = #{userId}")
    Coupon findListByUserIdAndCouponId(@Param("userId") Long userId, @Param("couponIds") Long couponIds,
        @Param("scenario") Integer scenario);
    
    @Update("UPDATE coupon set check_falg=#{CheckStatus},statuz=#{status} where id=#{id}")
    void updateSatus(@Param("id")Long id,@Param("CheckStatus")Integer CheckStatus,@Param("status")Integer status);
    /**
     * 根据用户及卡券id查询是否有效
     * 
     * @param userId
     *            用户id
     * @param couponIds
     *            卡券集
     * @param scenario
     *            卡券使用范围 0:全场通用1:出诊问诊2:题库3:视频',
     * @return
     */
    @Select("SELECT coupon.* from user_coupon as users ,coupon where users.coupon_id = coupon.id  and coupon.scenario = #{scenario} and coupon.check_falg = 1   and users.used_flag = 1 and users.id = #{couponIds} and  users.user_id = #{userId}")
    Coupon findListByUserIdAndPacketId(@Param("userId") Long userId, @Param("couponIds") Long couponIds,
        @Param("scenario") Integer scenario);

    @Update("UPDATE coupon set statuz=0 where id=#{id}")
    void updateCouponById(@Param("id") Long id);
    
    @Select("SELECT b.* FROM user_coupon a LEFT JOIN coupon b ON a.coupon_id=b.id WHERE a.id=#{id}")
    Coupon getByCouponId(@Param("id")Long id);
    
    @Update("UPDATE user_coupon set used_flag=1,order_id=null WHERE id=#{id}")
    void updateUserCouponStatuz (@Param("id")Long id);
}
