<?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.user.mapper.ShopCustomerMapper">
  <resultMap id="shopCustomerMap" type="com.tmerclub.cloud.user.model.ShopCustomer">
    <id column="shop_customer_id" property="shopCustomerId" />
    <result column="user_id" property="userId"/>
    <result column="member_name" property="memberName"/>
    <result column="shop_id" property="shopId"/>
    <result column="level_type" property="levelType"/>
    <result column="level_id" property="levelId"/>
    <result column="level" property="level"/>
    <result column="growth" property="growth"/>
    <result column="regist_time" property="registTime"/>
    <result column="vip_end_time" property="vipEndTime"/>
    <result column="create_time" property="createTime"/>
    <result column="update_time" property="updateTime"/>
  </resultMap>
  <select id="listByParam" resultType="com.tmerclub.cloud.api.user.vo.UserManagerVO">
    select sc.shop_id, sc.user_id, u.nick_name, u.phone, u.pic
    from shop_customer sc
    join user u on sc.user_id = u.user_id
    <where>
      sc.shop_id = #{shopCustomerDTO.shopId}
      <if test="shopCustomerDTO.nickName != null and shopCustomerDTO.nickName != ''">
        AND u.nick_name LIKE CONCAT('%',#{shopCustomerDTO.nickName},'%')
      </if>
      <if test="shopCustomerDTO.phone != null and shopCustomerDTO.phone != ''">
        AND u.phone LIKE CONCAT('%',#{shopCustomerDTO.phone},'%')
      </if>
    </where>
    order by sc.create_time desc
  </select>
  <insert id="saveBatch">
    insert into shop_customer (`user_id`,`member_name`,`shop_id`,`level_type`,`level_id`,`level`,`growth`,`regist_time`,`vip_end_time`)  values
    <foreach collection="shopCustomers" item="shopCustomer" separator=",">
      (#{shopCustomer.userId},#{shopCustomer.memberName},#{shopCustomer.shopId},#{shopCustomer.levelType},#{shopCustomer.levelId},#{shopCustomer.level},#{shopCustomer.growth},#{shopCustomer.registTime},#{shopCustomer.vipEndTime})
    </foreach>
  </insert>

  <select id="listNotExistByShopIdAndUserIds" resultMap="shopCustomerMap">
    SELECT DISTINCT u.user_id
    FROM `user` u
    LEFT JOIN shop_customer sc ON u.user_id = sc.user_id AND shop_id = #{shopId}
    WHERE sc.shop_id IS NULL AND u.user_id in
    <foreach collection="userIds" item="userId" open="(" separator="," close=")">
      #{userId}
    </foreach>
  </select>
  <select id="getIsShopCustomer" resultType="java.lang.Integer">
    SELECT COUNT(shop_customer_id) > 0 FROM shop_customer WHERE user_id = #{userId} AND shop_id = #{shopId}
  </select>
</mapper>
