<?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.reghao.tnb.user.app.db.mapper.UserContactMapper">
    <insert id="save" useGeneratedKeys="true" keyProperty="id">
        insert into user_contact
        (`friend_id`,`remark_name`,`status`,`owner`)
        values 
        (#{friendId},#{remarkName},#{status},#{owner})
    </insert>
    <insert id="saveAll" useGeneratedKeys="true" keyProperty="id">
        insert into user_contact
        (`friend_id`,`remark_name`,`status`,`owner`)
        values
        <foreach collection="list" item="item" index="index" separator=",">
            (#{item.friendId},#{item.remarkName},#{item.status},#{item.owner})
        </foreach>
    </insert>

    <update id="updateContactStatus">
        update user_contact
        set update_time=now(),`status`=#{status}
        where friend_id=#{userId}
    </update>
    <update id="updateFriendStatus">
        update user_contact
        set update_time=now(),`status`=#{status}
        where `owner`=#{owner} and friend_id=#{userId}
    </update>
    <update id="updateContactRemark">
        update user_contact
        set update_time=now(),`remark_name`=#{remarkName}
        where owner=#{owner} and friend_id=#{friendId}
    </update>

    <select id="findByOwner" resultType="cn.reghao.tnb.user.app.model.po.UserContact">
        select *
        from user_contact
        where owner=#{owner}
    </select>
    <select id="findByOwnerAndFriendId" resultType="cn.reghao.tnb.user.app.model.po.UserContact">
        select *
        from user_contact
        where `status`=1 and owner=#{owner} and friend_id=#{friendId}
    </select>
    <select id="findOnlineFriends" resultType="java.lang.Long">
        select friend_id
        from user_contact
        where `owner`=#{owner} and `status`=1
    </select>
    <select id="findFriendsByNotInGroup" resultType="cn.reghao.tnb.user.app.model.po.UserContact">
        select *
        from user_contact contact
        where contact.user_id=#{userId} and contact.friend_id not in
        (select user_id from group_member where group_id=#{groupId} and user_id!=#{userId})
    </select>
</mapper>
