<?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">
<!-- 命名，每一个映射对象不一样
	namespace:必须与对应的接口全类名一致
 -->
<mapper namespace="com.iamberry.wechat.service.mapper.GiftCardPayCodeMapper">
	<sql id="payCodeField">
		CODE_ID codeId,
		CODE_PASSWORD codePassword,
		CODE_STATUS codeStatus,
		CODE_REFERRER_OPENID codeReferrerOpenid,
		CODE_USE_OPENID codeUseOpenid,
		CODE_CREATE_DATE codeCreateDate,
		CODE_UPDATE_DATE codeUpdateDate,
		CODE_REMARK codeRemark
	</sql>
	
	<!-- 批量添加抵扣密码记录 -->
	<insert id="insertPayCodeList" parameterType="ArrayList">
		<selectKey resultType="int" keyProperty="codeId" order="AFTER"> 
			SELECT 
			LAST_INSERT_ID() 
		</selectKey> 
		INSERT INTO TB_IAMBERRY_GIFT_CARD_PAY_CODE
		(
			CODE_PASSWORD ,
			CODE_STATUS ,
			CODE_REFERRER_OPENID ,
			CODE_USE_OPENID ,
			CODE_CREATE_DATE ,
			CODE_UPDATE_DATE ,
			CODE_REMARK
		) 
		VALUES 
		<foreach collection="list" item="item" index="index" separator="," >
		(
			#{item.codePassword},#{item.codeStatus},#{item.codeReferrerOpenid},#{item.codeUseOpenid},
			NOW(),#{item.codeUpdateDate},#{item.codeRemark}
		)
		</foreach>  
	</insert>
	
	<!-- 查询所有抵扣密码 -->
	<select id="listPayCode" parameterType="GiftCardPayCode" resultType="GiftCardPayCode">
		SELECT 
			C.*, U1.USER_NICKNAME codeReferrerName, U2.USER_NICKNAME codeUseOpenName
		FROM TB_IAMBERRY_GIFT_CARD_PAY_CODE c
		LEFT JOIN TB_IAMBERRY_USER_USERINFO U1 ON C.CODE_REFERRER_OPENID = U1.USER_OPENID
		LEFT JOIN TB_IAMBERRY_USER_USERINFO U2 ON C.CODE_USE_OPENID = U2.USER_OPENID
		ORDER BY CODE_CREATE_DATE DESC
		<if test="page!=null and page.recordBegin>0 and page.pageSize>0 ">
	     LIMIT ${page.recordBegin},${page.pageSize}
	    </if>
	     <if test="page!=null and page.recordBegin==0 and page.pageSize>0 ">
	     LIMIT ${page.pageSize} 
	    </if>
	</select>
	
	<!-- 查询所有抵扣密码 -->
	<select id="countPayCode" resultType="Integer">
		SELECT 
			COUNT(CODE_ID)
		FROM TB_IAMBERRY_GIFT_CARD_PAY_CODE
	</select>
	
	<!--  根据支付密码查询抵扣码信息-->
	<select id="getPayCodeByIdOrPassword" parameterType="GiftCardPayCode" resultType="GiftCardPayCode">
		SELECT 
			<include refid="payCodeField"></include>
		FROM TB_IAMBERRY_GIFT_CARD_PAY_CODE
		<where>
			<if test="codeId != null and codeId != ''">
				CODE_ID = #{codeId}
			</if>
			<if test="codePassword != null and codePassword != ''">
				AND CODE_PASSWORD = #{codePassword}
			</if>
		</where>
	</select>
	
	
	<!-- 根据openid 修改使用状态和使用人openid -->
	<update id="updatePayCodeStatusAndUseOpenId" parameterType="GiftCardPayCode">
		UPDATE TB_IAMBERRY_GIFT_CARD_PAY_CODE
		SET 
			CODE_STATUS = #{codeStatus},
			CODE_USE_OPENID=#{codeUseOpenid},
			CODE_UPDATE_DATE=NOW()
		WHERE CODE_ID = #{codeId}
	</update>
	
</mapper>
