<?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.cyksj.mapper.manage.coupon.CouponMapper">

    <insert id="batchSendCouponToUsers">
        insert into
        coupon_user(`user_id`,`coupon_id`,`channel`,`valid_start_time`,`valid_end_time`,`status`,`created_time`,`update_time`)
        values
        <foreach collection="userIds" item="userId" separator=",">
            (#{userId},#{couponId},#{channel},#{validStartTime},#{validEndTime},#{status},now(),now())
        </foreach>
        ON DUPLICATE KEY UPDATE coupon_id = VALUES(coupon_id)
    </insert>

    <select id="checkExCode" resultType="com.cyksj.model.dto.CouponPopularizeDto">
        select cp.id         as couponId,
               cdp.id        as popularizeId,
               cdp.user_id,
               cdp.distribute_id,
               cp.goods_sku_ids,
               cp.type,
               cp.use_scope,
               cp.scope,
               cdp.coupon_id as popularizeCouponId,
               cdp.is_general,
               cp.goods_type,
               cp.reduce_money,
               cp.reduce_condition,
               cp.discount,
               cp.valid_days,
               cp.valid_hours,
               cp.valid_start_time,
               cp.valid_end_time,
               cp.is_valid_time
        from `coupon` cp
                 left join (select id, distribute_id,coupon_id, ex_code, user_id, is_general
                            from `coupon_distribute_popularize`
                            where deleted is true) cdp
                           on cdp.coupon_id = cp.id
        where cp.deleted is true
          and (cp.ex_code = #{couponExCode} or cdp.ex_code = #{couponExCode}) limit 1
    </select>

    <select id="getRenewCouponBySkuId" resultType="com.cyksj.model.entity.Coupon">
        select c.id
        from coupon c
        inner join coupon_sku cs on cs.coupon_id = c.id and c.deleted is true and cs.deleted is true and
        cs.sku_id = #{skuId} and c.use_scope = 'renew'
        <if test="couponIds.size()>0">
            and c.id not in
            <foreach collection="couponIds" item="item" open="(" separator="," close=")">
                #{item}
            </foreach>
        </if>
        and c.classification_id = 8
        and (select count(*) from coupon_user where user_id = #{userId} and coupon_id = c.id) = 0
        order by discount desc limit 1
    </select>

    <select id="getCouponNameByIds" resultType="java.lang.String">
        select group_concat(name) from coupon where id in
        <foreach collection="list" item="item" open="(" separator="," close=")">
            #{item}
        </foreach>
    </select>
</mapper>