<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.ycwl.basic.mapper.CouponRecordMapper">
    <select id="queryByUserWithGoodsId"
            resultType="com.ycwl.basic.model.pc.couponRecord.entity.CouponRecordEntity">
        select * from coupon_record where deleted = 0 and member_id = #{memberId} and coupon_id in (select id from coupon where deleted = 0 and scenic_id = #{scenicId} and FIND_IN_SET(#{goodsId},config_ids))
    </select>
    
    <select id="queryByMemberIdAndFaceId"
            resultType="com.ycwl.basic.model.pc.couponRecord.entity.CouponRecordEntity">
        select * from coupon_record where deleted = 0 and member_id = #{memberId} and face_id = #{faceId}
    </select>
    
    <select id="queryByMemberIdAndFaceIdAndType"
            resultType="com.ycwl.basic.model.pc.couponRecord.entity.CouponRecordEntity">
        select cr.* 
        from coupon_record cr 
        inner join coupon c on cr.coupon_id = c.id 
        where cr.deleted = 0 and c.deleted = 0 and cr.member_id = #{memberId} and cr.face_id = #{faceId} and c.type = #{type}
        limit 1
    </select>
    
    <select id="selectByPageQuery"
            resultType="com.ycwl.basic.model.pc.couponRecord.resp.CouponRecordPageResp">
        select 
            cr.id,
            cr.coupon_id as couponId,
            c.name as couponName,
            c.type as couponType,
            CASE c.type 
                WHEN 0 THEN '普通优惠券'
                WHEN 1 THEN '第一次推送'
                WHEN 2 THEN '第二次推送'
                WHEN 3 THEN '第三次推送'
                ELSE '未知类型'
            END as couponTypeName,
            cr.member_id as memberId,
            cr.face_id as faceId,
            c.scenic_id as scenicId,
            s.name as scenicName,
            cr.status,
            CASE cr.status 
                WHEN 0 THEN '未使用'
                WHEN 1 THEN '已使用'
                ELSE '未知状态'
            END as statusName,
            cr.create_time as createTime,
            cr.used_time as usedTime,
            cr.used_order_id as usedOrderId
        from coupon_record cr 
        inner join coupon c on cr.coupon_id = c.id 
        inner join scenic s on c.scenic_id = s.id
        <where>
            and cr.deleted = 0 and c.deleted = 0
            <if test="scenicId != null">
                and c.scenic_id = #{scenicId}
            </if>
            <if test="couponName != null and couponName != ''">
                and c.name like concat('%', #{couponName}, '%')
            </if>
            <if test="couponType != null">
                and c.type = #{couponType}
            </if>
            <if test="status != null">
                and cr.status = #{status}
            </if>
        </where>
        order by cr.create_time desc
    </select>
</mapper>