<?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="net.northking.cctp.device.db.dao.CdDeviceUsageLogDao">
  <select id="queryPages" resultMap="BaseResultMap" parameterType="net.northking.cctp.device.dto.device.DeviceLogDto">
    SELECT
    log.id
    ,log.device_id
    ,log.device_type
    ,log.start_time
    ,log.end_time
    ,log.usage_log
    ,log.user_by
    ,log.user_ip
    ,log.created_by
    ,log.created_time
    ,log.updated_by
    ,log.updated_time
    FROM cd_device_usage_log log
    LEFT JOIN cd_device_tenant cdt ON log.device_id = cdt.id
    <trim prefix="WHERE" prefixOverrides="AND" >
      DATE_SUB(CURDATE(),INTERVAL 30 DAY) <![CDATA[<=]]> DATE(created_time)
      <if test="tenantId != null">
        AND cdt.tenant_id = #{tenantId,jdbcType=VARCHAR}
      </if>
      <if test="deviceId != null">
        AND log.device_id = #{deviceId,jdbcType=VARCHAR}
      </if>
    </trim>
    order by log.created_time desc
  </select>


  <select id="queryCreatedBy" parameterType="string" resultType="string">
    SELECT user_by
    FROM cd_device_usage_log
    WHERE
    start_time = (
    SELECT MAX(start_time)
    FROM cd_device_usage_log
    WHERE device_id = #{deviceId,jdbcType=VARCHAR} AND end_time IS NULL)
    AND device_id = #{deviceId,jdbcType=VARCHAR}
    AND end_time IS NULL
  </select>

  <delete id="deleteUsageLog">
    DELETE
    FROM cd_device_usage_log
    WHERE DATE_SUB(CURDATE(), INTERVAL 30 DAY) > DATE(created_time)
  </delete>

  <!-- 请在本文件内添加自定义SQL语句 -->
</mapper>