<?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.tmerclub.cloud.coupon.mapper.CouponLockMapper">
    <resultMap id="couponLockMap" type="com.tmerclub.cloud.coupon.model.CouponLock">
        <id column="id" property="id"/>
        <result column="create_time" property="createTime"/>
        <result column="update_time" property="updateTime"/>
        <result column="coupon_id" property="couponId"/>
        <result column="coupon_user_id" property="couponUserId"/>
        <result column="user_id" property="userId"/>
        <result column="order_ids" property="orderIds"/>
        <result column="amount" property="amount"/>
        <result column="status" property="status"/>
    </resultMap>
    <insert id="saveBatch">
        insert into coupon_lock (`coupon_id`, `coupon_user_id`, `user_id`, `order_ids`, `amount`, `status`)
        values
        <foreach collection="couponLocks" item="couponLock" separator=",">
            (#{couponLock.couponId}, #{couponLock.couponUserId}, #{couponLock.userId}, #{couponLock.orderIds},
            #{couponLock.amount}, #{couponLock.status})
        </foreach>
    </insert>
    <select id="listCouponUserIdsByOrderId" resultType="java.lang.Long">
        SELECT coupon_user_id
        FROM coupon_lock
        WHERE FIND_IN_SET(#{orderId}, order_ids)
          and status = 0
    </select>
    <update id="unLockByIds">
        update coupon_lock
        set status = -1 where coupon_user_id in
        <foreach collection="couponUserIds" item="couponUserId" separator="," open="(" close=")">
            #{couponUserId}
        </foreach>
        and status = 0
    </update>

    <update id="markerCouponUse">
        update coupon_lock
        set status = 1 where
        <foreach collection="orderIds" item="orderId" separator=" OR ">
            FIND_IN_SET(#{orderId}, order_ids)
        </foreach>
    </update>

    <select id="getUserCouponIdByOrderId" resultMap="couponLockMap">
        SELECT cl.coupon_user_id, cl.order_ids
        FROM coupon_lock cl
        WHERE FIND_IN_SET(#{orderId}, cl.order_ids)
    </select>

    <select id="getUnConfirmAndLockCoupon" resultMap="couponLockMap">
        SELECT coupon_user_id
        FROM coupon_lock
        WHERE `status` != -1 and coupon_user_id IN
        <foreach collection="couponUserIds" item="couponUserId" open="(" close=")" separator=",">
            #{couponUserId}
        </foreach>
    </select>
</mapper>
