<?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="org.springblade.modules.mall.mapper.CouponUserMapper">

    <!-- 通用查询映射结果 -->
    <resultMap id="couponUserResultMap" type="org.springblade.modules.mall.entity.CouponUser">
        <result column="id" property="id"/>
        <result column="is_delete" property="isDelete"/>
        <result column="create_user_id" property="createUserId"/>
        <result column="create_time" property="createTime"/>
        <result column="update_user_id" property="updateUserId"/>
        <result column="update_time" property="updateTime"/>
        <result column="coupon_id" property="couponId"/>
        <result column="user_id" property="userId"/>
        <result column="state" property="state"/>
        <result column="user_time" property="userTime"/>
        <result column="order_id" property="orderId"/>
    </resultMap>


    <select id="selectCouponUserPage" resultMap="couponUserResultMap">
        select * from biz_coupon_user where is_deleted = 0
    </select>
    <select id="selectUserCouponList" resultType="org.springblade.modules.mall.vo.CouponUserVO">
        SELECT
            cu.id,
            c.preferential_type,
            c.type,
            c.title,
            c.start_time,
            c.end_time,
            c.discount_ratio,
            c.full_reduction,
            c.discount_amount,
            c.business_scene,
            c.valid_days,
            cu.user_time,
            cu.create_time,
            cu.order_id,
            cu.state
        FROM
            biz_coupon_user cu
            JOIN biz_coupon c ON cu.coupon_id = c.id
        WHERE
            cu.user_id = #{userId}
        <if test="state == 2">
            and state = 2
        </if>
        <if test="state == 1">
            and state = 1 and NOW() <![CDATA[>=]]> c.start_time and NOW() <![CDATA[<=]]> c.end_time
        </if>
        <if test="state == 3">
            and state != 2 and NOW() >= c.end_time
        </if>
    </select>
    <select id="quantity" resultType="org.springblade.modules.api.vo.CouponQuantityVO">
        SELECT
        (
        SELECT
        count( 1 )
        FROM
        biz_coupon_user cu
        JOIN biz_coupon c ON cu.coupon_id = c.id
        WHERE
        cu.user_id = #{userId}
        AND state != 2

        AND NOW() <![CDATA[>=]]> c.end_time
        ) expired,
        ( SELECT count( 1 ) used FROM biz_coupon_user cu JOIN biz_coupon c ON cu.coupon_id = c.id WHERE cu.user_id = #{userId} AND state = 2 ) used,
        (
        SELECT
        count( 1 )
        FROM
        biz_coupon_user cu
        JOIN biz_coupon c ON cu.coupon_id = c.id
        WHERE
        cu.user_id = #{userId}
        AND state = 1
        AND NOW() <![CDATA[>=]]> c.start_time
        AND NOW() <![CDATA[<=]]> c.end_time
        ) unused
    </select>

</mapper>
