<?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.usky.eg.mapper.EgDevicePersonBindMapper">

    <resultMap id="BaseResultMap" type="com.usky.eg.domain.EgDevicePersonBind">
        <result column="device_id" property="deviceId" />
        <result column="person_id" property="personId" />
        <result column="is_login_notify" property="isLoginNotify" />
    </resultMap>

    <select id="selectByDeviceIds" resultMap="BaseResultMap">
        select device_id, person_id, is_login_notify
        from eg_device_person_bind
        <where>
            <if test="deviceIds != null and deviceIds.size() > 0">
                and device_id in
                <foreach collection="deviceIds" item="id" open="(" separator="," close=")">
                    #{id}
                </foreach>
            </if>
        </where>
    </select>

    <select id="countByDeviceId" resultType="java.lang.Integer">
        select count(1)
        from eg_device_person_bind
        where device_id = #{deviceId}
    </select>

    <!--
        通过 sys_user_person 关联 sys_person，最终关联到 eg_device_person_bind，判断某个用户是否对某设备有绑定关系
        假定字段：sys_user_person(user_id, person_id)，sys_person(id)，eg_device_person_bind(person_id, device_id)
    -->
    <select id="countByUserIdAndDeviceId" resultType="java.lang.Integer">
        select count(1)
        from eg_device_person_bind b
                 join sys_person p on b.person_id = p.id
                 join sys_user_person up on up.person_id = p.id
        where up.user_id = #{userId}
          and b.device_id = #{deviceId}
    </select>

    <!-- 根据用户ID查询其绑定的设备ID列表 -->
    <select id="selectDeviceIdsByUserId" resultType="java.lang.Integer">
        select distinct b.device_id
        from eg_device_person_bind b
                 join sys_person p on b.person_id = p.id
                 join sys_user_person up on up.person_id = p.id
        where up.user_id = #{userId}
    </select>

    <delete id="deleteByDeviceId">
        delete from eg_device_person_bind
        where device_id = #{deviceId}
    </delete>

    <insert id="insert" parameterType="com.usky.eg.domain.EgDevicePersonBind">
        insert into eg_device_person_bind (device_id, person_id, is_login_notify)
        values (#{deviceId}, #{personId}, #{isLoginNotify})
    </insert>

</mapper>
