<?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.aiotagro.cattletrade.business.mapper.JbqServerMapper">

    <!-- 通用查询映射结果 -->
    <resultMap id="BaseResultMap" type="com.aiotagro.cattletrade.business.entity.JbqServer">
        <id column="id" property="id" />
        <result column="device_id" property="deviceId" />
        <result column="device_voltage" property="deviceVoltage" />
        <result column="device_temp" property="deviceTemp" />
        <result column="latitude" property="latitude" />
        <result column="longitude" property="longitude" />
        <result column="walk_steps" property="walkSteps" />
        <result column="y_walk_steps" property="yWalkSteps" />
        <result column="create_time" property="createTime" />
        <result column="create_by" property="createBy" />
        <result column="update_time" property="updateTime" />
        <result column="update_by" property="updateBy" />
        <result column="source_id" property="sourceId" />
    </resultMap>

    <!-- 通用查询结果列 -->
    <sql id="Base_Column_List">
        id, device_id, device_voltage, device_temp, latitude, longitude, walk_steps, y_walk_steps, create_time, create_by, update_time, update_by, source_id
    </sql>
    <select id="serverList" resultType="com.aiotagro.cattletrade.business.vo.ServerClientVo">
        SELECT
        server.id AS id,
        server.device_id AS deviceId,
        server.device_voltage AS deviceVoltage,
        server.device_temp AS deviceTemp,
        COALESCE(del.delivery_number, '未分配') AS deliveryNumber,
        COALESCE(del.license_plate, '未分配') AS licensePlate,
        del.create_time AS deliveryCreateTime,
        CASE
        WHEN TIMESTAMPDIFF(MINUTE, server.update_time, NOW()) &lt;= 60 THEN '在线状态'
        ELSE '离线状态'
        END AS onlineStatusDesc
        FROM
        jbq_server server
        LEFT JOIN
        (SELECT 
            device_id, 
            delivery_id,
            ROW_NUMBER() OVER (PARTITION BY device_id ORDER BY id DESC) as rn
         FROM delivery_device 
         WHERE device_type = 1) dd 
        ON server.device_id = dd.device_id AND dd.rn = 1
        LEFT JOIN
        delivery del ON dd.delivery_id = del.id
        WHERE 1=1
        <if test="item.deviceId != null and item.deviceId != ''">
            AND server.device_id = #{item.deviceId}
        </if>
        ORDER BY server.id ASC
    </select>

</mapper>
