<?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.UserMapper">
  <resultMap id="userMap" type="com.tmerclub.cloud.user.model.User">
    <id column="user_id" property="userId" />
    <result column="create_time" property="createTime"/>
    <result column="update_time" property="updateTime"/>
    <result column="nick_name" property="nickName"/>
    <result column="sex" property="sex"/>
    <result column="birth_date" property="birthDate"/>
    <result column="pic" property="pic"/>
    <result column="status" property="status"/>
    <result column="level" property="level"/>
    <result column="vip_end_time" property="vipEndTime"/>
    <result column="level_type" property="levelType"/>
    <result column="phone" property="phone"/>
  </resultMap>

  <resultMap id="userAndOpenIdsMap" type="com.tmerclub.cloud.api.user.vo.UserApiVO">
    <!--
      WARNING - @mbg.generated
    -->
    <id column="user_id" jdbcType="VARCHAR" property="userId" />
    <result column="nick_name" jdbcType="VARCHAR" property="nickName" />
    <result column="sex" jdbcType="CHAR" property="sex" />
    <result column="birth_date" jdbcType="CHAR" property="birthDate" />
    <result column="pic" jdbcType="VARCHAR" property="pic" />
    <result column="status" jdbcType="INTEGER" property="status" />
    <result column="level_type" jdbcType="INTEGER" property="levelType" />
    <result column="level" jdbcType="INTEGER" property="level" />
    <result column="prod_recommendation" jdbcType="INTEGER" property="prodRecommendation" />
    <collection property="bizUserIdList"  javaType="java.util.List" ofType="string">
      <id column="bizUserIdList" />
    </collection>
  </resultMap>

  <sql id="Vo_Column_List">
    `user_id`,`create_time`,`update_time`,`nick_name`,`sex`,`birth_date`,`pic`,`status`,`level`,`vip_end_time`,`level_type`,`phone`,`vip_level`,`prod_recommendation`
  </sql>
  <select id="list" resultType="com.tmerclub.cloud.user.vo.UserVO">
    select <include refid="Vo_Column_List"/>
    from user
    <where>
      <if test="userManagerDTO.nickName != null and userManagerDTO.nickName != ''">
        nick_name like concat('%', #{userManagerDTO.nickName},'%')
      </if>
    </where>
    order by user_id desc
  </select>
  <select id="getByUserId" resultType="com.tmerclub.cloud.api.user.vo.UserApiVO">
    select <include refid="Vo_Column_List"/> from user where user_id = #{userId}
  </select>

  <insert id="save">
    insert into user (`user_id`,`nick_name`,`sex`,`birth_date`,`pic`,`status`,`level`,`vip_end_time`,`level_type`,`phone`,`prod_recommendation`)
    values (#{user.userId},#{user.nickName},#{user.sex},#{user.birthDate},#{user.pic},#{user.status},#{user.level},#{user.vipEndTime},#{user.levelType},#{user.phone},#{user.prodRecommendation});
  </insert>

  <select id="filterExistUsers" resultType="com.tmerclub.cloud.user.model.User">
    select * from (
    <foreach collection="users" item="user" separator="UNION ALL">
      SELECT #{user.userId} `user_id`,#{user.nickName} `nick_name`,#{user.sex} `sex`,#{user.birthDate} `birth_date`,#{user.pic} `pic`,
      #{user.status} `status`,#{user.level} `level`,#{user.vipEndTime} `vip_end_time`,#{user.levelType} `level_type`, #{user.phone} `phone`,#{user.vipLevel} `vip_level`
      FROM DUAL
    </foreach>
    ) a WHERE NOT EXISTS (SELECT `user_id`,`phone` FROM `user` b WHERE a.`phone` = b.`phone` or a.`user_id` = b.`user_id`)
  </select>

    <insert id="saveBatch" parameterType="java.util.List">
      insert into `user` (`user_id`,`nick_name`,`sex`,`birth_date`,`pic`,`status`,`level`,`vip_end_time`,`level_type`,`phone`,`vip_level`)
      values
        <foreach collection="users" item="user" separator=",">
          ( #{user.userId}, #{user.nickName}, #{user.sex}, #{user.birthDate}, #{user.pic}, #{user.status}, #{user.level}, #{user.vipEndTime}, #{user.levelType}, #{user.phone}, #{user.vipLevel} )
        </foreach>
    </insert>

    <update id="update">
    update user
    <set>
      <if test="user.nickName != null">
        `nick_name` = #{user.nickName},
      </if>
      <if test="user.sex != null">
        `sex` = #{user.sex},
      </if>

        `birth_date` = #{user.birthDate},

      <if test="user.pic != null">
        `pic` = #{user.pic},
      </if>
      <if test="user.phone != null">
        `phone` = #{user.phone},
      </if>
      <if test="user.status != null">
        `status` = #{user.status},
      </if>
      <if test="user.level != null">
        `level` = #{user.level},
      </if>
      <if test="user.prodRecommendation != null">
        `prod_recommendation` = #{user.prodRecommendation},
      </if>
    </set>
    where user_id = #{user.userId}
  </update>

  <update id="updateUserLevel">
    UPDATE
    user
    SET
    `level` = #{level}
    WHERE user_id IN
    (SELECT user_id FROM user_extension WHERE level_type = 1 AND growth &gt; #{minGrowth}
    <if test="maxGrowth != null">
      AND growth &lt; #{maxGrowth}
    </if>
    )
  </update>
  <update id="updateUserLevelByUserExtensionAndUserIds" parameterType="java.util.List">
    UPDATE `user` u INNER JOIN `user_extension` ue SET u.level = ue.level
    WHERE u.user_id = ue.user_id AND
    u.user_id IN
    <foreach collection="userIds" item="userId" separator="," open="(" close=")">
      #{userId}
    </foreach>
  </update>
  <select id="getUserByUserIds" resultType="com.tmerclub.cloud.api.user.vo.UserApiVO">
    select `user_id`,`nick_name`,`pic`,`create_time`, phone, status from user
    where user_id in
      <foreach collection="userIds" item="userId" separator="," open="(" close=")">
        #{userId}
      </foreach>
    order by user_id desc
  </select>
  <select id="countUserPageByParam" resultType="java.lang.Long"
          parameterType="com.tmerclub.cloud.user.dto.UserManagerDTO">
    SELECT COUNT(u.user_id)
    FROM `user` u
    <if test="userManagerDTO.shopId != null and userManagerDTO.shopId != 0">
      join shop_customer sc on sc.user_id = u.user_id and sc.shop_id = #{userManagerDTO.shopId}
    </if>
    left JOIN user_level ul ON ul.level = u.level AND ul.level_type = u.level_type
    JOIN user_extension ue ON ue.`user_id` = u.user_id

    <where>
      <if test="userManagerDTO.nickName != null and userManagerDTO.nickName != ''">
        AND u.nick_name LIKE CONCAT('%',#{userManagerDTO.nickName},'%')
      </if>
      <if test="userManagerDTO.status != null">
        AND u.status = #{userManagerDTO.status}
      </if>
      <if test="userManagerDTO.levelType != null">
        AND u.level_Type = #{userManagerDTO.levelType}
        <if test="userManagerDTO.level != null">
          <if test="userManagerDTO.levelType == 0">
            AND u.level = #{userManagerDTO.level}
          </if>
          <if test="userManagerDTO.levelType == 1">
            AND u.vip_level = #{userManagerDTO.level}
          </if>
        </if>
      </if>
      <if test="userManagerDTO.phone != null and userManagerDTO.phone != ''">
        AND u.phone LIKE CONCAT('%',#{userManagerDTO.phone},'%')
      </if>
      <if test="userManagerDTO.tagIds != null and userManagerDTO.tagIds.size() > 0">
        AND u.user_id IN
        (
        SELECT DISTINCT(utg.user_id) FROM `user_tag_user` utg
        WHERE utg.user_tag_id IN
        <foreach collection="userManagerDTO.tagIds" item="tagId" index="index" open="(" close=")" separator=",">
          #{tagId}
        </foreach>
        )
      </if>
      <if test="userManagerDTO.userIds != null and userManagerDTO.userIds.size() > 0">
        AND u.user_id IN
        <foreach collection="userManagerDTO.userIds" item="userId" open="(" close=")" separator=",">
          #{userId}
        </foreach>
      </if>
      <if test="userManagerDTO.createStartTime != null and userManagerDTO.createEndTime !=  null ">
        AND (u.create_time between #{userManagerDTO.createStartTime} and #{userManagerDTO.createEndTime})
      </if>
    </where>
    ORDER BY u.create_time DESC
  </select>
  <select id="listUserByParam" resultType="com.tmerclub.cloud.api.user.vo.UserManagerVO">
    SELECT utemp.*,
    <!-- start初始化订单的数据 -->
    @consAmount := 0 AS consAmount,
    @actualAmount := 0 AS actualAmount,
    @consTimes := 0 AS consTimes,
    @reduceAmount := 0 AS reduceAmount,
    @averDiscount := 0.00 AS averDiscount,
    @afterSaleAmount := 0 AS afterSaleAmount,
    @afterSaleTimes := 0 AS afterSaleTimes,
    <!-- end初始化订单的数据 -->
    utemp.growth as growth
    FROM (
    SELECT
      u.nick_name,u.status,u.pic,u.level,u.level_type,u.vip_level,ul.level_name,pul.level_name as vip_level_name,
      u.user_id,ue.score,ue.`score` AS currentScore,u.create_time,u.update_time,u.phone,
      <if test="userManagerDTO.paySysType == 1">
        ue.allinpay_balance AS sumBalance,
        IFNULL(ue.allinpay_actual_balance,0) AS currentBalance,
      </if>
      <if test="userManagerDTO.paySysType != 1">
        ue.balance AS sumBalance,
        IFNULL(ue.actual_balance,0) AS currentBalance,
      </if>
      ue.growth AS growth
    FROM `user` u
    <if test="userManagerDTO.shopId != null and userManagerDTO.shopId != 0">
      join shop_customer sc on sc.`user_id` = u.user_id and sc.shop_id = #{userManagerDTO.shopId}
    </if>
    LEFT JOIN user_level pul ON pul.level = u.vip_level AND pul.level_type = 1
    LEFT JOIN user_level ul ON ul.level = u.level AND ul.level_type = 0
    JOIN user_extension ue ON ue.`user_id` = u.user_id
    <where>
      <if test="userManagerDTO.nickName != null and userManagerDTO.nickName != ''">
        AND u.nick_name LIKE CONCAT('%',#{userManagerDTO.nickName},'%')
      </if>
      <if test="userManagerDTO.status != null">
        AND u.status = #{userManagerDTO.status}
      </if>
      <if test="userManagerDTO.levelType != null">
        AND u.level_Type = #{userManagerDTO.levelType}
        <if test="userManagerDTO.level != null">
          <if test="userManagerDTO.levelType == 0">
            AND u.level = #{userManagerDTO.level}
          </if>
          <if test="userManagerDTO.levelType == 1">
            AND u.vip_level = #{userManagerDTO.level}
          </if>
        </if>
      </if>
      <if test="userManagerDTO.phone != null and userManagerDTO.phone != ''">
        AND u.phone LIKE CONCAT('%',#{userManagerDTO.phone},'%')
      </if>
      <if test="userManagerDTO.tagIds != null and userManagerDTO.tagIds.size() > 0">
        AND u.user_id IN
        (
        SELECT DISTINCT(utg.user_id) FROM `user_tag_user` utg
        WHERE utg.user_tag_id IN
        <foreach collection="userManagerDTO.tagIds" item="tagId" index="index" open="(" close=")" separator=",">
          #{tagId}
        </foreach>
        )
      </if>
      <if test="userManagerDTO.userIds != null and userManagerDTO.userIds.size() > 0">
        AND u.user_id IN
        <foreach collection="userManagerDTO.userIds" item="userId" open="(" close=")" separator=",">
          #{userId}
        </foreach>
      </if>
      <if test="userManagerDTO.createStartTime != null and userManagerDTO.createEndTime !=  null ">
        AND (u.create_time between #{userManagerDTO.createStartTime} and #{userManagerDTO.createEndTime})
      </if>
    </where>
    ORDER BY u.create_time DESC, u.user_id DESC
    LIMIT #{pageAdapter.begin} , #{pageAdapter.size}
    ) AS utemp
  </select>

  <update id="updateUserLevelByBuyVip">
    update user set vip_level = #{afterLevel},level_type = 1,vip_end_time = #{date} where user_id = #{userId}
  </update>
  <update id="updateUserTypeLevelByUserExtensionAndUserIds">
    UPDATE `user` u INNER JOIN `user_extension` ue SET u.level = ue.level,u.level_type = ue.level_type,u.vip_level= ue.vip_level
    WHERE u.user_id = ue.user_id AND
    u.user_id IN
    <foreach collection="userIds" item="userId" separator="," open="(" close=")">
      #{userId}
    </foreach>
  </update>
  <select id="getUserListByPhones" resultType="com.tmerclub.cloud.user.vo.UserVO" parameterType="java.util.List">
      select <include refid="Vo_Column_List"/> from user
      where phone in
      <foreach collection="phones" item="phone" separator="," open="(" close=")">
        #{phone}
      </foreach>
      order by user_id desc
    </select>

  <select id="getUserByCreateTimeRange" resultType="com.tmerclub.cloud.user.vo.UserVO">
    select user_id from user
    <where>
      (create_time between #{startDate} and #{endDate})
      <if test="status != null">
        and `status` = #{status}
      </if>
    </where>
  </select>
  <select id="getUserCountInfo" resultType="com.tmerclub.cloud.api.user.vo.MemberOverviewVO">
    SELECT
      count( DISTINCT u.user_id ) AS totalMember,
      count( DISTINCT CASE WHEN u.level_type = 1 THEN u.user_id ELSE NULL END ) AS paidMember,
      count( DISTINCT CASE WHEN u.create_time &gt;= #{startTime} THEN u.user_id ELSE NULL END ) AS newMember
    FROM
      `user` u WHERE u.create_time &lt; #{endTime}
  </select>

  <select id="countUserByLevel" resultType="int">
    select ifnull(count(user_id),0) from `user` where level_type = #{levelType}
    <if test="levelType == 0">
      and `level` = #{level}
    </if>
    <if test="levelType == 1">
      and `vip_level` = #{level}
    </if>
  </select>

  <select id="selectMemberByEndTime" resultType="com.tmerclub.cloud.user.vo.UserVO">
    select <include refid="Vo_Column_List"/> from user u
    where level_type = 1
    and vip_end_time &lt; #{endOfDay}
  </select>

  <select id="getUserIdListByLevel" resultType="java.lang.Long">
    select user_id from user
    <where>
      `status` = 1
      <if test="levelType != -1">
        and level_type = #{levelType}
      </if>
    </where>
  </select>
  <select id="getUserByParam" resultType="com.tmerclub.cloud.api.user.vo.UserApiVO">
    select user_id, nick_name from user
    <where>
      <if test="userApiVO.nickName != null and userApiVO.nickName != ''">
        nick_name LIKE CONCAT('%',#{userApiVO.nickName},'%')
      </if>
      <if test="userApiVO.userMobile != null and userApiVO.userMobile != ''">
        AND phone = #{userApiVO.userMobile}
      </if>
      <if test="userApiVO.status != null">
        AND status = #{userApiVO.status}
      </if>
    </where>
  </select>

  <select id="listUser" resultType="com.tmerclub.cloud.user.model.User">
    SELECT
      *
    FROM
      user
    WHERE
      `status` != -1
  </select>

  <delete id="deleteById">
    delete from `user` where user_id = #{userId}
  </delete>

  <select id="countNewUserByTime" resultType="java.lang.Integer">
    SELECT COUNT(user_id) FROM `user`
    <where>
      <if test="startTime != null">
        create_time &gt;= #{startTime}
      </if>
      <if test="startTime != null">
        and create_time &lt; #{endTime}
      </if>
    </where>
  </select>

  <select id="listNewUserIdByTime" resultType="java.lang.Long">
    SELECT user_id FROM `user`
    <where>
      <if test="startTime != null">
        create_time &gt;= #{startTime}
      </if>
      <if test="startTime != null">
        and create_time &lt; #{endTime}
      </if>
    </where>
  </select>

  <select id="listUserByUserIds" resultType="com.tmerclub.cloud.user.vo.UserVO">
    SELECT u.user_id,u.create_time,u.level_type,ul.vipStartTime FROM `user` u
    LEFT JOIN
    (
      SELECT user_id, MAX(create_time) AS vipStartTime FROM user_level_log
      WHERE level_io_type = 1 AND level_change_reason BETWEEN 3 AND 4 AND user_id IN
      <foreach collection="userIds" item="userId" separator="," open="(" close=")">
        #{userId}
      </foreach>
      GROUP BY user_id
    ) AS ul ON u.user_id = ul.user_id
    WHERE u.user_id IN
    <foreach collection="userIds" item="userId" separator="," open="(" close=")">
      #{userId}
    </foreach>
  </select>

  <select id="countUserNumByType" resultType="com.tmerclub.cloud.api.user.vo.MemberTrendRespVO">
    SELECT COUNT(*) memberNum, (
        SELECT COUNT(DISTINCT user_id)
        FROM user_level_log
        WHERE level_io_type = 1 AND level_change_reason BETWEEN 3 AND 4 AND after_level_type = 1 AND is_payed = 1 AND create_time &gt;= #{startTime}
      ) vipMemberNum
    FROM `user`
    WHERE create_time &gt;= #{startTime} AND `status` > -1

  </select>

  <select id="statisticsUserNum" resultType="com.tmerclub.cloud.api.user.vo.MemberCountVO">
    SELECT COUNT(*) totalMember, (
            SELECT COUNT(DISTINCT user_id)
            FROM user_level_log
            WHERE level_io_type = 1 # 变更类型为升级
            AND level_change_reason BETWEEN 3 AND 4 # 等级变更原因为 购买会员和续费会员
            AND before_level_type = 0  # 变更之前为普通会员
            AND after_level_type = 1  # 变更之前为付费会员
            AND is_payed = 1 # 已支付
            AND create_time &gt;= #{startTime} AND create_time &lt; #{endTime}
        ) newPaidMember,
        COUNT(IF(create_time &gt;= #{startTime} AND create_time &lt; #{endTime}, 1, NULL)) newMember,
        COUNT(IF(level_type = 1, 1, NULL)) paidMember
    FROM `user`
    WHERE create_time &lt;= #{endTime} AND `status` > -1
  </select>

  <select id="getInitialRegistrationTime" resultType="java.util.Date">
    SELECT create_time FROM `user` ORDER BY create_time ASC LIMIT 0,1
  </select>

  <select id="listUserByMobile" resultType="com.tmerclub.cloud.api.user.vo.UserApiVO">
    select user_id, status from `user` where phone = #{mobile}
  </select>

  <select id="countUserByPhone" resultType="int">
    SELECT COUNT(user_id) FROM `user` WHERE `status` BETWEEN 0 AND 1 AND phone = #{phone}
  </select>
</mapper>
