<?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.ai.mapper.AiDeviceMapper">

    <insert id="insertDevice" useGeneratedKeys="false">
        INSERT INTO ai_device (board_id, board_ip, description, status, create_time, create_by, update_time, update_by)
        VALUES (#{boardId}, #{boardIp}, #{description}, #{status}, #{createTime}, #{createBy}, #{updateTime}, #{updateBy})
    </insert>

    <insert id="saveOrUpdateDevice" useGeneratedKeys="false">
        INSERT INTO ai_device (board_id, board_ip, description, status, create_time, create_by, update_time, update_by)
        VALUES (#{boardId}, #{boardIp}, #{description}, #{status}, #{createTime}, #{createBy}, #{updateTime}, #{updateBy})
            ON DUPLICATE KEY UPDATE
                                 board_ip = VALUES(board_ip),
                                 description = VALUES(description),
                                 status = VALUES(status),
                                 update_time = VALUES(update_time),
                                 update_by = VALUES(update_by)
    </insert>

    <update id="updateDevice">
        UPDATE ai_device
        SET board_ip = #{boardIp},
            description = #{description},
            status = #{status},
            update_time = #{updateTime},
            update_by = #{updateBy}
        WHERE board_id = #{boardId}
    </update>

    <update id="updateDeviceStatus">
        UPDATE ai_device SET status = 0 WHERE update_time &lt;= NOW() - INTERVAL 10 MINUTE
    </update>

    <select id="getDevices" resultType="com.usky.ai.domain.AiDevice">
        SELECT * FROM ai_device
        <where>
            <if test="boardId != null and boardId != ''">
                AND board_id = #{boardId}
            </if>
        </where>
        LIMIT #{limit} OFFSET #{offset}
    </select>

    <select id="getTotalDevices" resultType="long">
        SELECT COUNT(*) FROM ai_device
        <where>
            <if test="boardId != null and boardId != ''">
                AND board_id = #{boardId}
            </if>
        </where>
    </select>

    <delete id="deleteDevice">
        DELETE FROM ai_device WHERE board_id = #{boardId}
    </delete>

    <select id="checkExists" resultType="boolean">
        SELECT COUNT(*) FROM ai_device
        WHERE board_id = #{boardId} OR board_ip = #{boardIp}
    </select>
</mapper>