<?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.iamberry.wechat.service.mapper.QrcodeMapper">

	<!-- 根据ID，获取二维码的类型、使用人 -->
	<select id="selectQrcodeByQrcodeId" parameterType="Integer" resultType="Qrcode">
		SELECT
			QRCODE_TYPE qrcodeType, 
			QRCODE_REPLACE_OPENID qrcodeReplaceOpenid
		FROM 
			TB_IAMBERRY_USER_QRCODE
		WHERE
			QRCODE_ID = #{qrcodeId}
	</select>
	
	<!-- 根据二维码ID, 更新二维码状态 -->
	<update id="updateQrcodeStatusById" parameterType="Integer">
		UPDATE 
			TB_IAMBERRY_USER_QRCODE 
		SET  
			QRCODE_STATUS = 2
		WHERE 
			QRCODE_ID = #{qrcodeId}
	</update>
	
	<!-- 根据二维码会员Openid, 更新二维码状态 -->
	<update id="updateQRcodeStatusByUserOpenid" parameterType="String">
		UPDATE 
			TB_IAMBERRY_USER_QRCODE 
		SET  
			QRCODE_STATUS = 2
		WHERE 
			QRCODE_REPLACE_OPENID = #{openid}
	</update>
	
	<!-- 为二维码叠加访问次数和吸收用户人数 -->
	<update id="updateQRcodeScannNumAndSubNum" parameterType="Qrcode">
		UPDATE 
			TB_IAMBERRY_USER_QRCODE 
		SET  
			QRCODE_SCANN_NUM = (QRCODE_SCANN_NUM + #{qrcodeScannNum}),
			QRCODE_SUB_NUM = (QRCODE_SUB_NUM + #{qrcodeSubNum})
		WHERE 
			QRCODE_ID = #{qrcodeId}
	</update>
	
	<!-- 获取数据库中空余的二维码 -->
	<select id="selectSpareQrcode" resultType="Qrcode">
		SELECT 
			QRCODE_ID qrcodeId, QRCODE_URL qrcodeUrl
		FROM 
			TB_IAMBERRY_USER_QRCODE 
		WHERE 
			QRCODE_TYPE = 1 AND QRCODE_STATUS = 2
		LIMIT 0, 1
	</select>
	
	<!-- 修改二维码所属人、状态,但是二维码状态必须是空余的 -->
	<update id="updateQRcodeUserAndStatusById" parameterType="Qrcode">
		UPDATE 
			TB_IAMBERRY_USER_QRCODE 
		SET  
			QRCODE_REPLACE_OPENID = #{qrcodeReplaceOpenid},
			QRCODE_STATUS = #{qrcodeStatus}
		WHERE 
			QRCODE_ID = #{qrcodeId} AND QRCODE_STATUS = 2
	</update>
	
	<!-- 添加一个二维码 -->
	<insert id="insertQrcode" parameterType="Qrcode" useGeneratedKeys="true" keyProperty="qrcodeId">
		 INSERT INTO 
		 	TB_IAMBERRY_USER_QRCODE
		 		(
			 		QRCODE_TYPE, QRCODE_OPENID, QRCODE_REPLACE_OPENID, 
			 		QRCODE_CREATE_DATE, QRCODE_URL, QRCODE_VALUE, QRCODE_STATUS,
			 		QRCODE_SCANN_NUM, QRCODE_SUB_NUM
				)
		 VALUES 
		  	( 
			  #{qrcodeType},  
			  #{qrcodeOpenid},
			  #{qrcodeReplaceOpenid}, 
			  NOW(),
			  #{qrcodeUrl},
			  #{qrcodeValue},
			  #{qrcodeStatus},
			  #{qrcodeScannNum},
			  #{qrcodeSubNum}
		  	)
	</insert>
	
	<!-- 根据当前使用人，获取对应的Qrcode -->
	<select id="selectQrcodeUrlByReplaceUser" parameterType="String" resultType="String">
		SELECT
			 QRCODE_URL qrcodeUrl
		FROM
			TB_IAMBERRY_USER_QRCODE
		WHERE
			QRCODE_REPLACE_OPENID = #{qrcodeReplaceOpenid} AND QRCODE_STATUS = 1
	</select>
	
	<!-- 根据ID，修改二维码URL -->
	<update id="updateQrcodeURLByOpenid" parameterType="Qrcode">
		UPDATE 
			TB_IAMBERRY_USER_QRCODE 
		SET  
			QRCODE_URL = #{qrcodeUrl}
			<if test="qrcodeValue != null">
				, QRCODE_VALUE = #{qrcodeValue}
			</if> 
		WHERE 
			QRCODE_ID = #{qrcodeId}
	</update>
</mapper>