<?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="cn.wisenergy.mapper.UsersMapper">
    <resultMap id="userMap" type="cn.wisenergy.model.app.Users">
        <id column="id" property="id"/>
        <result column="parent_id" property="parentId"/>
        <result column="path" property="path"/>
        <result column="rank" property="rank"/>
        <result column="country_code" property="countryCode"/>
        <result column="phone" property="phone"/>
        <result column="password" property="password"/>
        <result column="fund_pass" property="fundPass"/>
        <result column="nickname" property="nickname"/>
        <result column="avatar" property="avatar"/>
        <result column="invite_code" property="inviteCode"/>
        <result column="token" property="token"/>
        <result column="hash" property="hash"/>
        <result column="level" property="level"/>
        <result column="now_level" property="nowLevel"/>
        <result column="grade" property="grade"/>
        <result column="status" property="status"/>
        <result column="fund_status" property="fundStatus"/>
        <result column="active" property="active"/>
        <result column="note" property="note"/>
        <result column="reg_time" property="regTime"/>
        <result column="reg_ip" property="regIp"/>
        <result column="reg_address" property="regAddress"/>
        <result column="did" property="did"/>
        <result column="read_time" property="readTime"/>
        <result column="start_at" property="startAt"/>
        <result column="expire_at" property="expireAt"/>
        <result column="proxy" property="proxy"/>
        <result column="is_work" property="isWork"/>
        <result column="work_at" property="workAt"/>
        <result column="created_at" property="createdAt"/>
        <result column="updated_at" property="updatedAt"/>
    </resultMap>

    <sql id="table">
        users
    </sql>

    <sql id="cols_all">
        id,
        <include refid="cols_exclude_id"/>
    </sql>

    <sql id="cols_exclude_id">
        parent_id,path,rank,country_code,phone,password,fund_pass,nickname, avatar,invite_code,token,hash,`level`,now_level,
        grade,status,fund_status,active,note,reg_time,reg_ip,reg_address,did,read_time,start_at,expire_at,proxy,is_work,
        work_at,created_at,updated_at
    </sql>

    <sql id="vals">
        #{parentId},#{path},#{rank},#{countryCode},#{phone},#{password},#{fundPass},#{nickname},#{avatar},#{inviteCode},
        #{token},#{hash},#{level},#{nowLevel},#{grade},#{status},#{fundStatus},#{active},#{note},#{regTime},#{regIp},
        #{regAddress},#{did},#{readTime},#{startAt},#{expireAt},#{proxy},#{isWork},#{workAt},now(),now()
    </sql>

    <sql id="updateCondition">
        <if test="parentId != null">parent_id = #{parentId},</if>
        <if test="path != null">path =#{path},</if>
        <if test="rank != null">rank =#{rank},</if>
        <if test="countryCode != null">country_code =#{countryCode},</if>
        <if test="phone != null">phone =#{phone},</if>
        <if test="password != null">password = #{password},</if>
        <if test="fundPass != null">fund_pass =#{fundPass},</if>
        <if test="nickname != null">nickname =#{nickname},</if>
        <if test="avatar != null">avatar =#{avatar},</if>
        <if test="inviteCode != null">invite_code = #{inviteCode},</if>
        <if test="token != null">token = #{token},</if>
        <if test="hash != null">hash =#{hash},</if>
        <if test="level != null">`level` =#{level},</if>
        <if test="nowLevel != null">now_level =#{nowLevel},</if>
        <if test="grade != null">grade =#{grade},</if>
        <if test="status != null">status = #{status},</if>
        <if test="fundStatus != null">fund_status =#{fundStatus},</if>
        <if test="active != null">active =#{active},</if>
        <if test="note != null">note =#{note},</if>
        <if test="regTime != null">reg_time = #{regTime},</if>
        <if test="regIp != null">reg_ip = #{regIp},</if>
        <if test="regAddress != null">reg_address =#{regAddress},</if>
        <if test="did != null">did = #{did},</if>
        <if test="readTime != null">read_time =#{readTime},</if>
        <if test="startAt != null">start_at =#{startAt},</if>
        <if test="expireAt != null">expire_at =#{expireAt},</if>
        <if test="proxy != null">proxy = #{proxy},</if>
        <if test="isWork != null">is_work = #{isWork},</if>
        <if test="workAt != null">work_at = #{workAt},</if>
        update_time =now()
    </sql>

    <sql id="criteria">
        <if test="id != null">id = #{id}</if>
        <if test="parentId != null">and parent_id = #{parentId}</if>
        <if test="path != null">and path =#{path}</if>
        <if test="rank != null">and rank =#{rank}</if>
        <if test="countryCode != null">and country_code =#{countryCode}</if>
        <if test="phone != null">and phone =#{phone}</if>
        <if test="password != null">and password = #{password}</if>
        <if test="fundPass != null">and fund_pass =#{fundPass}</if>
        <if test="nickname != null">and nickname =#{nickname}</if>
        <if test="avatar != null">and avatar =#{avatar}</if>
        <if test="inviteCode != null">and invite_code = #{inviteCode}</if>
        <if test="token != null">and token = #{token}</if>
        <if test="hash != null">and hash =#{hash}</if>
        <if test="level != null">and `level` =#{level}</if>
        <if test="nowLevel != null">and now_level =#{nowLevel}</if>
        <if test="grade != null">and grade =#{grade}</if>
        <if test="status != null">and status = #{status}</if>
        <if test="fundStatus != null">and fund_status =#{fundStatus}</if>
        <if test="active != null">and active =#{active}</if>
        <if test="note != null">and note =#{note}</if>
        <if test="regTime != null">and reg_time = #{regTime}</if>
        <if test="regIp != null">and reg_ip = #{regIp}</if>
        <if test="regAddress != null">and reg_address =#{regAddress}</if>
        <if test="did != null">and did = #{did}</if>
        <if test="readTime != null">and read_time =#{readTime}</if>
        <if test="startAt != null">and start_at =#{startAt}</if>
        <if test="expireAt != null">and expire_at =#{expireAt}</if>
        <if test="proxy != null">and proxy = #{proxy}</if>
        <if test="isWork != null">and is_work = #{isWork}</if>
        <if test="workAt != null">and work_at = #{workAt}</if>
        <if test="createdAt != null">and created_at &gt;= #{createdAt}</if>
        <if test="updatedAt != null">and #{updatedAt} &gt;= updated_at</if>
    </sql>


    <insert id="add" parameterType="cn.wisenergy.model.app.Users" keyProperty="id" useGeneratedKeys="true">
        insert into
        <include refid="table"/>
        (<include refid="cols_exclude_id"/>)
        value(
        <include refid="vals"/>
        )
    </insert>

    <update id="edit" parameterType="cn.wisenergy.model.app.Users">
        UPDATE
        <include refid="table"/>
        <set>
            <include refid="updateCondition"/>
        </set>
        <where>
            id = #{id}
        </where>
    </update>

    <delete id="delById" parameterType="java.lang.Integer">
        delete from
        <include refid="table"/>
        where id = #{id}
    </delete>

    <select id="getLastUser" resultType="cn.wisenergy.model.vo.UserVo">
        select u.id as userId,u.parent_id as parentId,a.real_name as realName,a.id_number as idNumber,a.phone as phone,
        a.total_recharge as totalRecharge,a.total_withdrawal as totalWithdrawal,a.rank as rank,a.bottom as bottom,
        a.total_people as totalPeople,a.buy_total as buyTotal,a.sale_total as saleTotal
        from users u left join user_data a
        on u.id=a.user_id
		where u.parent_id =#{parentId}
    </select>

    <select id="getById" resultType="cn.wisenergy.model.app.Users">
        select
        <include refid="cols_all"/>
        from
        <include refid="table"/>
        <where>
            id=#{id}
        </where>
    </select>


    <select id="getLevelAndTotal" resultType="cn.wisenergy.model.dto.UsersInfoDto">
	    SELECT u1.rank,u2.count
        FROM
        users u1,(select count(*) 'count',max(LENGTH(path)) 'maxrank'
        from users
        where  path like CONCAT((SELECT path FROM users WHERE id=#{userId}), '%')) u2
        WHERE  path like CONCAT((SELECT path FROM users WHERE id=#{userId}), '%')
                    and LENGTH(path) = u2.maxrank LIMIT 1
    </select>

    <select id="getTotal" resultType="java.lang.Integer">
        select count(*)
        from
        <include refid="table"/>
        <where>
            FIND_IN_SET(#{id},path)
        </where>
    </select>


    <!--*****************************************chenqi***************************************-->
    <select id="getDownLevelAndTotalPeopleByUserId" resultType="cn.wisenergy.model.dto.UsersInfoDto">
         SELECT
	MAX(rank) 'bottom',
	count(*)-1 'totalPeople'
FROM
	users
WHERE
	path like CONCAT((SELECT path FROM users WHERE id=#{userId}), '%')



    </select>

    <select id="getDownUsersById" resultType="cn.wisenergy.model.dto.UserSimpleInfoDto">
    SELECT
	u.id 'userId',
	a.real_name ,
	u.rank,
	a.id_number,
	u.phone,
	if(ur.totalRecharge is NULL,0, round(ur.totalRecharge,2)) 'totalRecharge',
	if(uw.totalWithdrawal is NULL,0,round(uw.totalWithdrawal,2)) 'totalWithdrawal',
	u.parent_id,
	aa.real_name 'parentName'
	FROM users u
	LEFT JOIN actives a ON u.id = a.user_id
	LEFT JOIN actives aa ON u.parent_id = aa.user_id
	LEFT JOIN (
            SELECT user_id,round(SUM(amount),2) 'totalRecharge'
FROM user_recharge
WHERE user_id in (SELECT id from users WHERE parent_id = #{userId}) and status = 1
GROUP BY user_id
        ) ur ON ur.user_id=u.id
    LEFT JOIN (
            SELECT user_id,round(SUM(amount),2) 'totalWithdrawal'
FROM user_withdraws
WHERE user_id in (SELECT id from users WHERE parent_id = #{userId}) and status = 1
GROUP BY user_id
        ) uw ON uw.user_id=u.id
        WHERE
            u.parent_id = #{userId} or u.id = #{userId}
        ORDER BY u.id
    </select>

    <select id="getAllUserData" resultType="cn.wisenergy.model.dto.UserDto">
        select id as userId,rank,phone
        from
        <include refid="table"/>
        limit #{startNo},#{endNo}
    </select>

    <select id="getUserData" resultType="cn.wisenergy.model.vo.UserVo">
        select u.id as userId,u.parent_id as parentId,a.real_name as realName,a.id_number as idNumber,a.phone as phone,
        a.total_recharge as totalRecharge,a.total_withdrawal as totalWithdrawal,a.rank as rank,a.bottom as bottom,
        a.total_people as totalPeople,a.buy_total as buyTotal,a.sale_total as saleTotal
        from users u left join user_data a
        on u.id=a.user_id
        where u.id IN
        <foreach collection="list" index="index" item="id" separator="," open="(" close=")">
            #{id}
        </foreach>
        order by u.id
    </select>

</mapper>