<?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.github.wxiaoqi.security.admin.mapper.AppUserRelationMapper">


    <select id="selectByLeaderId" resultType="com.github.wxiaoqi.security.admin.entity.AppUserRelation">
        select `parent_id` as `parentId`,`user_id`as `userId`,`bind_time` as `bindTime` from `app_user_relation` where `parent_id`=#{leaderId} and `is_del`=0 order by `bind_time` DESC
    </select>

    <select id="countByParentId" resultType="Integer">
        select count(*)  from `app_user_relation` where
        `parent_id`=#{parentId} and `is_del`=0
         <if test="bindTime!='' and bindTime!=null and bindTime>0">
             and (is_forever=1 or bind_time>#{bindTime})
         </if>
    </select>

    <select id="selectByUserIds" resultType="com.github.wxiaoqi.security.admin.entity.AppUserRelation">
        select  `user_id`,`parent_id` from `app_user_relation` where  `is_del`=0 and `user_id` IN
        <foreach collection="userIds" item="userId" separator="," open="(" close=")">
           #{userId}
        </foreach>
    </select>

    <select id="selectCountByLeaderId" resultType="com.github.wxiaoqi.security.admin.entity.AppUserRelation">
        select * from   `app_user_relation` as `aur` inner join  `app_user_login` as `aul` on aul.id=aur.user_id where aur.is_del=0 and aul.isdel=0  and aur.parent_id=#{userId}
    </select>

    <select id="findAllRelations" resultType="com.github.wxiaoqi.security.admin.bo.UserBo">
        select  aur.parent_id as `leaderId`,aulp.username as `leaderPhone`,aulc.id as `userId`,aulc.username  as `phone`,
         IFNULL(audp.realname,audp.nickname) as `leaderName`,IFNULL(audc.realname,audc.nickname) as `name`,aupt.company_name as `companyName`
         from `app_user_relation` as aur
         left join `app_user_login` as aulp on aulp.id = aur.parent_id
         inner join `app_user_login` as aulc on aulc.id=aur.user_id
         left join `app_user_detail` as audp on audp.userid= aulp.id
         inner join `app_user_detail` as `audc` on audc.userid= aulc.id
         left join  `app_user_position_temp` as `aupt` on aupt.user_id = aulc.id
          where aur.is_del=0  and aulc.isdel=0
    </select>

    <select id="updateParentIdByUserId">
      update `app_user_relation` set `parent_id`=#{leaderId},`upd_time`=#{updTime}  where user_id=#{userId}
    </select>
</mapper>